X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=ONAP-PAP-REST%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Fpap%2Fxacml%2Frest%2FXACMLPapServlet.java;h=680c4d579a679b10c075dbefbca4d6d61552cf05;hb=8f4e03b0867eada5220f78a3988865851443b7da;hp=4406ad3da33fe2bf9378c9a9f1eaf1ff897cbfea;hpb=4068da123ee33b532b4b52f15545c76a978f977e;p=policy%2Fengine.git diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java index 4406ad3da..680c4d579 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -41,6 +41,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Properties; import java.util.Scanner; import java.util.Set; @@ -108,14 +109,15 @@ import com.google.common.base.Splitter; */ @WebServlet( description = "Implements the XACML PAP RESTful API.", - urlPatterns = { "/" }, - loadOnStartup=1, + urlPatterns = {"/"}, + loadOnStartup = 1, initParams = { - @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.") + @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", + description = "The location of the properties file holding configuration information.") }) public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable { private static final long serialVersionUID = 1L; - private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class); + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class); // audit (transaction) LOGGER private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); //Persistence Unit for JPA @@ -210,32 +212,42 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ setCommonProperties(); String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); - if(papSiteName == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry"); + if (papSiteName == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", + " ERROR: Bad papSiteName property entry"); throw new PAPException("papSiteName is null"); } String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE); - if(papNodeType == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry"); + if (papNodeType == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", + " ERROR: Bad papNodeType property entry"); throw new PAPException("papNodeType is null"); } //Integer will throw an exception of anything is missing or unrecognized int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); - int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int papTransTimeout = + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); + int papAuditTimeout = + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); //Boolean will default to false if anything is missing or unrecognized - boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); - boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); + boolean papAuditFlag = + Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); + boolean papFileSystemAudit = + Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); - if(papDependencyGroups == null){ + if (papDependencyGroups == null) { throw new PAPException("papDependencyGroups is null"); } setPAPDependencyGroups(papDependencyGroups); //Integer will throw an exception of anything is missing or unrecognized - int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); - int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); - int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); - int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); + int fpMonitorInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); + int failedCounterThreshold = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); + int testTransInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); + int writeFpcInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); LOGGER.debug("\n\n\n**************************************" + "\n*************************************" + "\n" @@ -268,15 +280,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList + "properties = " + properties + "\n\n**************************************"); } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: " - + "XACMLProperties.getProperties()"); + PolicyLogger + .error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: " + + "XACMLProperties.getProperties()"); throw new ServletException(e.getMessage(), e.getCause()); } // Create an IntegrityMonitor - if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){ - properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, ""))); + if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) { + properties.setProperty(PERSISTENCE_JDBC_PWD, + CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, ""))); } - im = IntegrityMonitor.getInstance(papResourceName,properties); + im = IntegrityMonitor.getInstance(papResourceName, properties); // Create an IntegrityAudit ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties); ia.startAuditThread(); @@ -288,7 +302,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList //Create the policyDBDao setPolicyDBDao(); // Load our PAP engine, first create a factory - ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); + ONAPPapEngineFactory factory = ONAPPapEngineFactory + .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); // The factory knows how to go about creating a PAP Engine setPAPEngine((PAPPolicyEngine) factory.newEngine()); PolicyDBDaoTransaction addNewGroup = null; @@ -311,7 +326,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine); - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){ + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) { /* * Auditing the local File System groups to be in sync with the Database */ @@ -324,18 +339,19 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList //get the current filesystem group and update from the database if needed StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup(); StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group); - if(updatedGroup!=null) { + if (updatedGroup != null) { papEngine.updateGroup(updatedGroup); - } + } LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString()); - + //release the transaction lock auditTrans.close(); } // Sanity check for URL. if (XACMLPapServlet.papURL == null) { - throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL); + throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + + XACMLPapServlet.papURL); } // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration // to all its known PDP nodes. @@ -347,10 +363,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } catch (FactoryException | PAPException e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine"); - throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e); + throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e); } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error"); - throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Failed to create engine - unexpected error"); + throw new ServletException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e); } } @@ -359,7 +377,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList initiateThread.start(); } - private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) { + private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) { try { mapper.writeValue(response.getOutputStream(), value); } catch (Exception e) { @@ -377,14 +395,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf()); } catch (Exception e) { - throw new ServletException("Unable to Create Policy DBDao Instance",e); + throw new ServletException("Unable to Create Policy DBDao Instance", e); } } private static void setEMF(Properties properties) throws ServletException { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); if (emf == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: " + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + + " Error creating entity manager factory with persistence unit: " + PERSISTENCE_UNIT); throw new ServletException("Unable to create Entity Manager Factory"); } @@ -399,24 +418,26 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException { - try{ + try { //Now we have flattened the array into a simple comma-separated list papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]"); //clean up the entries - for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){ + for (int i = 0; i < papDependencyGroupsFlatArray.length; i++) { papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); } - try{ - if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){ - papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); + try { + if (XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) { + papIntegrityAuditPeriodSeconds = Integer.parseInt( + XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); } - }catch(Exception e){ + } catch (Exception e) { String msg = "integrity_audit_period_seconds "; LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n"); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", + " ERROR: " + msg + "Bad property entry"); throw e; } - }catch(Exception e){ + } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); throw new PAPException(e); } @@ -426,46 +447,52 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setConfigHome(); setActionHome(); papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - if(papDbDriver == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry"); + if (papDbDriver == null) { + PolicyLogger + .error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbDriver property entry"); throw new PAPException("papDbDriver is null"); } setPapDbDriver(papDbDriver); papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - if(papDbUrl == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); + if (papDbUrl == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); throw new PAPException("papDbUrl is null"); } setPapDbUrl(papDbUrl); papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - if(papDbUser == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry"); + if (papDbUser == null) { + PolicyLogger + .error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbUser property entry"); throw new PAPException("papDbUser is null"); } setPapDbUser(papDbUser); - papDbPassword = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "")); - if(papDbPassword == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry"); + papDbPassword = CryptoUtils + .decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "")); + if (papDbPassword == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", + " ERROR: Bad papDbPassword property entry"); throw new PAPException("papDbPassword is null"); } setPapDbPassword(papDbPassword); papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME); - if(papResourceName == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry"); + if (papResourceName == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", + " ERROR: Bad papResourceName property entry"); throw new PAPException("papResourceName is null"); } environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); //Micro Service Properties - msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName"); + msOnapName = XACMLProperties.getProperty("xacml.policy.msOnapName"); setMsOnapName(msOnapName); - msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName"); + msPolicyName = XACMLProperties.getProperty("xacml.policy.msPolicyName"); setMsPolicyName(msPolicyName); // PDPId File location XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); if (XACMLPapServlet.pdpFile == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " - + XACMLRestProperties.PROP_PDP_IDFILE); - throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. "); + + XACMLRestProperties.PROP_PDP_IDFILE); + throw new PAPException("The PDP Id Authentication File Property :" + XACMLRestProperties.PROP_PDP_IDFILE + + " is not Valid. "); } } @@ -481,7 +508,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList /** * @see Servlet#destroy() - * + *

