2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.pap.xacml.rest;
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;
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.Scanner;
48 import java.util.UUID;
49 import java.util.concurrent.CopyOnWriteArrayList;
51 import javax.persistence.EntityManagerFactory;
52 import javax.persistence.Persistence;
53 import javax.persistence.PersistenceException;
54 import javax.servlet.Servlet;
55 import javax.servlet.ServletConfig;
56 import javax.servlet.ServletException;
57 import javax.servlet.annotation.WebInitParam;
58 import javax.servlet.annotation.WebServlet;
59 import javax.servlet.http.HttpServlet;
60 import javax.servlet.http.HttpServletRequest;
61 import javax.servlet.http.HttpServletResponse;
63 import org.apache.commons.io.IOUtils;
64 import org.onap.policy.common.ia.IntegrityAudit;
65 import org.onap.policy.common.im.AdministrativeStateException;
66 import org.onap.policy.common.im.ForwardProgressException;
67 import org.onap.policy.common.im.IntegrityMonitor;
68 import org.onap.policy.common.im.IntegrityMonitorProperties;
69 import org.onap.policy.common.im.StandbyStatusException;
70 import org.onap.policy.common.logging.ONAPLoggingContext;
71 import org.onap.policy.common.logging.ONAPLoggingUtils;
72 import org.onap.policy.common.logging.eelf.MessageCodes;
73 import org.onap.policy.common.logging.eelf.PolicyLogger;
74 import org.onap.policy.common.logging.flexlogger.FlexLogger;
75 import org.onap.policy.common.logging.flexlogger.Logger;
76 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
77 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
78 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
79 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
80 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
81 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
82 import org.onap.policy.rest.XACMLRest;
83 import org.onap.policy.rest.XACMLRestProperties;
84 import org.onap.policy.rest.dao.PolicyDBException;
85 import org.onap.policy.utils.PolicyUtils;
86 import org.onap.policy.xacml.api.XACMLErrorConstants;
87 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
88 import org.onap.policy.xacml.api.pap.OnapPDP;
89 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
90 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
91 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
92 import org.onap.policy.xacml.std.pap.StdPDP;
93 import org.onap.policy.xacml.std.pap.StdPDPGroup;
94 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
95 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
96 import org.onap.policy.xacml.std.pap.StdPDPStatus;
98 import com.att.research.xacml.api.pap.PAPException;
99 import com.att.research.xacml.api.pap.PDPPolicy;
100 import com.att.research.xacml.api.pap.PDPStatus;
101 import com.att.research.xacml.util.FactoryException;
102 import com.att.research.xacml.util.XACMLProperties;
103 import com.fasterxml.jackson.databind.ObjectMapper;
104 import com.google.common.base.Splitter;
107 * Servlet implementation class XacmlPapServlet
110 description = "Implements the XACML PAP RESTful API.",
111 urlPatterns = { "/" },
114 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
116 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
117 private static final long serialVersionUID = 1L;
118 private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
119 // audit (transaction) LOGGER
120 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
121 //Persistence Unit for JPA
122 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
123 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
125 private static final String ENVIRONMENT_HEADER = "Environment";
127 * List of Admin Console URLs.
128 * Used to send notifications when configuration changes.
130 * The CopyOnWriteArrayList *should* protect from concurrency errors.
131 * This list is seldom changed but often read, so the costs of this approach make sense.
133 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
135 private static String configHome;
136 private static String actionHome;
138 * This PAP instance's own URL.
139 * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
141 private static String papURL = null;
142 // The heartbeat thread.
143 private static Heartbeat heartbeat = null;
144 private static Thread heartbeatThread = null;
145 //The entity manager factory for JPA access
146 private static EntityManagerFactory emf;
147 private static PolicyDBDao policyDBDao;
149 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
151 private static PAPPolicyEngine papEngine = null;
153 * These are the parameters needed for DB access from the PAP
155 private static int papIntegrityAuditPeriodSeconds = -1;
156 private static String papDbDriver = null;
157 private static String papDbUrl = null;
158 private static String papDbUser = null;
159 private static String papDbPassword = null;
160 private static String papResourceName = null;
161 private static String[] papDependencyGroupsFlatArray = null;
162 private static String environment = null;
163 private static String pdpFile = null;
165 private transient IntegrityMonitor im;
166 private transient IntegrityAudit ia;
168 //MicroService Model Properties
169 private static String msOnapName;
170 private static String msPolicyName;
172 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
173 * this servlet starts. Its configurable by the admin.
175 private static transient Thread initiateThread = null;
176 private transient ONAPLoggingContext baseLoggingContext = null;
179 * @see HttpServlet#HttpServlet()
181 public XACMLPapServlet() {
186 * @see Servlet#init(ServletConfig)
188 public void init(ServletConfig config) throws ServletException {
191 baseLoggingContext = new ONAPLoggingContext();
192 // fixed data that will be the same in all logging output goes here
194 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
195 baseLoggingContext.setServer(hostname);
196 } catch (UnknownHostException e) {
197 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
200 XACMLRest.xacmlInit(config);
201 // Load the properties
202 XACMLRest.loadXacmlProperties(null, null);
204 * Retrieve the property values
206 setCommonProperties();
207 String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
208 if(papSiteName == null){
209 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
210 throw new PAPException("papSiteName is null");
212 String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
213 if(papNodeType == null){
214 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
215 throw new PAPException("papNodeType is null");
217 //Integer will throw an exception of anything is missing or unrecognized
218 int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
219 int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
220 int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
221 //Boolean will default to false if anything is missing or unrecognized
222 boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
223 boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
224 String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
225 if(papDependencyGroups == null){
226 throw new PAPException("papDependencyGroups is null");
228 setPAPDependencyGroups(papDependencyGroups);
229 //Integer will throw an exception of anything is missing or unrecognized
230 int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
231 int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
232 int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
233 int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
234 LOGGER.debug("\n\n\n**************************************"
235 + "\n*************************************"
237 + "\n papDbDriver = " + papDbDriver
238 + "\n papDbUrl = " + papDbUrl
239 + "\n papDbUser = " + papDbUser
240 + "\n papDbPassword = " + papDbPassword
241 + "\n papTransWait = " + papTransWait
242 + "\n papTransTimeout = " + papTransTimeout
243 + "\n papAuditTimeout = " + papAuditTimeout
244 + "\n papAuditFlag = " + papAuditFlag
245 + "\n papFileSystemAudit = " + papFileSystemAudit
246 + "\n papResourceName = " + papResourceName
247 + "\n fpMonitorInterval = " + fpMonitorInterval
248 + "\n failedCounterThreshold = " + failedCounterThreshold
249 + "\n testTransInterval = " + testTransInterval
250 + "\n writeFpcInterval = " + writeFpcInterval
251 + "\n papSiteName = " + papSiteName
252 + "\n papNodeType = " + papNodeType
253 + "\n papDependencyGroupsList = " + papDependencyGroups
254 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
255 + "\n\n*************************************"
256 + "\n**************************************");
257 // Pull custom persistence settings
258 Properties properties;
260 properties = XACMLProperties.getProperties();
261 LOGGER.debug("\n\n\n**************************************"
262 + "\n**************************************"
264 + "properties = " + properties
265 + "\n\n**************************************");
266 } catch (IOException e) {
267 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
268 + "XACMLProperties.getProperties()");
269 throw new ServletException(e.getMessage(), e.getCause());
271 // Create an IntegrityMonitor
272 im = IntegrityMonitor.getInstance(papResourceName,properties);
273 // Create an IntegrityAudit
274 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
275 ia.startAuditThread();
276 // Create the entity manager factory
278 // we are about to call the PDPs and give them their configuration.
279 // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
280 setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
281 //Create the policyDBDao
283 // Load our PAP engine, first create a factory
284 ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
285 // The factory knows how to go about creating a PAP Engine
286 setPAPEngine((PAPPolicyEngine) factory.newEngine());
287 PolicyDBDaoTransaction addNewGroup = null;
288 if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
290 addNewGroup = policyDBDao.getNewTransaction();
291 OnapPDPGroup group = papEngine.getDefaultGroup();
292 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
293 "automaticallyAdded");
294 addNewGroup.commitTransaction();
295 addNewGroup = policyDBDao.getNewTransaction();
296 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
297 addNewGroup.commitTransaction();
298 } catch (Exception e) {
299 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
300 " Error creating new default group in the database");
301 if (addNewGroup != null) {
302 addNewGroup.rollbackTransaction();
306 policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
307 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
309 * Auditing the local File System groups to be in sync with the Database
312 //get an AuditTransaction to lock out all other transactions
313 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
315 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
316 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
317 //get the current filesystem group and update from the database if needed
318 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
319 StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
320 if(updatedGroup!=null) {
321 papEngine.updateGroup(updatedGroup);
323 LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
325 //release the transaction lock
329 // Sanity check for URL.
330 if (XACMLPapServlet.papURL == null) {
331 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
333 // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
334 // to all its known PDP nodes.
335 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
336 startInitiateThreadService(new Thread(this));
338 // After startup, the PAP does Heartbeat's to each of the PDPs periodically
339 startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));
341 } catch (FactoryException | PAPException e) {
342 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
343 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
344 } catch (Exception e) {
345 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
346 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
350 private static void startInitiateThreadService(Thread thread) {
351 initiateThread = thread;
352 initiateThread.start();
355 private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) {
357 mapper.writeValue(response.getOutputStream(), value);
358 } catch (Exception e) {
363 private static void startHeartBeatService(Heartbeat heartbeat) {
364 XACMLPapServlet.heartbeat = heartbeat;
365 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
366 XACMLPapServlet.heartbeatThread.start();
369 private static void setPolicyDBDao() throws ServletException {
371 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
372 } catch (Exception e) {
373 throw new ServletException("Unable to Create Policy DBDao Instance",e);
377 private static void setEMF(Properties properties) throws ServletException {
378 emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
380 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
382 throw new ServletException("Unable to create Entity Manager Factory");
386 private static void setPAPURL(String papURL) {
387 XACMLPapServlet.papURL = papURL;
390 private static void setPAPEngine(PAPPolicyEngine newEngine) {
391 XACMLPapServlet.papEngine = newEngine;
394 private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
396 //Now we have flattened the array into a simple comma-separated list
397 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
398 //clean up the entries
399 for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
400 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
403 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
404 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
407 String msg = "integrity_audit_period_seconds ";
408 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
409 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
413 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
414 throw new PAPException(e);
418 private static void setCommonProperties() throws PAPException {
421 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
422 if(papDbDriver == null){
423 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
424 throw new PAPException("papDbDriver is null");
426 setPapDbDriver(papDbDriver);
427 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
428 if(papDbUrl == null){
429 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
430 throw new PAPException("papDbUrl is null");
432 setPapDbUrl(papDbUrl);
433 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
434 if(papDbUser == null){
435 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
436 throw new PAPException("papDbUser is null");
438 setPapDbUser(papDbUser);
439 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
440 if(papDbPassword == null){
441 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
442 throw new PAPException("papDbPassword is null");
444 setPapDbPassword(papDbPassword);
445 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
446 if(papResourceName == null){
447 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
448 throw new PAPException("papResourceName is null");
450 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
451 //Micro Service Properties
452 msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
453 setMsOnapName(msOnapName);
454 msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
455 setMsPolicyName(msPolicyName);
456 // PDPId File location
457 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
458 if (XACMLPapServlet.pdpFile == null) {
459 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
460 + XACMLRestProperties.PROP_PDP_IDFILE);
461 throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
466 * Thread used only during PAP startup to initiate change messages to all known PDPs.
467 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
471 // send the current configuration to all the PDPs that we know about
476 * @see Servlet#destroy()
478 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
479 * For now we assume that we do care.
482 public void destroy() {
483 // Make sure our threads are destroyed
484 if (XACMLPapServlet.heartbeatThread != null) {
485 // stop the heartbeat
487 if (XACMLPapServlet.heartbeat != null) {
488 XACMLPapServlet.heartbeat.terminate();
490 XACMLPapServlet.heartbeatThread.interrupt();
491 XACMLPapServlet.heartbeatThread.join();
492 } catch (InterruptedException e) {
493 XACMLPapServlet.heartbeatThread.interrupt();
494 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
497 if (initiateThread != null) {
499 initiateThread.interrupt();
500 initiateThread.join();
501 } catch (InterruptedException e) {
502 initiateThread.interrupt();
503 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
510 * - PDP nodes to register themselves with the PAP, and
511 * - Admin Console to make changes in the PDP Groups.
513 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
515 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
516 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
517 loggingContext.transactionStarted();
518 loggingContext.setServiceName("PAP.post");
519 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
520 UUID requestID = UUID.randomUUID();
521 loggingContext.setRequestID(requestID.toString());
522 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
524 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
526 PolicyDBDaoTransaction pdpTransaction = null;
527 loggingContext.metricStarted();
529 im.startTransaction();
530 loggingContext.metricEnded();
531 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
532 } catch (AdministrativeStateException ae){
533 String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
534 + " state of " + im.getStateManager().getAdminState()
535 + "\n Exception Message: " + ae.getMessage();
536 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
537 loggingContext.metricEnded();
538 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
539 loggingContext.transactionEnded();
540 PolicyLogger.audit("Transaction Failed - See Error.log");
541 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
543 }catch (StandbyStatusException se) {
544 String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
545 + " of " + im.getStateManager().getStandbyStatus()
546 + "\n Exception Message: " + se.getMessage();
547 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
548 loggingContext.metricEnded();
549 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
550 loggingContext.transactionEnded();
551 PolicyLogger.audit("Transaction Failed - See Error.log");
552 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
556 loggingContext.metricStarted();
557 XACMLRest.dumpRequest(request);
558 loggingContext.metricEnded();
559 PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
560 // since getParameter reads the content string, explicitly get the content before doing that.
561 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
562 request.getInputStream();
563 String groupId = request.getParameter("groupId");
564 String apiflag = request.getParameter("apiflag");
565 if(groupId != null) {
566 // Is this from the Admin Console or API?
567 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
568 // this is from the API so we need to check the client credentials before processing the request
569 if(!authorizeRequest(request)){
570 String message = "PEP not Authorized for making this Request!!";
571 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
572 loggingContext.transactionEnded();
573 PolicyLogger.audit("Transaction Failed - See Error.log");
574 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
579 loggingContext.metricStarted();
580 doACPost(request, response, groupId, loggingContext);
581 loggingContext.metricEnded();
582 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
583 loggingContext.transactionEnded();
584 PolicyLogger.audit("Transaction Ended Successfully");
588 // Request is from a PDP asking for its config.
589 loggingContext.setServiceName("PDP:PAP.register");
591 String id = this.getPDPID(request);
592 String jmxport = this.getPDPJMX(request);
593 LOGGER.info("Request(doPost) from PDP coming up: " + id);
594 // Get the PDP Object
595 OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
598 LOGGER.info("Unknown PDP: " + id);
600 if(CheckPDP.validateID(id)){
601 pdpTransaction = policyDBDao.getNewTransaction();
603 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
604 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
605 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) {
606 pdpTransaction.rollbackTransaction();
607 String message = "Failed to create new PDP for id: " + id;
608 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
609 loggingContext.transactionEnded();
610 PolicyLogger.audit("Transaction Failed - See Error.log");
611 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
615 // get the PDP we just created
617 pdp = XACMLPapServlet.papEngine.getPDP(id);
618 }catch(PAPException e){
622 if(pdpTransaction != null){
623 pdpTransaction.rollbackTransaction();
625 String message = "Failed to create new PDP for id: " + id;
626 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
627 loggingContext.transactionEnded();
628 PolicyLogger.audit("Transaction Failed - See Error.log");
629 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
634 String message = "PDP is Unauthorized to Connect to PAP: "+ id;
635 loggingContext.transactionEnded();
636 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
637 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
638 PolicyLogger.audit("Transaction Failed - See Error.log");
643 loggingContext.metricStarted();
644 pdpTransaction.commitTransaction();
645 loggingContext.metricEnded();
646 PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
647 } catch(Exception e){
648 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
651 if (jmxport != null && jmxport != ""){
653 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
654 }catch(NumberFormatException e){
658 // Get the PDP's Group
659 OnapPDPGroup group =null;
661 group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
662 }catch(PAPException e){
666 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
667 loggingContext.transactionEnded();
668 PolicyLogger.audit("Transaction Failed - See Error.log");
669 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
673 // Determine what group the PDP node is in and get
674 // its policy/pip properties.
675 Properties policies = group.getPolicyProperties();
676 Properties pipconfig = group.getPipConfigProperties();
677 // Get the current policy/pip configuration that the PDP has
678 Properties pdpProperties = new Properties();
680 pdpProperties.load(request.getInputStream());
681 }catch(IOException e){
684 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
685 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
686 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
687 // Validate the node's properties
688 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
689 // Send back current configuration
690 if (isCurrent == false) {
691 // Tell the PDP we are sending back the current policies/pip config
692 LOGGER.info("PDP configuration NOT current.");
693 if (policies != null) {
694 // Put URL's into the properties in case the PDP needs to
696 this.populatePolicyURL(request.getRequestURL(), policies);
697 // Copy the properties to the output stream
699 policies.store(response.getOutputStream(), "");
700 }catch(IOException e){
704 if (pipconfig != null) {
705 // Copy the properties to the output stream
707 pipconfig.store(response.getOutputStream(), "");
708 }catch(IOException e){
712 // We are good - and we are sending them information
713 response.setStatus(HttpServletResponse.SC_OK);
715 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
716 }catch(PAPException e){
720 // Tell them they are good
721 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
723 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
724 }catch(PAPException e){
728 // tell the AC that something changed
729 loggingContext.metricStarted();
731 loggingContext.metricEnded();
732 PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
733 loggingContext.transactionEnded();
734 auditLogger.info("Success");
735 PolicyLogger.audit("Transaction Ended Successfully");
736 } catch (PAPException | IOException | NumberFormatException e) {
737 if(pdpTransaction != null){
738 pdpTransaction.rollbackTransaction();
740 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
741 loggingContext.transactionEnded();
742 PolicyLogger.audit("Transaction Failed - See Error.log");
743 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
747 //Catch anything that fell through
748 loggingContext.transactionEnded();
749 PolicyLogger.audit("Transaction Ended");
753 private void setResponseError(HttpServletResponse response,int responseCode, String message) {
755 response.sendError(responseCode, message);
756 } catch (IOException e) {
757 LOGGER.error("Error setting Error response Header ", e);
763 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
765 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
766 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
767 loggingContext.transactionStarted();
768 loggingContext.setServiceName("PAP.get");
769 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
770 UUID requestID = UUID.randomUUID();
771 loggingContext.setRequestID(requestID.toString());
772 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
774 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
777 loggingContext.metricStarted();
778 XACMLRest.dumpRequest(request);
779 loggingContext.metricEnded();
780 PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
781 String pathInfo = request.getRequestURI();
782 LOGGER.info("path info: " + pathInfo);
783 if (pathInfo != null){
784 //DO NOT do a im.startTransaction for the test request
785 if (pathInfo.equals("/pap/test")) {
787 testService(loggingContext, response);
788 } catch (IOException e) {
794 //This im.startTransaction() covers all other Get transactions
796 loggingContext.metricStarted();
797 im.startTransaction();
798 loggingContext.metricEnded();
799 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
800 } catch (AdministrativeStateException ae){
801 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
802 + " state of " + im.getStateManager().getAdminState()
803 + "\n Exception Message: " + ae.getMessage();
804 LOGGER.info(message, ae);
805 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
806 loggingContext.transactionEnded();
807 PolicyLogger.audit("Transaction Failed - See Error.log");
808 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
810 }catch (StandbyStatusException se) {
811 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
812 + " of " + im.getStateManager().getStandbyStatus()
813 + "\n Exception Message: " + se.getMessage();
814 LOGGER.info(message, se);
815 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
816 loggingContext.transactionEnded();
817 PolicyLogger.audit("Transaction Failed - See Error.log");
818 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
821 // Request from the API to get the gitPath
822 String apiflag = request.getParameter("apiflag");
824 if(authorizeRequest(request)){
825 APIRequestHandler apiRequestHandler = new APIRequestHandler();
827 loggingContext.metricStarted();
828 apiRequestHandler.doGet(request,response, apiflag);
829 loggingContext.metricEnded();
830 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
831 }catch(IOException e){
834 loggingContext.transactionEnded();
835 PolicyLogger.audit("Transaction Ended Successfully");
839 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
840 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
841 loggingContext.transactionEnded();
842 PolicyLogger.audit("Transaction Failed - See Error.log");
843 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
848 // Is this from the Admin Console?
849 String groupId = request.getParameter("groupId");
850 if (groupId != null) {
851 // this is from the Admin Console, so handle separately
853 loggingContext.metricStarted();
854 doACGet(request, response, groupId, loggingContext);
855 loggingContext.metricEnded();
856 PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
857 } catch(IOException e){
860 loggingContext.transactionEnded();
861 PolicyLogger.audit("Transaction Ended Successfully");
866 String id = this.getPDPID(request);
867 LOGGER.info("doGet from: " + id);
868 // Get the PDP Object
871 pdp = XACMLPapServlet.papEngine.getPDP(id);
872 }catch(PAPException e){
877 // Check if request came from localhost
878 if (request.getRemoteHost().equals("localhost") ||
879 request.getRemoteHost().equals(request.getLocalAddr())) {
880 // Return status information - basically all the groups
881 loggingContext.setServiceName("PAP.getGroups");
882 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
883 // convert response object to JSON and include in the response
884 mapperWriteValue(new ObjectMapper(), response, groups);
885 response.setHeader("content-type", "application/json");
886 response.setStatus(HttpServletResponse.SC_OK);
887 loggingContext.transactionEnded();
888 PolicyLogger.audit("Transaction Ended Successfully");
892 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
893 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
894 loggingContext.transactionEnded();
895 PolicyLogger.audit("Transaction Failed - See Error.log");
896 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
900 loggingContext.setServiceName("PAP.getPolicy");
901 // Get the PDP's Group
902 OnapPDPGroup group = null;
904 group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
905 } catch (PAPException e) {
909 String message = "No group associated with pdp " + pdp.getId();
910 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
911 loggingContext.transactionEnded();
912 PolicyLogger.audit("Transaction Failed - See Error.log");
913 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
917 // Which policy do they want?
918 String policyId = request.getParameter("id");
919 if (policyId == null) {
920 String message = "Did not specify an id for the policy";
921 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
922 loggingContext.transactionEnded();
923 PolicyLogger.audit("Transaction Failed - See Error.log");
924 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
928 PDPPolicy policy = group.getPolicy(policyId);
929 if (policy == null) {
930 String message = "Unknown policy: " + policyId;
931 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
932 loggingContext.transactionEnded();
933 PolicyLogger.audit("Transaction Failed - See Error.log");
934 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
939 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
940 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
941 } catch (PAPException| IOException e){
944 try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
945 // Send the policy back
946 IOUtils.copy(is, os);
947 response.setStatus(HttpServletResponse.SC_OK);
948 loggingContext.transactionEnded();
949 auditLogger.info("Success");
950 PolicyLogger.audit("Transaction Ended Successfully");
951 } catch (IOException e) {
952 String message = "Failed to open policy id " + policyId;
954 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
955 loggingContext.transactionEnded();
956 PolicyLogger.audit("Transaction Failed - See Error.log");
957 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
959 } catch (PAPException e) {
961 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
962 loggingContext.transactionEnded();
963 PolicyLogger.audit("Transaction Failed - See Error.log");
964 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
968 loggingContext.transactionEnded();
969 PolicyLogger.audit("Transaction Ended");
974 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
976 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
977 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
978 loggingContext.transactionStarted();
979 loggingContext.setServiceName("PAP.put");
980 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
981 UUID requestID = UUID.randomUUID();
982 loggingContext.setRequestID(requestID.toString());
983 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
985 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
988 loggingContext.metricStarted();
989 im.startTransaction();
990 loggingContext.metricEnded();
991 PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
992 } catch (AdministrativeStateException | StandbyStatusException e) {
993 String message = "PUT interface called for PAP " + papResourceName;
994 if (e instanceof AdministrativeStateException) {
995 message += " but it has an Administrative state of "
996 + im.getStateManager().getAdminState();
997 } else if (e instanceof StandbyStatusException) {
998 message += " but it has a Standby Status of "
999 + im.getStateManager().getStandbyStatus();
1002 message += "\n Exception Message: " + e.getMessage();
1004 LOGGER.info(message, e);
1005 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1006 loggingContext.transactionEnded();
1007 PolicyLogger.audit("Transaction Failed - See Error.log");
1008 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1012 loggingContext.metricStarted();
1013 XACMLRest.dumpRequest(request);
1014 loggingContext.metricEnded();
1015 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1016 //need to check if request is from the API or Admin console
1017 String apiflag = request.getParameter("apiflag");
1018 //This would occur if a PolicyDBDao notification was received
1019 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1020 if(policyDBDaoRequestUrl != null){
1021 String policyDBDaoRequestEntityId = request.getParameter("entityid");
1022 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1023 String policyDBDaoRequestExtraData = request.getParameter("extradata");
1024 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
1025 setResponseError(response,400, "entityid or entitytype not supplied");
1026 loggingContext.transactionEnded();
1027 PolicyLogger.audit("Transaction Ended Successfully");
1028 im.endTransaction();
1031 loggingContext.metricStarted();
1032 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
1033 loggingContext.metricEnded();
1034 PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1035 response.setStatus(200);
1036 loggingContext.transactionEnded();
1037 PolicyLogger.audit("Transaction Ended Successfully");
1038 im.endTransaction();
1042 * Request for ImportService
1044 String importService = request.getParameter("importService");
1045 if (importService != null) {
1046 if(authorizeRequest(request)){
1047 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1049 loggingContext.metricStarted();
1050 apiRequestHandler.doPut(request, response, importService);
1051 loggingContext.metricEnded();
1052 PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1053 }catch(IOException e){
1056 im.endTransaction();
1059 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1060 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1061 loggingContext.transactionEnded();
1062 PolicyLogger.audit("Transaction Failed - See Error.log");
1063 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1067 //This would occur if we received a notification of a policy rename from AC
1068 String oldPolicyName = request.getParameter("oldPolicyName");
1069 String newPolicyName = request.getParameter("newPolicyName");
1070 if(oldPolicyName != null && newPolicyName != null){
1071 if(LOGGER.isDebugEnabled()){
1072 LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding"
1073 + "\npolicyToCreateUpdate = " + " ");
1077 oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
1078 newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
1079 if(LOGGER.isDebugEnabled()){
1080 LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding"
1081 + "\npolicyToCreateUpdate = " + " ");
1083 } catch(UnsupportedEncodingException e){
1084 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
1085 + "\npolicyToCreateUpdate = " + " ");
1086 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToCreateUpdate encoding not supported"
1087 + "\nfailure with the following exception: " + e);
1088 loggingContext.transactionEnded();
1089 PolicyLogger.audit("Transaction Failed - See error.log");
1090 im.endTransaction();
1093 //send it to PolicyDBDao
1094 PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
1096 renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
1097 }catch(Exception e){
1098 renameTransaction.rollbackTransaction();
1099 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
1100 + "\nfailure with the following exception: " + e);
1101 loggingContext.transactionEnded();
1102 PolicyLogger.audit("Transaction Failed - See error.log");
1103 im.endTransaction();
1106 loggingContext.metricStarted();
1107 renameTransaction.commitTransaction();
1108 loggingContext.metricEnded();
1109 PolicyLogger.metrics("XACMLPapServlet goPut commitTransaction");
1110 response.setStatus(HttpServletResponse.SC_OK);
1111 loggingContext.transactionEnded();
1112 PolicyLogger.audit("Transaction Ended Successfully");
1113 im.endTransaction();
1117 // See if this is Admin Console registering itself with us
1119 String acURLString = request.getParameter("adminConsoleURL");
1120 if (acURLString != null) {
1121 loggingContext.setServiceName("AC:PAP.register");
1122 // remember this Admin Console for future updates
1123 if ( ! adminConsoleURLStringList.contains(acURLString)) {
1124 adminConsoleURLStringList.add(acURLString);
1126 if (LOGGER.isDebugEnabled()) {
1127 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1129 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1130 loggingContext.transactionEnded();
1131 auditLogger.info("Success");
1132 PolicyLogger.audit("Transaction Ended Successfully");
1133 im.endTransaction();
1137 * This is to update the PDP Group with the policy/policies being pushed
1138 * Part of a 2 step process to push policies to the PDP that can now be done
1139 * From both the Admin Console and the PolicyEngine API
1141 String groupId = request.getParameter("groupId");
1142 if (groupId != null) {
1144 if(!authorizeRequest(request)){
1145 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1146 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1147 loggingContext.transactionEnded();
1148 PolicyLogger.audit("Transaction Failed - See Error.log");
1149 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1152 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1154 updateGroupsFromAPI(request, response, groupId, loggingContext);
1155 }catch(IOException e){
1158 loggingContext.transactionEnded();
1159 PolicyLogger.audit("Transaction Ended Successfully");
1160 im.endTransaction();
1164 // this is from the Admin Console, so handle separately
1166 loggingContext.metricEnded();
1167 doACPut(request, response, groupId, loggingContext);
1168 loggingContext.metricEnded();
1169 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1170 } catch (IOException e) {
1173 loggingContext.transactionEnded();
1174 PolicyLogger.audit("Transaction Ended Successfully");
1175 im.endTransaction();
1179 // Request is for policy validation and creation
1181 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1182 // this request is from the Admin Console
1183 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1185 loggingContext.metricStarted();
1186 savePolicyHandler.doPolicyAPIPut(request, response);
1187 loggingContext.metricEnded();
1188 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1189 } catch (IOException e) {
1192 loggingContext.transactionEnded();
1193 PolicyLogger.audit("Transaction Ended Successfully");
1194 im.endTransaction();
1196 } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
1197 // this request is from the Policy Creation API
1198 if(authorizeRequest(request)){
1199 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1201 loggingContext.metricStarted();
1202 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1203 loggingContext.metricEnded();
1204 PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1205 } catch (IOException e) {
1208 loggingContext.transactionEnded();
1209 PolicyLogger.audit("Transaction Ended Successfully");
1210 im.endTransaction();
1213 String message = "PEP not Authorized for making this Request!!";
1214 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1215 loggingContext.transactionEnded();
1216 PolicyLogger.audit("Transaction Failed - See Error.log");
1217 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1218 im.endTransaction();
1222 // We do not expect anything from anywhere else.
1223 // This method is here in case we ever need to support other operations.
1224 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1225 loggingContext.transactionEnded();
1226 PolicyLogger.audit("Transaction Failed - See Error.log");
1227 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1228 loggingContext.transactionEnded();
1229 PolicyLogger.audit("Transaction Failed - See error.log");
1230 im.endTransaction();
1234 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1236 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1237 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1238 loggingContext.transactionStarted();
1239 loggingContext.setServiceName("PAP.delete");
1240 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1241 UUID requestID = UUID.randomUUID();
1242 loggingContext.setRequestID(requestID.toString());
1243 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1245 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1248 loggingContext.metricStarted();
1249 im.startTransaction();
1250 loggingContext.metricEnded();
1251 PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1252 } catch (AdministrativeStateException ae){
1253 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1254 + " state of " + im.getStateManager().getAdminState()
1255 + "\n Exception Message: " + ae.getMessage();
1256 LOGGER.info(message, ae);
1257 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1258 loggingContext.transactionEnded();
1259 PolicyLogger.audit("Transaction Failed - See Error.log");
1260 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1262 }catch (StandbyStatusException se) {
1263 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1264 + " of " + im.getStateManager().getStandbyStatus()
1265 + "\n Exception Message: " + se.getMessage();
1266 LOGGER.info(message, se);
1267 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1268 loggingContext.transactionEnded();
1269 PolicyLogger.audit("Transaction Failed - See Error.log");
1270 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1273 loggingContext.metricStarted();
1274 XACMLRest.dumpRequest(request);
1275 loggingContext.metricEnded();
1276 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1277 String groupId = request.getParameter("groupId");
1278 String apiflag = request.getParameter("apiflag");
1279 if (groupId != null) {
1280 // Is this from the Admin Console or API?
1282 if(!authorizeRequest(request)){
1283 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1284 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1285 loggingContext.transactionEnded();
1286 PolicyLogger.audit("Transaction Failed - See Error.log");
1287 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1290 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1292 loggingContext.metricStarted();
1293 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1294 loggingContext.metricEnded();
1295 PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1296 } catch (Exception e) {
1297 LOGGER.error("Exception Occured"+e);
1299 if(apiRequestHandler.getNewGroup()!=null){
1300 groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1304 // this is from the Admin Console, so handle separately
1306 loggingContext.metricStarted();
1307 doACDelete(request, response, groupId, loggingContext);
1308 loggingContext.metricEnded();
1309 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1310 } catch (IOException e) {
1313 loggingContext.transactionEnded();
1314 PolicyLogger.audit("Transaction Ended Successfully");
1315 im.endTransaction();
1318 //Catch anything that fell through
1319 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1320 loggingContext.transactionEnded();
1321 PolicyLogger.audit("Transaction Failed - See Error.log");
1322 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1323 im.endTransaction();
1326 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1327 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1328 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1329 if (localRootPolicies == null || localReferencedPolicies == null) {
1330 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1333 // Compare the policies and pipconfig properties to the pdpProperties
1335 // the policy properties includes only xacml.rootPolicies and
1336 // xacml.referencedPolicies without any .url entries
1337 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1338 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1339 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1340 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1341 pdpPipConfig.equals(pipconfig)) {
1342 // The PDP is current
1345 } catch (Exception e) {
1346 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1347 // or if there are policies that do not have a corresponding ".url" property.
1348 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1349 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1354 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1355 String lists[] = new String[2];
1356 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1357 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1358 for (String list : lists) {
1359 if (list != null && list.isEmpty() == false) {
1360 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1361 String url = urlPath + "?id=" + id;
1362 LOGGER.info("Policy URL for " + id + ": " + url);
1363 policies.setProperty(id + ".url", url);
1369 protected String getPDPID(HttpServletRequest request) {
1370 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1371 if (pdpURL == null || pdpURL.isEmpty()) {
1372 // Should send back its port for identification
1373 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1379 protected String getPDPJMX(HttpServletRequest request) {
1380 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1381 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1382 // Should send back its port for identification
1383 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1390 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1395 * @param loggingContext
1396 * @throws ServletException
1397 * @throws IOException
1399 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1400 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1401 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1403 // for PUT operations the group may or may not need to exist before the operation can be done
1404 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1406 // get the request input stream content into a String
1408 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1409 scanner.useDelimiter("\\A");
1410 json = scanner.hasNext() ? scanner.next() : "";
1413 PolicyLogger.info("pushPolicy request from API: " + json);
1415 // convert Object sent as JSON into local object
1416 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1418 //Get the current policies from the Group and Add the new one
1419 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1420 currentPoliciesInGroup = group.getPolicies();
1421 //If the selected policy is in the group we must remove the old version of it
1422 LOGGER.info("Removing old version of the policy");
1423 for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
1424 if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
1425 group.removePolicy(existingPolicy);
1426 LOGGER.info("Removing policy: " + existingPolicy);
1431 // Assume that this is an update of an existing PDP Group
1432 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1434 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1435 } catch(Exception e){
1436 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1437 +"group="+group.getId());
1438 throw new PAPException(e.getMessage());
1441 LOGGER.info("Calling updatGroup() with new group");
1442 papEngine.updateGroup(group);
1444 String policyId = "empty";
1446 policyId = policy.getId();
1448 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1449 response.addHeader("operation", "push");
1450 response.addHeader("policyId", policyId);
1451 response.addHeader("groupId", groupId);
1453 LOGGER.info("Group '" + group.getId() + "' updated");
1455 loggingContext.metricStarted();
1456 acPutTransaction.commitTransaction();
1457 loggingContext.metricEnded();
1458 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1459 loggingContext.metricStarted();
1461 loggingContext.metricEnded();
1462 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1464 // Group changed, which might include changing the policies
1465 groupChanged(group, loggingContext);
1466 loggingContext.transactionEnded();
1467 LOGGER.info("Success");
1469 if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1470 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1471 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1472 LOGGER.debug("Precheck Successful.");
1476 PolicyLogger.audit("Transaction Ended Successfully");
1478 } catch (PAPException e) {
1479 acPutTransaction.rollbackTransaction();
1480 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1481 loggingContext.transactionEnded();
1482 PolicyLogger.audit("Transaction Failed - See Error.log");
1483 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1484 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1485 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1486 response.addHeader("error","addGroupError");
1487 response.addHeader("message", message);
1493 * Requests from the Admin Console for operations not on single specific objects
1498 * @param loggingContext
1499 * @throws ServletException
1500 * @throws IOException
1502 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1503 PolicyDBDaoTransaction doACPostTransaction = null;
1505 String groupName = request.getParameter("groupName");
1506 String groupDescription = request.getParameter("groupDescription");
1507 String apiflag = request.getParameter("apiflag");
1508 if (groupName != null && groupDescription != null) {
1509 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
1510 loggingContext.setServiceName("AC:PAP.createGroup");
1511 String unescapedName = null;
1512 String unescapedDescription = null;
1514 unescapedName = URLDecoder.decode(groupName, "UTF-8");
1515 unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1516 } catch (UnsupportedEncodingException e) {
1519 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1521 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1522 papEngine.newGroup(unescapedName, unescapedDescription);
1523 loggingContext.metricStarted();
1524 newGroupTransaction.commitTransaction();
1525 loggingContext.metricEnded();
1526 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1527 } catch (Exception e) {
1528 newGroupTransaction.rollbackTransaction();
1529 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1530 loggingContext.transactionEnded();
1531 PolicyLogger.audit("Transaction Failed - See Error.log");
1532 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1535 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1536 if (LOGGER.isDebugEnabled()) {
1537 LOGGER.debug("New Group '" + groupId + "' created");
1539 // tell the Admin Consoles there is a change
1540 loggingContext.metricStarted();
1542 loggingContext.metricEnded();
1543 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1544 // new group by definition has no PDPs, so no need to notify them of changes
1545 loggingContext.transactionEnded();
1546 PolicyLogger.audit("Transaction Failed - See Error.log");
1547 auditLogger.info("Success");
1548 PolicyLogger.audit("Transaction Ended Successfully");
1551 // for all remaining POST operations the group must exist before the operation can be done
1552 OnapPDPGroup group = null;
1554 group = papEngine.getGroup(groupId);
1555 } catch (PAPException e){
1558 if (group == null) {
1559 String message = "Unknown groupId '" + groupId + "'";
1560 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1561 loggingContext.transactionEnded();
1562 PolicyLogger.audit("Transaction Failed - See Error.log");
1564 response.addHeader("error", "unknownGroupId");
1565 response.addHeader("operation", "push");
1566 response.addHeader("message", message);
1567 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1569 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1574 // If the request contains a policyId then we know we are pushing the policy to PDP
1575 if (request.getParameter("policyId") != null) {
1578 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1580 loggingContext.setServiceName("AC:PAP.postPolicy");
1583 String policyId = request.getParameter("policyId");
1584 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1585 StdPDPGroup updatedGroup = null;
1587 //Copying the policy to the file system and updating groups in database
1588 LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
1589 updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1590 loggingContext.metricStarted();
1591 addPolicyToGroupTransaction.commitTransaction();
1592 loggingContext.metricEnded();
1593 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1594 LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
1596 } catch (Exception e) {
1597 addPolicyToGroupTransaction.rollbackTransaction();
1598 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1599 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1600 loggingContext.transactionEnded();
1601 PolicyLogger.audit("Transaction Failed - See Error.log");
1603 response.addHeader("error", "policyCopyError");
1604 response.addHeader("message", message);
1605 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1607 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1612 // Get new transaction to perform updateGroup()
1613 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1616 * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
1617 * The GUI does this from the POLICY-SDK-APP code.
1619 if(apiflag != null){
1621 // read the inputStream into a buffer
1622 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1623 scanner.useDelimiter("\\A");
1624 String json = scanner.hasNext() ? scanner.next() : "";
1626 LOGGER.info("PushPolicy API request: " + json);
1628 // convert Object sent as JSON into local object
1629 ObjectMapper mapper = new ObjectMapper();
1630 Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
1631 StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
1633 // Assume that this is an update of an existing PDP Group
1634 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1636 acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
1637 } catch(Exception e){
1638 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
1640 throw new PAPException(e.getMessage());
1643 LOGGER.info("Calling updatGroup() with new group");
1644 papEngine.updateGroup(updatedGroup);
1646 LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
1648 // Commit transaction to send notification to other PAPs
1649 loggingContext.metricStarted();
1650 acPutTransaction.commitTransaction();
1651 loggingContext.metricEnded();
1652 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1653 loggingContext.metricStarted();
1656 loggingContext.metricEnded();
1657 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1659 // Group changed to send notification to PDPs, which might include changing the policies
1660 groupChanged(updatedGroup,loggingContext);
1661 loggingContext.transactionEnded();
1662 LOGGER.info("Success");
1664 if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1665 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1666 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1667 LOGGER.debug("Precheck Successful.");
1671 //delete temporary policy file from the bin directory
1672 if(policy != null) {
1673 Files.deleteIfExists(Paths.get(policy.getId()));
1677 } catch (Exception e) {
1678 acPutTransaction.rollbackTransaction();
1679 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1680 loggingContext.transactionEnded();
1681 PolicyLogger.audit("Transaction Failed - See Error.log");
1682 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API.";
1683 LOGGER.error(message);
1684 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1685 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1686 response.addHeader("error","addGroupError");
1687 response.addHeader("message", message);
1693 // policy file copied ok and the Group was updated on the PDP
1694 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1695 response.addHeader("operation", "push");
1696 response.addHeader("policyId", policyId);
1697 response.addHeader("groupId", groupId);
1699 LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1700 loggingContext.transactionEnded();
1701 auditLogger.info("Success");
1702 LOGGER.info("Transaction Ended Successfully");
1705 } else if (request.getParameter("default") != null) {
1706 // Args: group=<groupId> default=true <= make default
1707 // change the current default group to be the one identified in the request.
1708 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1709 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1710 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1711 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1713 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1714 papEngine.setDefaultGroup(group);
1715 loggingContext.metricStarted();
1716 setDefaultGroupTransaction.commitTransaction();
1717 loggingContext.metricEnded();
1718 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1719 } catch (Exception e) {
1720 setDefaultGroupTransaction.rollbackTransaction();
1721 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1722 loggingContext.transactionEnded();
1723 PolicyLogger.audit("Transaction Failed - See Error.log");
1724 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1727 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1728 if (LOGGER.isDebugEnabled()) {
1729 LOGGER.debug("Group '" + groupId + "' set to be default");
1731 // Notify the Admin Consoles that something changed
1732 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1733 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1734 loggingContext.metricStarted();
1736 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1737 loggingContext.metricEnded();
1738 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1739 loggingContext.transactionEnded();
1740 auditLogger.info("Success");
1741 LOGGER.info("Transaction Ended Successfully");
1743 } else if (request.getParameter("pdpId") != null) {
1744 doACPostTransaction = policyDBDao.getNewTransaction();
1745 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
1746 loggingContext.setServiceName("AC:PAP.movePDP");
1747 String pdpId = request.getParameter("pdpId");
1748 OnapPDP pdp = papEngine.getPDP(pdpId);
1749 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1751 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1752 }catch(Exception e){
1753 doACPostTransaction.rollbackTransaction();
1754 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1755 " Error while moving pdp in the database: "
1756 +"pdp="+pdp.getId()+",to group="+group.getId());
1757 throw new PAPException(e.getMessage());
1759 papEngine.movePDP((OnapPDP) pdp, group);
1760 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1761 if (LOGGER.isDebugEnabled()) {
1762 LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1764 // update the status of both the original group and the new one
1765 ((StdPDPGroup)originalGroup).resetStatus();
1766 ((StdPDPGroup)group).resetStatus();
1767 // Notify the Admin Consoles that something changed
1768 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1769 loggingContext.metricStarted();
1771 loggingContext.metricEnded();
1772 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1773 // Need to notify the PDP that it's config may have changed
1774 pdpChanged(pdp, loggingContext);
1775 loggingContext.metricStarted();
1776 doACPostTransaction.commitTransaction();
1777 loggingContext.metricEnded();
1778 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1779 loggingContext.transactionEnded();
1780 auditLogger.info("Success");
1781 PolicyLogger.audit("Transaction Ended Successfully");
1784 } catch (PAPException e) {
1785 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1786 loggingContext.transactionEnded();
1787 PolicyLogger.audit("Transaction Failed - See Error.log");
1788 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1794 * Requests from the Admin Console to GET info about the Groups and PDPs
1799 * @param loggingContext
1800 * @throws ServletException
1801 * @throws IOException
1803 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1805 String parameterDefault = request.getParameter("default");
1806 String pdpId = request.getParameter("pdpId");
1807 String pdpGroup = request.getParameter("getPDPGroup");
1808 if ("".equals(groupId)) {
1809 // request IS from AC but does not identify a group by name
1810 if (parameterDefault != null) {
1811 // Request is for the Default group (whatever its id)
1812 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1813 OnapPDPGroup group = papEngine.getDefaultGroup();
1814 // convert response object to JSON and include in the response
1815 mapperWriteValue(new ObjectMapper(), response, group);
1816 if (LOGGER.isDebugEnabled()) {
1817 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1819 response.setStatus(HttpServletResponse.SC_OK);
1820 response.setHeader("content-type", "application/json");
1822 response.getOutputStream().close();
1823 } catch (IOException e){
1826 loggingContext.transactionEnded();
1827 auditLogger.info("Success");
1828 PolicyLogger.audit("Transaction Ended Successfully");
1830 } else if (pdpId != null) {
1831 // Request is related to a PDP
1832 if (pdpGroup == null) {
1833 // Request is for the (unspecified) group containing a given PDP
1834 loggingContext.setServiceName("AC:PAP.getPDP");
1837 pdp = papEngine.getPDP(pdpId);
1838 }catch(PAPException e){
1841 // convert response object to JSON and include in the response
1842 mapperWriteValue(new ObjectMapper(), response, pdp);
1843 if (LOGGER.isDebugEnabled()) {
1844 LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1846 response.setStatus(HttpServletResponse.SC_OK);
1847 response.setHeader("content-type", "application/json");
1849 response.getOutputStream().close();
1850 } catch (IOException e){
1853 loggingContext.transactionEnded();
1854 auditLogger.info("Success");
1855 PolicyLogger.audit("Transaction Ended Successfully");
1858 // Request is for the group containing a given PDP
1859 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1860 OnapPDPGroup group =null;
1862 OnapPDP pdp = papEngine.getPDP(pdpId);
1863 group = papEngine.getPDPGroup((OnapPDP) pdp);
1864 }catch(PAPException e){
1867 // convert response object to JSON and include in the response
1868 mapperWriteValue(new ObjectMapper(), response, group);
1869 if (LOGGER.isDebugEnabled()) {
1870 LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1872 response.setStatus(HttpServletResponse.SC_OK);
1873 response.setHeader("content-type", "application/json");
1875 response.getOutputStream().close();
1876 } catch (IOException e){
1879 loggingContext.transactionEnded();
1880 auditLogger.info("Success");
1881 PolicyLogger.audit("Transaction Ended Successfully");
1885 // request is for top-level properties about all groups
1886 loggingContext.setServiceName("AC:PAP.getAllGroups");
1887 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
1888 // convert response object to JSON and include in the response
1889 mapperWriteValue(new ObjectMapper(), response, groups);
1890 if (LOGGER.isDebugEnabled()) {
1891 LOGGER.debug("GET All groups req");
1893 response.setStatus(HttpServletResponse.SC_OK);
1894 response.setHeader("content-type", "application/json");
1896 response.getOutputStream().close();
1897 } catch (IOException e){
1900 loggingContext.transactionEnded();
1901 auditLogger.info("Success");
1902 PolicyLogger.audit("Transaction Ended Successfully");
1906 // for all other GET operations the group must exist before the operation can be done
1907 OnapPDPGroup group = null;
1909 group = papEngine.getGroup(groupId);
1910 } catch(PAPException e){
1913 if (group == null) {
1914 String message = "Unknown groupId '" + groupId + "'";
1915 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1916 loggingContext.transactionEnded();
1917 PolicyLogger.audit("Transaction Failed - See Error.log");
1918 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1921 // Figure out which request this is based on the parameters
1922 String policyId = request.getParameter("policyId");
1923 if (policyId != null) {
1924 // retrieve a policy
1925 loggingContext.setServiceName("AC:PAP.getPolicy");
1926 // convert response object to JSON and include in the response
1927 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1928 loggingContext.transactionEnded();
1929 PolicyLogger.audit("Transaction Failed - See Error.log");
1930 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1932 // No other parameters, so return the identified Group
1933 loggingContext.setServiceName("AC:PAP.getGroup");
1934 // convert response object to JSON and include in the response
1935 mapperWriteValue(new ObjectMapper(), response, group);
1936 if (LOGGER.isDebugEnabled()) {
1937 LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1939 response.setStatus(HttpServletResponse.SC_OK);
1940 response.setHeader("content-type", "application/json");
1942 response.getOutputStream().close();
1943 } catch (IOException e){
1946 loggingContext.transactionEnded();
1947 auditLogger.info("Success");
1948 PolicyLogger.audit("Transaction Ended Successfully");
1951 // Currently there are no other GET calls from the AC.
1952 // 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.
1953 // Other GETs that could be called:
1954 // Specific Group (groupId=<groupId>)
1955 // A Policy (groupId=<groupId> policyId=<policyId>)
1956 // A PDP (groupId=<groupId> pdpId=<pdpId>)
1957 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1958 loggingContext.transactionEnded();
1959 PolicyLogger.audit("Transaction Failed - See Error.log");
1960 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1961 } catch (PAPException e) {
1962 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1963 loggingContext.transactionEnded();
1964 PolicyLogger.audit("Transaction Failed - See Error.log");
1965 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1971 * Requests from the Admin Console to create new items or update existing ones
1976 * @param loggingContext
1977 * @throws ServletException
1978 * @throws IOException
1980 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1981 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1983 // for PUT operations the group may or may not need to exist before the operation can be done
1984 OnapPDPGroup group = papEngine.getGroup(groupId);
1985 // determine the operation needed based on the parameters in the request
1986 // for remaining operations the group must exist before the operation can be done
1987 if (group == null) {
1988 String message = "Unknown groupId '" + groupId + "'";
1989 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1990 loggingContext.transactionEnded();
1991 PolicyLogger.audit("Transaction Failed - See Error.log");
1992 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1995 if (request.getParameter("policy") != null) {
1996 // 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)
1997 loggingContext.setServiceName("AC:PAP.putPolicy");
1998 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
1999 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2000 loggingContext.transactionEnded();
2001 PolicyLogger.audit("Transaction Failed - See Error.log");
2002 auditLogger.info("Success");
2003 PolicyLogger.audit("Transaction Ended Successfully");
2005 } else if (request.getParameter("pdpId") != null) {
2006 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
2007 String pdpId = request.getParameter("pdpId");
2008 if (papEngine.getPDP(pdpId) == null) {
2009 loggingContext.setServiceName("AC:PAP.createPDP");
2011 loggingContext.setServiceName("AC:PAP.updatePDP");
2013 // get the request content into a String
2015 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2017 Scanner scanner = new Scanner(request.getInputStream());
2018 scanner.useDelimiter("\\A");
2019 json = scanner.hasNext() ? scanner.next() : "";
2021 }catch(IOException e){
2024 LOGGER.info("JSON request from AC: " + json);
2025 // convert Object sent as JSON into local object
2026 ObjectMapper mapper = new ObjectMapper();
2027 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
2028 if (pdpId == null ||
2029 objectFromJSON == null ||
2030 ! (objectFromJSON instanceof StdPDP) ||
2031 ((StdPDP)objectFromJSON).getId() == null ||
2032 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
2033 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
2034 loggingContext.transactionEnded();
2035 PolicyLogger.audit("Transaction Failed - See Error.log");
2036 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
2038 StdPDP pdp = (StdPDP) objectFromJSON;
2040 OnapPDP oPDP = null;
2042 oPDP = papEngine.getPDP(pdpId);
2043 }catch (PAPException e){
2047 // this is a request to create a new PDP object
2049 acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(),
2050 pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
2051 } catch(Exception e){
2052 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2053 +"pdp="+ (pdp.getId()) +",to group="+group.getId());
2054 throw new PAPException(e.getMessage());
2057 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
2058 }catch(PAPException e){
2063 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
2064 } catch(Exception e){
2065 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
2066 +"pdp="+ pdp.getId());
2067 throw new PAPException(e.getMessage());
2069 // this is a request to update the pdp
2071 papEngine.updatePDP(pdp);
2072 }catch(PAPException e){
2076 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2077 if (LOGGER.isDebugEnabled()) {
2078 LOGGER.debug("PDP '" + pdpId + "' created/updated");
2080 // adjust the group's state including the new PDP
2081 ((StdPDPGroup)group).resetStatus();
2082 // tell the Admin Consoles there is a change
2083 loggingContext.metricStarted();
2085 loggingContext.metricEnded();
2086 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2087 // this might affect the PDP, so notify it of the change
2088 pdpChanged(pdp, loggingContext);
2089 loggingContext.metricStarted();
2090 acPutTransaction.commitTransaction();
2091 loggingContext.metricEnded();
2092 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2093 loggingContext.transactionEnded();
2094 auditLogger.info("Success");
2095 PolicyLogger.audit("Transaction Ended Successfully");
2099 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2100 +"pdp=null" + ",to group="+group.getId());
2101 throw new PAPException("PDP is null");
2102 } catch(Exception e){
2103 throw new PAPException("PDP is null" + e.getMessage() +e);
2106 } else if (request.getParameter("pipId") != null) {
2107 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
2108 loggingContext.setServiceName("AC:PAP.putPIP");
2109 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2110 loggingContext.transactionEnded();
2111 PolicyLogger.audit("Transaction Failed - See Error.log");
2112 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2115 // Assume that this is an update of an existing PDP Group
2116 // ARGS: group=<groupId> <= Update an Existing Group
2117 loggingContext.setServiceName("AC:PAP.updateGroup");
2118 // get the request content into a String
2120 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2122 Scanner scanner = new Scanner(request.getInputStream());
2123 scanner.useDelimiter("\\A");
2124 json = scanner.hasNext() ? scanner.next() : "";
2126 }catch(IOException e){
2129 LOGGER.info("JSON request from AC: " + json);
2130 // convert Object sent as JSON into local object
2131 ObjectMapper mapper = new ObjectMapper();
2132 Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
2133 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
2134 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
2135 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
2136 loggingContext.transactionEnded();
2137 PolicyLogger.audit("Transaction Failed - See Error.log");
2138 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input, id="+group.getId() +" object="+objectFromJSON);
2140 // The Path on the PAP side is not carried on the RESTful interface with the AC
2141 // (because it is local to the PAP)
2142 // so we need to fill that in before submitting the group for update
2143 if(objectFromJSON != null){
2144 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
2147 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
2148 } catch(Exception e){
2149 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
2150 +"group="+group.getId());
2152 throw new PAPException(e.getMessage());
2155 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
2156 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
2157 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
2158 LOGGER.debug("Precheck Successful.");
2161 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
2162 }catch(PAPException e){
2165 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2166 if (LOGGER.isDebugEnabled()) {
2167 LOGGER.debug("Group '" + group.getId() + "' updated");
2169 loggingContext.metricStarted();
2170 acPutTransaction.commitTransaction();
2171 loggingContext.metricEnded();
2172 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2173 // tell the Admin Consoles there is a change
2174 loggingContext.metricStarted();
2176 loggingContext.metricEnded();
2177 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2178 // Group changed, which might include changing the policies
2179 groupChanged(group, loggingContext);
2180 loggingContext.transactionEnded();
2181 auditLogger.info("Success");
2182 PolicyLogger.audit("Transaction Ended Successfully");
2185 } catch (PAPException e) {
2187 acPutTransaction.rollbackTransaction();
2188 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2189 loggingContext.transactionEnded();
2190 PolicyLogger.audit("Transaction Failed - See Error.log");
2191 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2197 * Requests from the Admin Console to delete/remove items
2202 * @param loggingContext
2203 * @throws ServletException
2204 * @throws IOException
2206 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2207 //This code is to allow deletes to propagate to the database since delete is not implemented
2208 String isDeleteNotify = request.getParameter("isDeleteNotify");
2209 if(isDeleteNotify != null){
2210 String policyToDelete = request.getParameter("policyToDelete");
2212 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
2213 } catch(UnsupportedEncodingException e){
2214 LOGGER.error("Unsupported URL encoding of policyToDelete (UTF-8", e);
2215 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToDelete encoding not supported");
2218 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
2220 deleteTransaction.deletePolicy(policyToDelete);
2221 } catch(Exception e){
2222 deleteTransaction.rollbackTransaction();
2223 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"deleteTransaction.deleteTransaction(policyToDelete) "
2224 + "\nfailure with the following exception: " + e);
2227 loggingContext.metricStarted();
2228 deleteTransaction.commitTransaction();
2229 loggingContext.metricEnded();
2230 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2231 response.setStatus(HttpServletResponse.SC_OK);
2234 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
2236 // for all DELETE operations the group must exist before the operation can be done
2237 loggingContext.setServiceName("AC:PAP.delete");
2238 OnapPDPGroup group = papEngine.getGroup(groupId);
2239 if (group == null) {
2240 String message = "Unknown groupId '" + groupId + "'";
2241 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2242 loggingContext.transactionEnded();
2243 PolicyLogger.audit("Transaction Failed - See Error.log");
2244 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
2247 // determine the operation needed based on the parameters in the request
2248 if (request.getParameter("policy") != null) {
2249 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
2250 loggingContext.setServiceName("AC:PAP.deletePolicy");
2251 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2252 loggingContext.transactionEnded();
2253 PolicyLogger.audit("Transaction Failed - See Error.log");
2254 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2256 } else if (request.getParameter("pdpId") != null) {
2257 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
2258 String pdpId = request.getParameter("pdpId");
2259 OnapPDP pdp = papEngine.getPDP(pdpId);
2261 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
2262 } catch(Exception e){
2263 throw new PAPException(e);
2266 papEngine.removePDP((OnapPDP) pdp);
2267 }catch(PAPException e){
2270 // adjust the status of the group, which may have changed when we removed this PDP
2271 ((StdPDPGroup)group).resetStatus();
2272 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2273 loggingContext.metricStarted();
2275 loggingContext.metricEnded();
2276 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2277 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2278 pdpChanged(pdp, loggingContext);
2279 loggingContext.metricStarted();
2280 removePdpOrGroupTransaction.commitTransaction();
2281 loggingContext.metricEnded();
2282 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2283 loggingContext.transactionEnded();
2284 auditLogger.info("Success");
2285 PolicyLogger.audit("Transaction Ended Successfully");
2287 } else if (request.getParameter("pipId") != null) {
2288 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2289 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2290 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2291 loggingContext.transactionEnded();
2292 PolicyLogger.audit("Transaction Failed - See Error.log");
2293 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2296 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
2297 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2298 OnapPDPGroup moveToGroup = null;
2299 if (moveToGroupId != null) {
2301 moveToGroup = papEngine.getGroup(moveToGroupId);
2302 }catch(PAPException e){
2306 // get list of PDPs in the group being deleted so we can notify them that they got changed
2307 Set<OnapPDP> movedPDPs = new HashSet<>();
2308 movedPDPs.addAll(group.getOnapPdps());
2309 // do the move/remove
2311 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2312 } catch(Exception e){
2313 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2314 throw new PAPException(e.getMessage());
2317 papEngine.removeGroup(group, moveToGroup);
2318 }catch(PAPException e){
2321 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2322 loggingContext.metricStarted();
2324 loggingContext.metricEnded();
2325 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2326 // notify any PDPs in the removed set that their config may have changed
2327 for (OnapPDP pdp : movedPDPs) {
2328 pdpChanged(pdp, loggingContext);
2330 loggingContext.metricStarted();
2331 removePdpOrGroupTransaction.commitTransaction();
2332 loggingContext.metricEnded();
2333 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2334 loggingContext.transactionEnded();
2335 auditLogger.info("Success");
2336 PolicyLogger.audit("Transaction Ended Successfully");
2339 } catch (PAPException e) {
2340 removePdpOrGroupTransaction.rollbackTransaction();
2341 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2342 loggingContext.transactionEnded();
2343 PolicyLogger.audit("Transaction Failed - See Error.log");
2344 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2350 * Heartbeat thread - periodically check on PDPs' status
2352 * Heartbeat with all known PDPs.
2354 * Implementation note:
2356 * The PDPs are contacted Sequentially, not in Parallel.
2358 * If we did this in parallel using multiple threads we would simultaneously use
2362 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2363 * when user changes occur.
2364 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2366 * The Sequential operation does a heartbeat request to each PDP one at a time.
2367 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2368 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2369 * it could take a long time to cycle through all of the PDPs.
2370 * That means that this may not notice a PDP being down in a predictable time.
2372 private class Heartbeat implements Runnable {
2373 private PAPPolicyEngine papEngine;
2374 private Set<OnapPDP> pdps = new HashSet<>();
2375 private int heartbeatInterval;
2376 private int heartbeatTimeout;
2378 public volatile boolean isRunning = false;
2380 public synchronized boolean isRunning() {
2381 return this.isRunning;
2384 public synchronized void terminate() {
2385 this.isRunning = false;
2388 public Heartbeat(PAPPolicyEngine papEngine2) {
2389 papEngine = papEngine2;
2390 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2391 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2396 // Set ourselves as running
2397 synchronized(this) {
2398 this.isRunning = true;
2400 HashMap<String, URL> idToURLMap = new HashMap<>();
2402 while (this.isRunning()) {
2403 // Wait the given time
2404 Thread.sleep(heartbeatInterval);
2405 // get the list of PDPs (may have changed since last time)
2407 synchronized(papEngine) {
2409 for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2410 for (OnapPDP p : g.getOnapPdps()) {
2414 } catch (PAPException e) {
2415 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2418 // Check for shutdown
2419 if (this.isRunning() == false) {
2420 LOGGER.info("isRunning is false, getting out of loop.");
2423 // try to get the summary status from each PDP
2424 boolean changeSeen = false;
2425 for (OnapPDP pdp : pdps) {
2426 // Check for shutdown
2427 if (this.isRunning() == false) {
2428 LOGGER.info("isRunning is false, getting out of loop.");
2431 // the id of the PDP is its url (though we add a query parameter)
2432 URL pdpURL = idToURLMap.get(pdp.getId());
2433 if (pdpURL == null) {
2434 // haven't seen this PDP before
2435 String fullURLString = null;
2438 if(CheckPDP.validateID(pdp.getId())){
2439 fullURLString = pdp.getId() + "?type=hb";
2440 pdpURL = new URL(fullURLString);
2441 idToURLMap.put(pdp.getId(), pdpURL);
2443 } catch (MalformedURLException e) {
2444 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2448 // Do a GET with type HeartBeat
2449 String newStatus = "";
2450 HttpURLConnection connection = null;
2452 // Open up the connection
2454 connection = (HttpURLConnection)pdpURL.openConnection();
2455 // Setup our method and headers
2456 connection.setRequestMethod("GET");
2457 connection.setConnectTimeout(heartbeatTimeout);
2459 String encoding = CheckPDP.getEncoding(pdp.getId());
2460 if(encoding !=null){
2461 connection.setRequestProperty("Authorization", "Basic " + encoding);
2464 connection.connect();
2465 if (connection.getResponseCode() == 204) {
2466 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2467 if (LOGGER.isDebugEnabled()) {
2468 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2471 // anything else is an unexpected result
2472 newStatus = PDPStatus.Status.UNKNOWN.toString();
2473 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2476 } catch (UnknownHostException e) {
2477 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2478 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2479 } catch (SocketTimeoutException e) {
2480 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2481 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2482 } catch (ConnectException e) {
2483 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2484 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2485 } catch (Exception e) {
2486 newStatus = PDPStatus.Status.UNKNOWN.toString();
2487 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2489 // cleanup the connection
2490 if(connection != null)
2491 connection.disconnect();
2493 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2494 if (LOGGER.isDebugEnabled()) {
2495 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
2498 setPDPSummaryStatus(pdp, newStatus);
2499 } catch (PAPException e) {
2500 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2505 // Check for shutdown
2506 if (this.isRunning() == false) {
2507 LOGGER.info("isRunning is false, getting out of loop.");
2510 // if any of the PDPs changed state, tell the ACs to update
2515 } catch (InterruptedException e) {
2516 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
2518 Thread.currentThread().interrupt();
2524 * HELPER to change Group status when PDP status is changed
2525 * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2527 private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2528 setPDPSummaryStatus(pdp, newStatus.toString());
2531 private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2532 synchronized(papEngine) {
2533 StdPDPStatus status = new StdPDPStatus();
2534 status.setStatus(PDPStatus.Status.valueOf(newStatus));
2535 ((StdPDP)pdp).setStatus(status);
2536 // now adjust the group
2537 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2538 // if the PDP was just deleted it may transiently exist but not be in a group
2539 if (group != null) {
2540 group.resetStatus();
2546 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2547 * in the PDP group directories
2550 public void changed() {
2551 // all PDPs in all groups need to be updated/sync'd
2552 Set<OnapPDPGroup> groups;
2554 groups = papEngine.getOnapPDPGroups();
2555 } catch (PAPException e) {
2556 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2557 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2559 for (OnapPDPGroup group : groups) {
2560 groupChanged(group);
2564 public void changed(ONAPLoggingContext loggingContext) {
2565 // all PDPs in all groups need to be updated/sync'd
2566 Set<OnapPDPGroup> groups;
2568 groups = papEngine.getOnapPDPGroups();
2569 } catch (PAPException e) {
2570 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2571 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2573 for (OnapPDPGroup group : groups) {
2574 groupChanged(group, loggingContext);
2579 public void groupChanged(OnapPDPGroup group) {
2580 // all PDPs within one group need to be updated/sync'd
2581 for (OnapPDP pdp : group.getOnapPdps()) {
2586 public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
2587 // all PDPs within one group need to be updated/sync'd
2588 for (OnapPDP pdp : group.getOnapPdps()) {
2589 pdpChanged(pdp, loggingContext);
2594 public void pdpChanged(OnapPDP pdp) {
2595 // kick off a thread to do an event notification for each PDP.
2596 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2597 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2598 Thread t = new Thread(new UpdatePDPThread(pdp));
2599 if(CheckPDP.validateID(pdp.getId())){
2604 public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2605 // kick off a thread to do an event notification for each PDP.
2606 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2607 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2608 Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
2609 if(CheckPDP.validateID(pdp.getId())){
2614 private class UpdatePDPThread implements Runnable {
2615 private OnapPDP pdp;
2616 private String requestId;
2617 private ONAPLoggingContext loggingContext;
2619 public UpdatePDPThread(OnapPDP pdp) {
2623 public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2625 if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
2626 this.requestId = loggingContext.getRequestID();
2628 this.loggingContext = loggingContext;
2632 // send the current configuration to one PDP
2633 HttpURLConnection connection = null;
2634 // get a new logging context for the thread
2636 if (this.loggingContext == null) {
2637 loggingContext = new ONAPLoggingContext(baseLoggingContext);
2639 } catch (Exception e) {
2640 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2641 // Since this is a server-side error, it probably does not reflect a problem on the client,
2642 // so do not change the PDP status.
2646 loggingContext.setServiceName("PAP:PDP.putConfig");
2647 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2648 if ((requestId == null) || (requestId == "")) {
2649 UUID requestID = UUID.randomUUID();
2650 loggingContext.setRequestID(requestID.toString());
2651 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
2653 loggingContext.setRequestID(requestId);
2654 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
2656 loggingContext.transactionStarted();
2657 // the Id of the PDP is its URL
2658 if (LOGGER.isDebugEnabled()) {
2659 LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2661 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2662 //TODO (need to change "cache=", implying getting some input saying which to change)
2663 URL url = new URL(pdp.getId() + "?cache=all");
2664 // Open up the connection
2665 connection = (HttpURLConnection)url.openConnection();
2666 // Setup our method and headers
2667 connection.setRequestMethod("PUT");
2669 String encoding = CheckPDP.getEncoding(pdp.getId());
2670 if(encoding !=null){
2671 connection.setRequestProperty("Authorization", "Basic " + encoding);
2673 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2674 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2675 connection.setInstanceFollowRedirects(true);
2676 connection.setDoOutput(true);
2677 try (OutputStream os = connection.getOutputStream()) {
2678 OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2679 // if the PDP was just deleted, there is no group, but we want to send an update anyway
2680 if (group == null) {
2681 // create blank properties files
2682 Properties policyProperties = new Properties();
2683 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2684 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2685 policyProperties.store(os, "");
2686 Properties pipProps = new Properties();
2687 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2688 pipProps.store(os, "");
2690 // send properties from the current group
2691 group.getPolicyProperties().store(os, "");
2692 Properties policyLocations = new Properties();
2693 for (PDPPolicy policy : group.getPolicies()) {
2694 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2696 policyLocations.store(os, "");
2697 group.getPipConfigProperties().store(os, "");
2699 } catch (Exception e) {
2700 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2701 // Since this is a server-side error, it probably does not reflect a problem on the client,
2702 // so do not change the PDP status.
2706 loggingContext.metricStarted();
2707 connection.connect();
2708 loggingContext.metricEnded();
2709 PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
2710 if (connection.getResponseCode() == 204) {
2711 LOGGER.info("Success. We are configured correctly.");
2712 loggingContext.transactionEnded();
2713 auditLogger.info("Success. PDP is configured correctly.");
2714 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2715 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2716 } else if (connection.getResponseCode() == 200) {
2717 LOGGER.info("Success. PDP needs to update its configuration.");
2718 loggingContext.transactionEnded();
2719 auditLogger.info("Success. PDP needs to update its configuration.");
2720 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2721 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2723 LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2724 loggingContext.transactionEnded();
2725 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2726 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2727 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2729 } catch (Exception e) {
2731 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2732 loggingContext.transactionEnded();
2733 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2735 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2736 } catch (PAPException e1) {
2738 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2739 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2742 // cleanup the connection
2743 if(connection != null){
2744 connection.disconnect();
2746 // tell the AC to update it's status info
2753 * RESTful Interface from PAP to ACs notifying them of changes
2755 private void notifyAC() {
2756 // kick off a thread to do one event notification for all registered ACs
2757 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2758 // as part of processing this message on their end.
2759 Thread t = new Thread(new NotifyACThread());
2763 private class NotifyACThread implements Runnable {
2765 List<String> disconnectedACs = new ArrayList<>();
2766 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2767 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2768 for (String acURL : adminConsoleURLStringList) {
2769 HttpURLConnection connection = null;
2771 acURL += "?PAPNotification=true";
2772 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
2773 //TODO - If so, put correct parameters into the Query string here
2774 acURL += "&objectType=all" + "&action=update";
2775 if (LOGGER.isDebugEnabled()) {
2776 LOGGER.debug("creating url for id '" + acURL + "'");
2778 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2779 //TODO (need to change "cache=", implying getting some input saying which to change)
2780 URL url = new URL(acURL );
2781 // Open up the connection
2782 connection = (HttpURLConnection)url.openConnection();
2783 // Setup our method and headers
2784 connection.setRequestMethod("PUT");
2785 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2786 // Adding this in. It seems the HttpUrlConnection class does NOT
2787 // properly forward our headers for POST re-direction. It does so
2788 // for a GET re-direction.
2789 // So we need to handle this ourselves.
2790 //TODO - is this needed for a PUT? seems better to leave in for now?
2791 connection.setInstanceFollowRedirects(false);
2792 // Do not include any data in the PUT because this is just a
2793 // notification to the AC.
2794 // The AC will use GETs back to the PAP to get what it needs
2795 // to fill in the screens.
2797 connection.connect();
2798 if (connection.getResponseCode() == 204) {
2799 LOGGER.info("Success. We updated correctly.");
2801 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2804 } catch (Exception e) {
2805 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2806 disconnectedACs.add(acURL);
2808 // cleanup the connection
2809 if(connection != null)
2810 connection.disconnect();
2813 // remove any ACs that are no longer connected
2814 if (disconnectedACs.size() > 0) {
2815 adminConsoleURLStringList.removeAll(disconnectedACs);
2820 private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2821 LOGGER.info("Test request received");
2823 im.evaluateSanity();
2824 //If we make it this far, all is well
2825 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2826 LOGGER.info(message);
2827 loggingContext.transactionEnded();
2828 PolicyLogger.audit("Transaction Failed - See Error.log");
2829 response.setStatus(HttpServletResponse.SC_OK);
2831 }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
2833 if (e instanceof ForwardProgressException) {
2834 submsg = " is not making forward progress.";
2835 } else if (e instanceof AdministrativeStateException) {
2836 submsg = " Administrative State is LOCKED.";
2838 submsg = " Standby Status is NOT PROVIDING SERVICE.";
2841 String message = "GET:/pap/test called and PAP " + papResourceName + submsg
2842 + " Exception Message: " + e.getMessage();
2843 LOGGER.info(message, e);
2844 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2845 loggingContext.transactionEnded();
2846 PolicyLogger.audit("Transaction Failed - See Error.log");
2847 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2849 }catch (Exception e) {
2850 //A subsystem is not making progress, is locked, standby or is not responding
2851 String eMsg = e.getMessage();
2853 eMsg = "No Exception Message";
2855 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2856 + " Exception Message: " + eMsg;
2857 LOGGER.info(message, e);
2858 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2859 loggingContext.transactionEnded();
2860 PolicyLogger.audit("Transaction Failed - See Error.log");
2861 //Get the specific list of subsystems that failed
2862 String ssFailureList = null;
2863 for(String failedSS : papDependencyGroupsFlatArray){
2864 if(eMsg.contains(failedSS)){
2865 if(ssFailureList == null){
2866 ssFailureList = failedSS;
2868 ssFailureList = ssFailureList.concat(","+failedSS);
2872 if(ssFailureList == null){
2873 ssFailureList = "UnknownSubSystem";
2875 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2876 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2882 * Authorizing the PEP Requests.
2884 private boolean authorizeRequest(HttpServletRequest request) {
2885 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2886 // Check if the Client is Authorized.
2887 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2894 private static void loadWebapps() throws PAPException{
2895 if(actionHome == null || configHome == null){
2896 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2898 if (webappsPath == null) {
2899 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2900 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2902 Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2903 Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2904 if (Files.notExists(webappsPathConfig)) {
2906 Files.createDirectories(webappsPathConfig);
2907 } catch (IOException e) {
2908 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2909 + webappsPathConfig.toAbsolutePath().toString());
2912 if (Files.notExists(webappsPathAction)) {
2914 Files.createDirectories(webappsPathAction);
2915 } catch (IOException e) {
2916 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2917 + webappsPathAction.toAbsolutePath().toString(), e);
2920 actionHome = webappsPathAction.toString();
2921 configHome = webappsPathConfig.toString();
2925 public static String getConfigHome(){
2928 } catch (PAPException e) {
2935 private static void setConfigHome(){
2936 configHome = getConfigHome();
2939 public static String getActionHome(){
2942 } catch (PAPException e) {
2949 private static void setActionHome(){
2950 actionHome = getActionHome();
2953 public static EntityManagerFactory getEmf() {
2957 public IntegrityAudit getIa() {
2961 public static String getPDPFile(){
2962 return XACMLPapServlet.pdpFile;
2965 public static String getPersistenceUnit(){
2966 return PERSISTENCE_UNIT;
2969 public static PAPPolicyEngine getPAPEngine(){
2973 public static PolicyDBDaoTransaction getDbDaoTransaction(){
2974 return policyDBDao.getNewTransaction();
2976 public static String getPapDbDriver() {
2980 public static void setPapDbDriver(String papDbDriver) {
2981 XACMLPapServlet.papDbDriver = papDbDriver;
2984 public static String getPapDbUrl() {
2988 public static void setPapDbUrl(String papDbUrl) {
2989 XACMLPapServlet.papDbUrl = papDbUrl;
2992 public static String getPapDbUser() {
2996 public static void setPapDbUser(String papDbUser) {
2997 XACMLPapServlet.papDbUser = papDbUser;
3000 public static String getPapDbPassword() {
3001 return papDbPassword;
3004 public static void setPapDbPassword(String papDbPassword) {
3005 XACMLPapServlet.papDbPassword = papDbPassword;
3008 public static String getMsOnapName() {
3012 public static void setMsOnapName(String msOnapName) {
3013 XACMLPapServlet.msOnapName = msOnapName;
3016 public static String getMsPolicyName() {
3017 return msPolicyName;
3020 public static void setMsPolicyName(String msPolicyName) {
3021 XACMLPapServlet.msPolicyName = msPolicyName;