* Depending on how this servlet is run, we may or may not care about cleaning up the resources. * For now we assume that we do care. */ @@ -514,16 +541,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList /** * Called by: - * - PDP nodes to register themselves with the PAP, and - * - Admin Console to make changes in the PDP Groups. + * - PDP nodes to register themselves with the PAP, and + * - Admin Console to make changes in the PDP Groups. * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); loggingContext.transactionStarted(); loggingContext.setServiceName("PAP.post"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + if ((loggingContext.getRequestID() == null) || (Objects.equals(loggingContext.getRequestID(), ""))) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestID(requestID.toString()); PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one"); @@ -536,18 +564,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.startTransaction(); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); - } catch (AdministrativeStateException ae){ + } catch (AdministrativeStateException ae) { String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative" + " state of " + im.getStateManager().getAdminState() - + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION; + + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION; LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; - }catch (StandbyStatusException se) { + } catch (StandbyStatusException se) { String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status" + " of " + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + se.getMessage(); @@ -556,7 +584,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } catch (IntegrityMonitorException e) { String message = "POST interface called for PAP " + papResourceName + " but an exception occurred" @@ -566,7 +594,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } try { @@ -579,16 +607,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList request.getInputStream(); String groupId = request.getParameter("groupId"); String apiflag = request.getParameter("apiflag"); - if(groupId != null) { + if (groupId != null) { // Is this from the Admin Console or API? - if(apiflag!=null && apiflag.equalsIgnoreCase("api")) { + if (apiflag != null && apiflag.equalsIgnoreCase("api")) { // this is from the API so we need to check the client credentials before processing the request - if(!authorizeRequest(request)){ + if (!authorizeRequest(request)) { String message = "PEP not Authorized for making this Request!!"; PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message); im.endTransaction(); return; } @@ -614,11 +642,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (pdp == null) { LOGGER.info("Unknown PDP: " + id); // Check PDP ID - if(CheckPDP.validateID(id)){ + if (CheckPDP.validateID(id)) { pdpTransaction = policyDBDao.getNewTransaction(); try { - pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister"); - XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport)); + pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, + "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister"); + XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, + "Registered on first startup", Integer.parseInt(jmxport)); } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) { pdpTransaction.rollbackTransaction(); String message = "Failed to create new PDP for id: " + id; @@ -630,13 +660,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } // get the PDP we just created - try{ + try { pdp = XACMLPapServlet.papEngine.getPDP(id); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } if (pdp == null) { - if(pdpTransaction != null){ + if (pdpTransaction != null) { pdpTransaction.rollbackTransaction(); } String message = "Failed to create new PDP for id: " + id; @@ -648,42 +678,47 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } } else { - String message = "PDP is Unauthorized to Connect to PAP: "+ id; + String message = "PDP is Unauthorized to Connect to PAP: " + id; loggingContext.transactionEnded(); PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration."); + setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, + "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration" + + "."); PolicyLogger.audit("Transaction Failed - See Error.log"); im.endTransaction(); return; } - try{ + try { loggingContext.metricStarted(); pdpTransaction.commitTransaction(); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + "Could not commit transaction to put pdp in the database"); } } - if (jmxport != null && jmxport != ""){ - try{ + if (jmxport != null && !Objects.equals(jmxport, "")) { + try { ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport)); - }catch(NumberFormatException e){ + } catch (NumberFormatException e) { LOGGER.error(e); } } // Get the PDP's Group - OnapPDPGroup group =null; - try{ - group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp); - }catch(PAPException e){ + OnapPDPGroup group = null; + try { + group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp); + } catch (PAPException e) { LOGGER.error(e); } if (group == null) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + + " PDP not associated with any group, even the default"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default"); + setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, + "PDP not associated with any group, even the default"); im.endTransaction(); return; } @@ -693,9 +728,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Properties pipconfig = group.getPipConfigProperties(); // Get the current policy/pip configuration that the PDP has Properties pdpProperties = new Properties(); - try{ + try { pdpProperties.load(request.getInputStream()); - }catch(IOException e){ + } catch (IOException e) { LOGGER.error(e); } LOGGER.info("PDP Current Properties: " + pdpProperties.toString()); @@ -712,33 +747,33 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // retrieve them. this.populatePolicyURL(request.getRequestURL(), policies); // Copy the properties to the output stream - try{ + try { policies.store(response.getOutputStream(), ""); - }catch(IOException e){ + } catch (IOException e) { LOGGER.error(e); } } if (pipconfig != null) { // Copy the properties to the output stream - try{ + try { pipconfig.store(response.getOutputStream(), ""); - }catch(IOException e){ + } catch (IOException e) { LOGGER.error(e); } } // We are good - and we are sending them information response.setStatus(HttpServletResponse.SC_OK); - try{ + try { setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } } else { // Tell them they are good response.setStatus(HttpServletResponse.SC_NO_CONTENT); - try{ + try { setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } } @@ -751,7 +786,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); } catch (PAPException | IOException | NumberFormatException e) { - if(pdpTransaction != null){ + if (pdpTransaction != null) { pdpTransaction.rollbackTransaction(); } LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); @@ -767,233 +802,237 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.endTransaction(); } - private void setResponseError(HttpServletResponse response,int responseCode, String message) { + private void setResponseError(HttpServletResponse response, int responseCode, String message) { try { - if(message != null && !message.isEmpty()){ - response.sendError(responseCode, message); + if (message != null && !message.isEmpty()) { + response.sendError(responseCode, message); } } catch (IOException e) { LOGGER.error("Error setting Error response Header ", e); } - return; } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); loggingContext.transactionStarted(); loggingContext.setServiceName("PAP.get"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + if ((loggingContext.getRequestID() == null) || (Objects.equals(loggingContext.getRequestID(), ""))) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestID(requestID.toString()); PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one"); } else { PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)"); } - loggingContext.metricStarted(); - XACMLRest.dumpRequest(request); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest"); - String pathInfo = request.getRequestURI(); - LOGGER.info("path info: " + pathInfo); - if (pathInfo != null){ - //DO NOT do a im.startTransaction for the test request - if (pathInfo.equals("/pap/test")) { - try { - testService(loggingContext, response); - } catch (IOException e) { - LOGGER.debug(e); - } - return; + loggingContext.metricStarted(); + XACMLRest.dumpRequest(request); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest"); + String pathInfo = request.getRequestURI(); + LOGGER.info("path info: " + pathInfo); + if (pathInfo != null) { + //DO NOT do a im.startTransaction for the test request + if (pathInfo.equals("/pap/test")) { + try { + testService(loggingContext, response); + } catch (IOException e) { + LOGGER.debug(e); } - } - //This im.startTransaction() covers all other Get transactions - try { - loggingContext.metricStarted(); - im.startTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction"); - } catch (AdministrativeStateException ae){ - String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() - + "\n Exception Message: " + ae.getMessage(); - LOGGER.info(message, ae); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (StandbyStatusException se) { - String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status" - + " of " + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " + se.getMessage(); - LOGGER.info(message, se); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - } catch (IntegrityMonitorException e) { - String message = "GET interface called for PAP " + papResourceName + " but an exception occurred" - + "\n Exception Message: " + e.getMessage(); - LOGGER.info(message, e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } - // Request from the API to get the gitPath - String apiflag = request.getParameter("apiflag"); - if (apiflag!=null) { - if(authorizeRequest(request)){ - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - try{ - loggingContext.metricStarted(); - apiRequestHandler.doGet(request,response, apiflag); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet"); - }catch(IOException e){ - LOGGER.error(e); - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } else { - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message); - im.endTransaction(); - return; - } - } - // Is this from the Admin Console? - String groupId = request.getParameter("groupId"); - if (groupId != null) { - // this is from the Admin Console, so handle separately - try{ + } + //This im.startTransaction() covers all other Get transactions + try { + loggingContext.metricStarted(); + im.startTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction"); + } catch (AdministrativeStateException ae) { + String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative" + + " state of " + im.getStateManager().getAdminState() + + "\n Exception Message: " + ae.getMessage(); + LOGGER.info(message, ae); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } catch (StandbyStatusException se) { + String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status" + + " of " + im.getStateManager().getStandbyStatus() + + "\n Exception Message: " + se.getMessage(); + LOGGER.info(message, se); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } catch (IntegrityMonitorException e) { + String message = "GET interface called for PAP " + papResourceName + " but an exception occurred" + + "\n Exception Message: " + e.getMessage(); + LOGGER.info(message, e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } + // Request from the API to get the gitPath + String apiflag = request.getParameter("apiflag"); + if (apiflag != null) { + if (authorizeRequest(request)) { + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + try { loggingContext.metricStarted(); - doACGet(request, response, groupId, loggingContext); + apiRequestHandler.doGet(request, response, apiflag); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doGet doACGet"); - } catch(IOException e){ + PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet"); + } catch (IOException e) { LOGGER.error(e); } loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Ended Successfully"); im.endTransaction(); return; - } - // Get the PDP's ID - String id = this.getPDPID(request); - LOGGER.info("doGet from: " + id); - // Get the PDP Object - OnapPDP pdp = null; - try{ - pdp = XACMLPapServlet.papEngine.getPDP(id); - }catch(PAPException e){ - LOGGER.error(e); - } - // Is it known? - if (pdp == null) { - // Check if request came from localhost - if (request.getRemoteHost().equals("localhost") || - request.getRemoteHost().equals(request.getLocalAddr())) { - // Return status information - basically all the groups - loggingContext.setServiceName("PAP.getGroups"); - Set groups = null; - try { - groups = papEngine.getOnapPDPGroups(); - } catch(PAPException e) { - LOGGER.debug(e); - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - im.endTransaction(); - return; - } - // convert response object to JSON and include in the response - mapperWriteValue(new ObjectMapper(), response, groups); - response.setHeader("content-type", "application/json"); - response.setStatus(HttpServletResponse.SC_OK); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr(); + } else { + String message = + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message); + setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message); im.endTransaction(); return; } - loggingContext.setServiceName("PAP.getPolicy"); - // Get the PDP's Group - OnapPDPGroup group = null; + } + // Is this from the Admin Console? + String groupId = request.getParameter("groupId"); + if (groupId != null) { + // this is from the Admin Console, so handle separately try { - group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp); - } catch (PAPException e) { - LOGGER.error(e); - } - if (group == null) { - String message = "No group associated with pdp " + pdp.getId(); - LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message); - im.endTransaction(); - return; - } - // Which policy do they want? - String policyId = request.getParameter("id"); - if (policyId == null) { - String message = "Did not specify an id for the policy"; - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); - im.endTransaction(); - return; - } - PDPPolicy policy = group.getPolicy(policyId); - if (policy == null) { - String message = "Unknown policy: " + policyId; - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); - im.endTransaction(); - return; - } - try{ - LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " - + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString()); - } catch (PAPException| IOException e){ + loggingContext.metricStarted(); + doACGet(request, response, groupId, loggingContext); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doGet doACGet"); + } catch (IOException e) { LOGGER.error(e); } - try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) { - // Send the policy back - IOUtils.copy(is, os); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + // Get the PDP's ID + String id = this.getPDPID(request); + LOGGER.info("doGet from: " + id); + // Get the PDP Object + OnapPDP pdp = null; + try { + pdp = XACMLPapServlet.papEngine.getPDP(id); + } catch (PAPException e) { + LOGGER.error(e); + } + // Is it known? + if (pdp == null) { + // Check if request came from localhost + if (request.getRemoteHost().equals("localhost") || + request.getRemoteHost().equals(request.getLocalAddr())) { + // Return status information - basically all the groups + loggingContext.setServiceName("PAP.getGroups"); + Set groups = null; + try { + groups = papEngine.getOnapPDPGroups(); + } catch (PAPException e) { + LOGGER.debug(e); + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + im.endTransaction(); + return; + } + // convert response object to JSON and include in the response + mapperWriteValue(new ObjectMapper(), response, groups); + response.setHeader("content-type", "application/json"); response.setStatus(HttpServletResponse.SC_OK); loggingContext.transactionEnded(); - auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); - } catch (IOException e) { - String message = "Failed to open policy id " + policyId; - LOGGER.debug(e); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); + im.endTransaction(); + return; } + String message = + "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr(); + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message); + im.endTransaction(); + return; + } + loggingContext.setServiceName("PAP.getPolicy"); + // Get the PDP's Group + OnapPDPGroup group = null; + try { + group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp); + } catch (PAPException e) { + LOGGER.error(e); + } + if (group == null) { + String message = "No group associated with pdp " + pdp.getId(); + LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message); + im.endTransaction(); + return; + } + // Which policy do they want? + String policyId = request.getParameter("id"); + if (policyId == null) { + String message = "Did not specify an id for the policy"; + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message); + im.endTransaction(); + return; + } + PDPPolicy policy = group.getPolicy(policyId); + if (policy == null) { + String message = "Unknown policy: " + policyId; + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message); + im.endTransaction(); + return; + } + try { + LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString()); + } catch (PAPException | IOException e) { + LOGGER.error(e); + } + try (InputStream is = new FileInputStream( + ((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId); + OutputStream os = response.getOutputStream()) { + // Send the policy back + IOUtils.copy(is, os); + response.setStatus(HttpServletResponse.SC_OK); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + } catch (IOException e) { + String message = "Failed to open policy id " + policyId; + LOGGER.debug(e); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message); + } loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Ended"); im.endTransaction(); @@ -1002,11 +1041,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList /** * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) */ - protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doPut(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); loggingContext.transactionStarted(); loggingContext.setServiceName("PAP.put"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + if ((loggingContext.getRequestID() == null) || (Objects.equals(loggingContext.getRequestID(), ""))) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestID(requestID.toString()); PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one"); @@ -1022,10 +1062,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String message = "PUT interface called for PAP " + papResourceName; if (e instanceof AdministrativeStateException) { message += " but it has an Administrative state of " - + im.getStateManager().getAdminState(); + + im.getStateManager().getAdminState(); } else if (e instanceof StandbyStatusException) { message += " but it has a Standby Status of " - + im.getStateManager().getStandbyStatus(); + + im.getStateManager().getStandbyStatus(); } else { message += " but an exception occurred"; @@ -1036,7 +1076,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } @@ -1048,13 +1088,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String apiflag = request.getParameter("apiflag"); //This would occur if a PolicyDBDao notification was received String policyDBDaoRequestUrl = request.getParameter("policydbdaourl"); - if(policyDBDaoRequestUrl != null){ - LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." ); + if (policyDBDaoRequestUrl != null) { + LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received."); String policyDBDaoRequestEntityId = request.getParameter("entityid"); String policyDBDaoRequestEntityType = request.getParameter("entitytype"); String policyDBDaoRequestExtraData = request.getParameter("extradata"); - if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){ - setResponseError(response,400, "entityid or entitytype not supplied"); + if (policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null) { + setResponseError(response, 400, "entityid or entitytype not supplied"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Ended Successfully"); im.endTransaction(); @@ -1062,7 +1102,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } loggingContext.metricStarted(); LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification"); - policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this); + policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl, policyDBDaoRequestEntityId, + policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification"); response.setStatus(200); @@ -1076,24 +1117,25 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ String importService = request.getParameter("importService"); if (importService != null) { - if(authorizeRequest(request)){ + if (authorizeRequest(request)) { APIRequestHandler apiRequestHandler = new APIRequestHandler(); - try{ + try { loggingContext.metricStarted(); apiRequestHandler.doPut(request, response, importService); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut"); - }catch(IOException e){ + } catch (IOException e) { LOGGER.error(e); } im.endTransaction(); return; } else { - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message ); + String message = + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message); return; } } @@ -1104,7 +1146,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (acURLString != null) { loggingContext.setServiceName("AC:PAP.register"); // remember this Admin Console for future updates - if ( ! adminConsoleURLStringList.contains(acURLString)) { + if (!adminConsoleURLStringList.contains(acURLString)) { adminConsoleURLStringList.add(acURLString); } if (LOGGER.isDebugEnabled()) { @@ -1124,19 +1166,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ String groupId = request.getParameter("groupId"); if (groupId != null) { - if(apiflag!=null){ - if(!authorizeRequest(request)){ - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + if (apiflag != null) { + if (!authorizeRequest(request)) { + String message = + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message); return; } - if(apiflag.equalsIgnoreCase("addPolicyToGroup")){ - try{ + if (apiflag.equalsIgnoreCase("addPolicyToGroup")) { + try { updateGroupsFromAPI(request, response, groupId, loggingContext); - }catch(IOException e){ + } catch (IOException e) { LOGGER.error(e); } loggingContext.transactionEnded(); @@ -1162,10 +1205,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // // Request is for policy validation and creation // - if (apiflag != null && apiflag.equalsIgnoreCase("admin")){ + if (apiflag != null && apiflag.equalsIgnoreCase("admin")) { // this request is from the Admin Console SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance(); - try{ + try { loggingContext.metricStarted(); savePolicyHandler.doPolicyAPIPut(request, response); loggingContext.metricEnded(); @@ -1179,9 +1222,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) { // this request is from the Policy Creation API - if(authorizeRequest(request)){ + if (authorizeRequest(request)) { APIRequestHandler apiRequestHandler = new APIRequestHandler(); - try{ + try { loggingContext.metricStarted(); apiRequestHandler.doPut(request, response, request.getHeader("ClientScope")); loggingContext.metricEnded(); @@ -1198,7 +1241,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message); im.endTransaction(); return; } @@ -1208,7 +1251,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See error.log"); im.endTransaction(); @@ -1217,11 +1260,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList /** * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response) */ - protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doDelete(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); loggingContext.transactionStarted(); loggingContext.setServiceName("PAP.delete"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + if ((loggingContext.getRequestID() == null) || (Objects.equals(loggingContext.getRequestID(), ""))) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestID(requestID.toString()); PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one"); @@ -1233,7 +1277,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.startTransaction(); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction"); - } catch (AdministrativeStateException ae){ + } catch (AdministrativeStateException ae) { String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative" + " state of " + im.getStateManager().getAdminState() + "\n Exception Message: " + ae.getMessage(); @@ -1241,9 +1285,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; - }catch (StandbyStatusException se) { + } catch (StandbyStatusException se) { String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status" + " of " + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + se.getMessage(); @@ -1251,7 +1295,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } catch (IntegrityMonitorException e) { String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred" @@ -1260,7 +1304,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } loggingContext.metricStarted(); @@ -1271,13 +1315,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String apiflag = request.getParameter("apiflag"); if (groupId != null) { // Is this from the Admin Console or API? - if(apiflag!=null) { - if(!authorizeRequest(request)){ - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + if (apiflag != null) { + if (!authorizeRequest(request)) { + String message = + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message); return; } APIRequestHandler apiRequestHandler = new APIRequestHandler(); @@ -1287,15 +1332,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete"); } catch (Exception e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } - if(apiRequestHandler.getNewGroup()!=null){ + if (apiRequestHandler.getNewGroup() != null) { groupChanged(apiRequestHandler.getNewGroup(), loggingContext); } return; } // this is from the Admin Console, so handle separately - try{ + try { loggingContext.metricStarted(); doACDelete(request, response, groupId, loggingContext); loggingContext.metricEnded(); @@ -1312,7 +1357,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); im.endTransaction(); } @@ -1320,7 +1365,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); if (localRootPolicies == null || localReferencedPolicies == null) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies); + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies=" + + localRootPolicies + " ReferencedPolicies=" + localReferencedPolicies); return false; } // Compare the policies and pipconfig properties to the pdpProperties @@ -1373,7 +1419,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT); if (pdpJMMX == null || pdpJMMX.isEmpty()) { // Should send back its port for identification - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned"); + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + + "PDP did not send custom header for JMX Port so the value of 0 is assigned"); return null; } return pdpJMMX; @@ -1389,7 +1436,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException { + public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, + ONAPLoggingContext loggingContext) throws IOException { PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI"); try { @@ -1400,7 +1448,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String json = null; java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; + json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); PolicyLogger.info("pushPolicy request from API: " + json); @@ -1413,8 +1461,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList currentPoliciesInGroup = group.getPolicies(); //If the selected policy is in the group we must remove the old version of it LOGGER.info("Removing old version of the policy"); - for(PDPPolicy existingPolicy : currentPoliciesInGroup) { - if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){ + for (PDPPolicy existingPolicy : currentPoliciesInGroup) { + if (existingPolicy.getName().equals(policy.getName()) && + !existingPolicy.getId().equals(policy.getId())) { group.removePolicy(existingPolicy); LOGGER.info("Removing policy: " + existingPolicy); break; @@ -1423,23 +1472,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Assume that this is an update of an existing PDP Group loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); - try{ + try { acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " - +"group="+group.getId()); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " Error while updating group in the database: " + + "group=" + group.getId()); throw new PAPException(e.getMessage()); } LOGGER.info("Calling updatGroup() with new group"); papEngine.updateGroup(group); String policyId = "empty"; - if(policy !=null && policy.getId() != null){ + if (policy != null && policy.getId() != null) { policyId = policy.getId(); } - if(!policyId.matches(REGEX) ){ + if (!policyId.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", "Policy Id is not valid"); return; } @@ -1464,7 +1514,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); LOGGER.info("Success"); - if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { + if (policy != null && + ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); if (pushPolicyHandler.preSafetyCheck(policy, configHome)) { LOGGER.debug("Precheck Successful."); @@ -1472,18 +1523,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } PolicyLogger.audit("Transaction Ended Successfully"); - return; } catch (PAPException e) { acPutTransaction.rollbackTransaction(); PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP."; + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Exception in request to update group from API - See Error.log on on the PAP."; setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", message); - return; } } @@ -1497,18 +1547,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException { + private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, + ONAPLoggingContext loggingContext) throws ServletException, IOException { PolicyDBDaoTransaction doACPostTransaction = null; try { String groupName = request.getParameter("groupName"); String groupDescription = request.getParameter("groupDescription"); String apiflag = request.getParameter("apiflag"); if (groupName != null && groupDescription != null) { - // Args: group= groupName= groupDescription= <= create a new group + // Args: group= groupName= groupDescription= <= create + // a new group loggingContext.setServiceName("AC:PAP.createGroup"); String unescapedName = null; String unescapedDescription = null; - try{ + try { unescapedName = URLDecoder.decode(groupName, "UTF-8"); unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8"); } catch (UnsupportedEncodingException e) { @@ -1516,7 +1568,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction(); try { - newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost"); + newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, + unescapedDescription, "XACMLPapServlet.doACPost"); papEngine.newGroup(unescapedName, unescapedDescription); loggingContext.metricStarted(); newGroupTransaction.commitTransaction(); @@ -1524,10 +1577,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); } catch (Exception e) { newGroupTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " Unable to create new group"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "Unable to create new group '" + groupId + "'"); return; } response.setStatus(HttpServletResponse.SC_NO_CONTENT); @@ -1548,30 +1603,30 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // for all remaining POST operations the group must exist before the operation can be done OnapPDPGroup group = null; - try{ + try { group = papEngine.getGroup(groupId); - } catch (PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } if (group == null) { String message = "Unknown groupId '" + groupId + "'"; //for fixing Header Manipulation of Fortify issue - if(!message.matches(REGEX)){ + if (!message.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", "GroupId Id is not valid"); return; } PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - if (apiflag!=null){ + if (apiflag != null) { response.addHeader("error", "unknownGroupId"); response.addHeader("operation", "push"); response.addHeader("message", message); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message); } return; } @@ -1579,7 +1634,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // If the request contains a policyId then we know we are pushing the policy to PDP if (request.getParameter("policyId") != null) { - if(apiflag!=null){ + if (apiflag != null) { loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy"); LOGGER.info("PushPolicy Request From The API"); } else { @@ -1593,7 +1648,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { //Copying the policy to the file system and updating groups in database LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()"); - updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost"); + updatedGroup = addPolicyToGroupTransaction + .addPolicyToGroup(group.getId(), policyId, "XACMLPapServlet.doACPost"); loggingContext.metricStarted(); addPolicyToGroupTransaction.commitTransaction(); loggingContext.metricEnded(); @@ -1602,30 +1658,31 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } catch (Exception e) { addPolicyToGroupTransaction.rollbackTransaction(); - String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e; + String message = "Policy '" + policyId + "' not copied to group '" + groupId + "': " + e; //for fixing Header Manipulation of Fortify issue - if(!message.matches(REGEX)){ + if (!message.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", "Policy Id is not valid"); return; } PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - if (apiflag!=null){ + if (apiflag != null) { response.addHeader("error", "policyCopyError"); response.addHeader("message", message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); } return; } - if(apiflag != null){ + if (apiflag != null) { /* - * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change. + * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other + * paps of the change. * The GUI does this from the POLICY-SDK-APP code. */ @@ -1635,7 +1692,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // get the request content into a String and read the inputStream into a buffer java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); - String json = scanner.hasNext() ? scanner.next() : ""; + String json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); // convert Object sent as JSON into local object @@ -1647,11 +1704,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Assume that this is an update of an existing PDP Group loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); - try{ + try { acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: " - + e); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " Error occurred when notifying PAPs of a group change: " + + e); throw new PAPException(e.getMessage()); } @@ -1672,11 +1730,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC"); // Group changed to send notification to PDPs, which might include changing the policies - groupChanged(updatedGroup,loggingContext); + groupChanged(updatedGroup, loggingContext); loggingContext.transactionEnded(); LOGGER.info("Success"); - if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { + if (policy != null && ((policy.getName().contains("Config_MS_")) || + (policy.getId().contains("BRMS_Param")))) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); if (pushPolicyHandler.preSafetyCheck(policy, configHome)) { LOGGER.debug("Precheck Successful."); @@ -1691,11 +1750,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API."; + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Exception occurred when updating the group from API."; LOGGER.error(message); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", message); return; } @@ -1712,13 +1772,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList auditLogger.info("Success"); LOGGER.info("Transaction Ended Successfully"); - return; } else if (request.getParameter("default") != null) { // Args: group= default=true <= make default // change the current default group to be the one identified in the request. loggingContext.setServiceName("AC:PAP.setDefaultGroup"); - // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed. - // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway. + // This is a POST operation rather than a PUT "update group" because of the side-effect that the + // current default group is also changed. + // It should never be the case that multiple groups are currently marked as the default, but protect + // against that anyway. PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction(); try { setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost"); @@ -1732,7 +1793,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "Unable to set group '" + groupId + "' to default"); return; } response.setStatus(HttpServletResponse.SC_NO_CONTENT); @@ -1740,8 +1802,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.debug("Group '" + groupId + "' set to be default"); } // Notify the Admin Consoles that something changed - // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that - //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups + // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just + // notify on that + //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to + // update whole configuration of all groups loggingContext.metricStarted(); notifyAC(); // This does not affect any PDPs in the existing groups, so no need to notify them of this change @@ -1750,7 +1814,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); auditLogger.info("Success"); LOGGER.info("Transaction Ended Successfully"); - return; } else if (request.getParameter("pdpId") != null) { doACPostTransaction = policyDBDao.getNewTransaction(); // Args: group= pdpId= <= move PDP to group @@ -1758,25 +1821,26 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String pdpId = request.getParameter("pdpId"); OnapPDP pdp = papEngine.getPDP(pdpId); OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp); - try{ + try { doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost"); - }catch(Exception e){ + } catch (Exception e) { doACPostTransaction.rollbackTransaction(); PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while moving pdp in the database: " - +"pdp="+pdp.getId()+",to group="+group.getId()); + + "pdp=" + pdp.getId() + ",to group=" + group.getId()); throw new PAPException(e.getMessage()); } papEngine.movePDP((OnapPDP) pdp, group); response.setStatus(HttpServletResponse.SC_NO_CONTENT); if (LOGGER.isDebugEnabled()) { - LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default"); + LOGGER.debug("PDP '" + pdp.getId() + "' moved to group '" + group.getId() + "' set to be default"); } // update the status of both the original group and the new one - ((StdPDPGroup)originalGroup).resetStatus(); - ((StdPDPGroup)group).resetStatus(); + ((StdPDPGroup) originalGroup).resetStatus(); + ((StdPDPGroup) group).resetStatus(); // Notify the Admin Consoles that something changed - // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that + // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just + // notify on that loggingContext.metricStarted(); notifyAC(); loggingContext.metricEnded(); @@ -1790,14 +1854,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); - return; } } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } @@ -1811,7 +1873,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException { + private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, + ONAPLoggingContext loggingContext) throws IOException { try { String parameterDefault = request.getParameter("default"); String pdpId = request.getParameter("pdpId"); @@ -1823,15 +1886,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.setServiceName("AC:PAP.getDefaultGroup"); OnapPDPGroup group = papEngine.getDefaultGroup(); // convert response object to JSON and include in the response - mapperWriteValue(new ObjectMapper(), response, group); + mapperWriteValue(new ObjectMapper(), response, group); if (LOGGER.isDebugEnabled()) { LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); response.setHeader("content-type", "application/json"); - try{ + try { response.getOutputStream().close(); - } catch (IOException e){ + } catch (IOException e) { LOGGER.error(e); } loggingContext.transactionEnded(); @@ -1844,21 +1907,21 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Request is for the (unspecified) group containing a given PDP loggingContext.setServiceName("AC:PAP.getPDP"); OnapPDP pdp = null; - try{ + try { pdp = papEngine.getPDP(pdpId); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } // convert response object to JSON and include in the response - mapperWriteValue(new ObjectMapper(), response, pdp); + mapperWriteValue(new ObjectMapper(), response, pdp); if (LOGGER.isDebugEnabled()) { LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); response.setHeader("content-type", "application/json"); - try{ + try { response.getOutputStream().close(); - } catch (IOException e){ + } catch (IOException e) { LOGGER.error(e); } loggingContext.transactionEnded(); @@ -1868,23 +1931,23 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } else { // Request is for the group containing a given PDP loggingContext.setServiceName("AC:PAP.getGroupForPDP"); - OnapPDPGroup group =null; - try{ + OnapPDPGroup group = null; + try { OnapPDP pdp = papEngine.getPDP(pdpId); group = papEngine.getPDPGroup((OnapPDP) pdp); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } // convert response object to JSON and include in the response - mapperWriteValue(new ObjectMapper(), response, group); + mapperWriteValue(new ObjectMapper(), response, group); if (LOGGER.isDebugEnabled()) { LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); response.setHeader("content-type", "application/json"); - try{ + try { response.getOutputStream().close(); - } catch (IOException e){ + } catch (IOException e) { LOGGER.error(e); } loggingContext.transactionEnded(); @@ -1898,23 +1961,23 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Set groups = null; try { groups = papEngine.getOnapPDPGroups(); - } catch(PAPException e) { + } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } // convert response object to JSON and include in the response - mapperWriteValue(new ObjectMapper(), response, groups); + mapperWriteValue(new ObjectMapper(), response, groups); if (LOGGER.isDebugEnabled()) { LOGGER.debug("GET All groups req"); } response.setStatus(HttpServletResponse.SC_OK); response.setHeader("content-type", "application/json"); - try{ + try { response.getOutputStream().close(); - } catch (IOException e){ + } catch (IOException e) { LOGGER.error(e); } loggingContext.transactionEnded(); @@ -1925,24 +1988,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // for all other GET operations the group must exist before the operation can be done OnapPDPGroup group = null; - try{ + try { group = papEngine.getGroup(groupId); - } catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } if (group == null) { String message = "Unknown groupId '" + groupId + "'"; //for fixing Header Manipulation of Fortify issue - if(!message.matches(REGEX)){ + if (!message.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", "Group Id is not valid"); return; } PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message); return; } // Figure out which request this is based on the parameters @@ -1954,20 +2017,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented"); } else { // No other parameters, so return the identified Group loggingContext.setServiceName("AC:PAP.getGroup"); // convert response object to JSON and include in the response - mapperWriteValue(new ObjectMapper(), response, group); + mapperWriteValue(new ObjectMapper(), response, group); if (LOGGER.isDebugEnabled()) { LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); response.setHeader("content-type", "application/json"); - try{ + try { response.getOutputStream().close(); - } catch (IOException e){ + } catch (IOException e) { LOGGER.error(e); } loggingContext.transactionEnded(); @@ -1976,7 +2039,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } // Currently there are no other GET calls from the AC. - // 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. + // 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. // Other GETs that could be called: // Specific Group (groupId=) // A Policy (groupId= policyId=) @@ -1984,13 +2048,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED "); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } @@ -2004,7 +2067,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException { + private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, + ONAPLoggingContext loggingContext) throws IOException { PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); try { // for PUT operations the group may or may not need to exist before the operation can be done @@ -2016,19 +2080,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message); return; } if (request.getParameter("policy") != null) { - // group= policy= contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties) + // group= policy= contents=policy file <= Create new policy + // file in group dir, or replace it if it already exists (do not touch properties) loggingContext.setServiceName("AC:PAP.putPolicy"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! "); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! "); response.setStatus(HttpServletResponse.SC_NO_CONTENT); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); - return; } else if (request.getParameter("pdpId") != null) { // ARGS: group= pdpId= <= create a new PDP or Update an Existing one String pdpId = request.getParameter("pdpId"); @@ -2040,12 +2105,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // get the request content into a String String json = null; // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) - try{ + try { Scanner scanner = new Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; + json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - }catch(IOException e){ + } catch (IOException e) { LOGGER.error(e); } LOGGER.info("JSON request from AC: " + json); @@ -2054,54 +2119,58 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Object objectFromJSON = null; try { objectFromJSON = mapper.readValue(json, StdPDP.class); - } catch(Exception e) { + } catch (Exception e) { LOGGER.error(e); } if (pdpId == null || objectFromJSON == null || - ! (objectFromJSON instanceof StdPDP) || - ((StdPDP)objectFromJSON).getId() == null || - ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON); + !(objectFromJSON instanceof StdPDP) || + ((StdPDP) objectFromJSON).getId() == null || + !((StdPDP) objectFromJSON).getId().equals(pdpId)) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + + " objectFromJSON=" + objectFromJSON); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "Bad input pdpid for object:" + objectFromJSON); } StdPDP pdp = (StdPDP) objectFromJSON; - if(pdp != null){ + if (pdp != null) { OnapPDP oPDP = null; - try{ + try { oPDP = papEngine.getPDP(pdpId); - }catch (PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } if (oPDP == null) { // this is a request to create a new PDP object - try{ + try { acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), - pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: " - +"pdp="+ (pdp.getId()) +",to group="+group.getId()); + pdp.getDescription(), pdp.getJmxPort(), "XACMLPapServlet.doACPut"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " Error while adding pdp to group in the database: " + + "pdp=" + (pdp.getId()) + ",to group=" + group.getId()); throw new PAPException(e.getMessage()); } - try{ + try { papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } } else { - try{ + try { acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: " - +"pdp="+ pdp.getId()); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " Error while updating pdp in the database: " + + "pdp=" + pdp.getId()); throw new PAPException(e.getMessage()); } // this is a request to update the pdp - try{ + try { papEngine.updatePDP(pdp); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } } @@ -2110,7 +2179,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.debug("PDP '" + pdpId + "' created/updated"); } // adjust the group's state including the new PDP - ((StdPDPGroup)group).resetStatus(); + ((StdPDPGroup) group).resetStatus(); // tell the Admin Consoles there is a change loggingContext.metricStarted(); notifyAC(); @@ -2125,24 +2194,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); - return; - }else{ - try{ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: " - +"pdp=null" + ",to group="+group.getId()); + } else { + try { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", + " Error while adding pdp to group in the database: " + + "pdp=null" + ",to group=" + group.getId()); throw new PAPException("PDP is null"); - } catch(Exception e){ - throw new PAPException("PDP is null" + e.getMessage() +e); + } catch (Exception e) { + throw new PAPException("PDP is null" + e.getMessage() + e); } } } else if (request.getParameter("pipId") != null) { - // group= pipId= contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation) + // group= pipId= contents=pip properties <= add a + // PIP to pip config, or replace it if it already exists (lenient operation) loggingContext.setServiceName("AC:PAP.putPIP"); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); - return; + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); } else { // Assume that this is an update of an existing PDP Group // ARGS: group= <= Update an Existing Group @@ -2150,12 +2219,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // get the request content into a String String json = null; // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) - try{ + try { Scanner scanner = new Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; + json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - }catch(IOException e){ + } catch (IOException e) { LOGGER.error(e); } LOGGER.info("JSON request from AC: " + json); @@ -2163,44 +2232,47 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList ObjectMapper mapper = new ObjectMapper(); Object objectFromJSON = null; try { - objectFromJSON = mapper.readValue(json, StdPDPGroup.class); - } catch(Exception e) { + objectFromJSON = mapper.readValue(json, StdPDPGroup.class); + } catch (Exception e) { LOGGER.error(e); } - if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) || - ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON); + if (objectFromJSON == null || !(objectFromJSON instanceof StdPDPGroup) || + !((StdPDPGroup) objectFromJSON).getId().equals(group.getId())) { + PolicyLogger + .error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + + " objectFromJSON=" + objectFromJSON); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "Bad input id for object:" + objectFromJSON); } // The Path on the PAP side is not carried on the RESTful interface with the AC // (because it is local to the PAP) // so we need to fill that in before submitting the group for update - if(objectFromJSON != null){ - ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory()); + if (objectFromJSON != null) { + ((StdPDPGroup) objectFromJSON).setDirectory(((StdPDPGroup) group).getDirectory()); } - try{ - if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){ - acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete"); + try { + if ("delete".equals(((StdPDPGroup) objectFromJSON).getOperation())) { + acPutTransaction.updateGroup((StdPDPGroup) objectFromJSON, "XACMLPapServlet.doDelete"); } else { - acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); + acPutTransaction.updateGroup((StdPDPGroup) objectFromJSON, "XACMLPapServlet.doACPut"); } - } catch(Exception e){ + } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " - +"group="+group.getId()); + + "group=" + group.getId()); LOGGER.error(e); throw new PAPException(e.getMessage()); } PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); - OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON; + OnapPDPGroup updatedGroup = (StdPDPGroup) objectFromJSON; if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) { LOGGER.debug("Precheck Successful."); } - try{ - papEngine.updateGroup((StdPDPGroup)objectFromJSON); - }catch(PAPException e){ + try { + papEngine.updateGroup((StdPDPGroup) objectFromJSON); + } catch (PAPException e) { LOGGER.error(e); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); @@ -2221,7 +2293,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); - return; } } catch (PAPException e) { LOGGER.debug(e); @@ -2229,8 +2300,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } @@ -2244,7 +2314,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException { + private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, + ONAPLoggingContext loggingContext) throws IOException { PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction(); try { // for all DELETE operations the group must exist before the operation can be done @@ -2255,34 +2326,34 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'"); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'"); return; } // determine the operation needed based on the parameters in the request if (request.getParameter("policy") != null) { - // group= policy= [delete=] <= delete policy file from group + // group= policy= [delete=] <= delete policy file from + // group loggingContext.setServiceName("AC:PAP.deletePolicy"); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); - return; + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); } else if (request.getParameter("pdpId") != null) { // ARGS: group= pdpId= <= delete PDP String pdpId = request.getParameter("pdpId"); OnapPDP pdp = papEngine.getPDP(pdpId); - try{ - removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete"); - } catch(Exception e){ + try { + removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(), "XACMLPapServlet.doACDelete"); + } catch (Exception e) { throw new PAPException(e); } - try{ + try { papEngine.removePDP((OnapPDP) pdp); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } // adjust the status of the group, which may have changed when we removed this PDP - ((StdPDPGroup)group).resetStatus(); + ((StdPDPGroup) group).resetStatus(); response.setStatus(HttpServletResponse.SC_NO_CONTENT); loggingContext.metricStarted(); notifyAC(); @@ -2297,23 +2368,22 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); - return; } else if (request.getParameter("pipId") != null) { // group= pipId= <= delete PIP config for given engine loggingContext.setServiceName("AC:PAP.deletePIPConfig"); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); - return; + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); } else { - // ARGS: group= movePDPsToGroupId= <= delete a group and move all its PDPs to the given group + // ARGS: group= movePDPsToGroupId= <= delete a group and + // move all its PDPs to the given group String moveToGroupId = request.getParameter("movePDPsToGroupId"); OnapPDPGroup moveToGroup = null; if (moveToGroupId != null) { - try{ + try { moveToGroup = papEngine.getGroup(moveToGroupId); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } } @@ -2321,15 +2391,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Set movedPDPs = new HashSet<>(); movedPDPs.addAll(group.getOnapPdps()); // do the move/remove - try{ - removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception"); + try { + removePdpOrGroupTransaction.deleteGroup(group, moveToGroup, "XACMLPapServlet.doACDelete"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", + " Failed to delete PDP Group. Exception"); throw new PAPException(e.getMessage()); } - try{ + try { papEngine.removeGroup(group, moveToGroup); - }catch(PAPException e){ + } catch (PAPException e) { LOGGER.error(e); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); @@ -2348,37 +2419,36 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); auditLogger.info("Success"); PolicyLogger.audit("Transaction Ended Successfully"); - return; } } catch (PAPException e) { removePdpOrGroupTransaction.rollbackTransaction(); PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } /** * Heartbeat thread - periodically check on PDPs' status - * + *

* Heartbeat with all known PDPs. - * + *

* Implementation note: - * + *

* The PDPs are contacted Sequentially, not in Parallel. - * + *

* If we did this in parallel using multiple threads we would simultaneously use - * - 1 thread and - * - 1 connection + * - 1 thread and + * - 1 connection * for EACH PDP. * This could become a resource problem since we already use multiple threads and connections for updating the PDPs * when user changes occur. * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive. - * + *

* The Sequential operation does a heartbeat request to each PDP one at a time. - * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout. + * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they + * timeout. * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds) * it could take a long time to cycle through all of the PDPs. * That means that this may not notice a PDP being down in a predictable time. @@ -2401,14 +2471,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList public Heartbeat(PAPPolicyEngine papEngine2) { papEngine = papEngine2; - this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); - this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); + this.heartbeatInterval = Integer.parseInt( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); + this.heartbeatTimeout = Integer.parseInt( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); } @Override public void run() { // Set ourselves as running - synchronized(this) { + synchronized (this) { this.isRunning = true; } HashMap idToURLMap = new HashMap<>(); @@ -2418,7 +2490,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Thread.sleep(heartbeatInterval); // get the list of PDPs (may have changed since last time) pdps.clear(); - synchronized(papEngine) { + synchronized (papEngine) { try { for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) { for (OnapPDP p : g.getOnapPdps()) { @@ -2426,7 +2498,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + "Heartbeat unable to read PDPs from PAPEngine"); } } // Check for shutdown @@ -2449,13 +2522,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String fullURLString = null; try { // Check PDP ID - if(CheckPDP.validateID(pdp.getId())){ + if (CheckPDP.validateID(pdp.getId())) { fullURLString = pdp.getId() + "?type=hb"; pdpURL = new URL(fullURLString); idToURLMap.put(pdp.getId(), pdpURL); } } catch (MalformedURLException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", + " PDP id '" + fullURLString + "' is not a valid URL"); continue; } } @@ -2464,14 +2538,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList HttpURLConnection connection = null; try { // Open up the connection - if(pdpURL != null){ - connection = (HttpURLConnection)pdpURL.openConnection(); + if (pdpURL != null) { + connection = (HttpURLConnection) pdpURL.openConnection(); // Setup our method and headers connection.setRequestMethod("GET"); connection.setConnectTimeout(heartbeatTimeout); // Authentication String encoding = CheckPDP.getEncoding(pdp.getId()); - if(encoding !=null){ + if (encoding != null) { connection.setRequestProperty("Authorization", "Basic " + encoding); } // Do the connect @@ -2484,34 +2558,42 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } else { // anything else is an unexpected result newStatus = PDPStatus.Status.UNKNOWN.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId()); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + + " Heartbeat connect response code " + connection.getResponseCode() + ": " + + pdp.getId()); } } } catch (UnknownHostException e) { newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST"); } catch (SocketTimeoutException e) { newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Heartbeat '" + pdp.getId() + "' connection timeout"); } catch (ConnectException e) { newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Heartbeat '" + pdp.getId() + "' cannot connect"); } catch (Exception e) { newStatus = PDPStatus.Status.UNKNOWN.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + "Heartbeat '" + pdp.getId() + "' connect exception"); } finally { // cleanup the connection - if(connection != null) + if (connection != null) connection.disconnect(); } - if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) { + if (!pdp.getStatus().getStatus().toString().equals(newStatus)) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'"); + LOGGER.debug("previous status='" + pdp.getStatus().getStatus() + "' new Status='" + + newStatus + "'"); } try { setPDPSummaryStatus(pdp, newStatus); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId()); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + "Unable to set state for PDP '" + pdp.getId()); } changeSeen = true; } @@ -2543,12 +2625,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException { - synchronized(papEngine) { + synchronized (papEngine) { StdPDPStatus status = new StdPDPStatus(); status.setStatus(PDPStatus.Status.valueOf(newStatus)); - ((StdPDP)pdp).setStatus(status); + ((StdPDP) pdp).setStatus(status); // now adjust the group - StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp); + StdPDPGroup group = (StdPDPGroup) papEngine.getPDPGroup((OnapPDP) pdp); // if the PDP was just deleted it may transiently exist but not be in a group if (group != null) { group.resetStatus(); @@ -2605,22 +2687,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } @Override - public void pdpChanged(OnapPDP pdp) { + public void pdpChanged(OnapPDP pdp) { // kick off a thread to do an event notification for each PDP. // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc) - // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out. + // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or + // time-out. Thread t = new Thread(new UpdatePDPThread(pdp)); - if(CheckPDP.validateID(pdp.getId())){ + if (CheckPDP.validateID(pdp.getId())) { t.start(); } } - public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) { + public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) { // kick off a thread to do an event notification for each PDP. // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc) - // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out. + // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or + // time-out. Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext)); - if(CheckPDP.validateID(pdp.getId())){ + if (CheckPDP.validateID(pdp.getId())) { t.start(); } } @@ -2636,8 +2720,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) { this.pdp = pdp; - if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) { - this.requestId = loggingContext.getRequestID(); + if ((loggingContext != null) && (loggingContext.getRequestID() != null || + Objects.equals(loggingContext.getRequestID(), ""))) { + this.requestId = loggingContext.getRequestID(); } this.loggingContext = loggingContext; } @@ -2648,40 +2733,47 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // get a new logging context for the thread try { if (this.loggingContext == null) { - loggingContext = new ONAPLoggingContext(baseLoggingContext); + loggingContext = new ONAPLoggingContext(baseLoggingContext); } } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId()); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Failed to send property file to " + pdp.getId()); // Since this is a server-side error, it probably does not reflect a problem on the client, // so do not change the PDP status. return; } try { loggingContext.setServiceName("PAP:PDP.putConfig"); - // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP - if ((requestId == null) || (requestId == "")) { + // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used + // later when calling PDP + if ((requestId == null) || (Objects.equals(requestId, ""))) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID()); + PolicyLogger + .info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated" + + " one: " + + loggingContext.getRequestID()); } else { loggingContext.setRequestID(requestId); - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID()); + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + + loggingContext.getRequestID()); } loggingContext.transactionStarted(); // the Id of the PDP is its URL if (LOGGER.isDebugEnabled()) { LOGGER.debug("creating url for id '" + pdp.getId() + "'"); } - //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other? + //TODO - currently always send both policies and pips. Do we care enough to add code to allow + // sending just one or the other? //TODO (need to change "cache=", implying getting some input saying which to change) URL url = new URL(pdp.getId() + "?cache=all"); // Open up the connection - connection = (HttpURLConnection)url.openConnection(); + connection = (HttpURLConnection) url.openConnection(); // Setup our method and headers connection.setRequestMethod("PUT"); // Authentication String encoding = CheckPDP.getEncoding(pdp.getId()); - if(encoding !=null){ + if (encoding != null) { connection.setRequestProperty("Authorization", "Basic " + encoding); } connection.setRequestProperty("Content-Type", "text/x-java-properties"); @@ -2705,13 +2797,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList group.getPolicyProperties().store(os, ""); Properties policyLocations = new Properties(); for (PDPPolicy policy : group.getPolicies()) { - policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId()); + policyLocations + .put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId()); } policyLocations.store(os, ""); group.getPipConfigProperties().store(os, ""); } } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId()); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Failed to send property file to " + pdp.getId()); // Since this is a server-side error, it probably does not reflect a problem on the client, // so do not change the PDP status. return; @@ -2734,27 +2828,34 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.audit("Transaction Success. PDP is configured correctly."); setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); } else { - LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + + connection.getResponseMessage()); loggingContext.transactionEnded(); - auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + + connection.getResponseMessage()); + PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + + connection.getResponseMessage()); setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN); } } catch (Exception e) { LOGGER.debug(e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Unable to sync config with PDP '" + pdp.getId() + "'"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e); try { setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN); } catch (PAPException e1) { LOGGER.debug(e1); - PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN"); + PolicyLogger + .audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN"); } } finally { // cleanup the connection - if(connection != null){ + if (connection != null) { connection.disconnect(); } // tell the AC to update it's status info @@ -2783,17 +2884,19 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList HttpURLConnection connection = null; try { acURL += "?PAPNotification=true"; - //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed? + //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want + // to tell it which group/pdp changed? //TODO - If so, put correct parameters into the Query string here acURL += "&objectType=all" + "&action=update"; if (LOGGER.isDebugEnabled()) { LOGGER.debug("creating url for id '" + acURL + "'"); } - //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other? + //TODO - currently always send both policies and pips. Do we care enough to add code to allow + // sending just one or the other? //TODO (need to change "cache=", implying getting some input saying which to change) - URL url = new URL(acURL ); + URL url = new URL(acURL); // Open up the connection - connection = (HttpURLConnection)url.openConnection(); + connection = (HttpURLConnection) url.openConnection(); // Setup our method and headers connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", "text/x-java-properties"); @@ -2812,15 +2915,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (connection.getResponseCode() == 204) { LOGGER.info("Success. We updated correctly."); } else { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + + " message: " + connection.getResponseMessage()); } } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Unable to sync config AC '" + acURL + "'"); disconnectedACs.add(acURL); } finally { // cleanup the connection - if(connection != null) + if (connection != null) connection.disconnect(); } } @@ -2831,7 +2936,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{ + private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException { LOGGER.info("Test request received"); try { im.evaluateSanity(); @@ -2841,8 +2946,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); response.setStatus(HttpServletResponse.SC_OK); - return; - }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){ + } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) { String submsg; if (e instanceof ForwardProgressException) { submsg = " is not making forward progress."; @@ -2858,12 +2962,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (Exception e) { + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e) { //A subsystem is not making progress, is locked, standby or is not responding String eMsg = e.getMessage(); - if(eMsg == null){ + if (eMsg == null) { eMsg = "No Exception Message"; } String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." @@ -2874,21 +2977,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.audit("Transaction Failed - See Error.log"); //Get the specific list of subsystems that failed String ssFailureList = null; - for(String failedSS : papDependencyGroupsFlatArray){ - if(eMsg.contains(failedSS)){ - if(ssFailureList == null){ + for (String failedSS : papDependencyGroupsFlatArray) { + if (eMsg.contains(failedSS)) { + if (ssFailureList == null) { ssFailureList = failedSS; - }else{ - ssFailureList = ssFailureList.concat(","+failedSS); + } else { + ssFailureList = ssFailureList.concat("," + failedSS); } } } - if(ssFailureList == null){ + if (ssFailureList == null) { ssFailureList = "UnknownSubSystem"; } response.addHeader("X-ONAP-SubsystemFailure", ssFailureList); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; } } @@ -2898,29 +3000,31 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private boolean authorizeRequest(HttpServletRequest request) { String clientCredentials = request.getHeader(ENVIRONMENT_HEADER); // Check if the Client is Authorized. - if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ + if (clientCredentials != null && clientCredentials.equalsIgnoreCase(environment)) { return true; - }else{ + } else { return false; } } - private static void loadWebapps() throws PAPException{ - if(actionHome == null || configHome == null){ + private static void loadWebapps() throws PAPException { + if (actionHome == null || configHome == null) { Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); //Sanity Check if (webappsPath == null) { PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new PAPException( + "Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); } - Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config"); - Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action"); + Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config"); + Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action"); if (Files.notExists(webappsPathConfig)) { try { Files.createDirectories(webappsPathConfig); } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: " - + webappsPathConfig.toAbsolutePath().toString()); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + "Failed to create config directory: " + + webappsPathConfig.toAbsolutePath().toString()); } } if (Files.notExists(webappsPathAction)) { @@ -2936,7 +3040,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - public static String getConfigHome(){ + public static String getConfigHome() { try { loadWebapps(); } catch (PAPException e) { @@ -2946,11 +3050,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return configHome; } - private static void setConfigHome(){ + private static void setConfigHome() { configHome = getConfigHome(); } - public static String getActionHome(){ + public static String getActionHome() { try { loadWebapps(); } catch (PAPException e) { @@ -2960,7 +3064,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return actionHome; } - private static void setActionHome(){ + private static void setActionHome() { actionHome = getActionHome(); } @@ -2972,21 +3076,22 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return ia; } - public static String getPDPFile(){ + public static String getPDPFile() { return XACMLPapServlet.pdpFile; } - public static String getPersistenceUnit(){ + public static String getPersistenceUnit() { return PERSISTENCE_UNIT; } - public static PAPPolicyEngine getPAPEngine(){ + public static PAPPolicyEngine getPAPEngine() { return papEngine; } - public static PolicyDBDaoTransaction getDbDaoTransaction(){ + public static PolicyDBDaoTransaction getDbDaoTransaction() { return policyDBDao.getNewTransaction(); } + public static String getPapDbDriver() { return papDbDriver; }