diff options
author | Krishnajinka <kris.jinka@samsung.com> | 2018-08-03 10:36:19 +0900 |
---|---|---|
committer | Krishnajinka <kris.jinka@samsung.com> | 2018-08-03 10:36:35 +0900 |
commit | 4068da123ee33b532b4b52f15545c76a978f977e (patch) | |
tree | 2f0e6393d1e204b6d0b32e58c4d9a1625c2d6ad4 /ONAP-PAP-REST/src/main | |
parent | f0fec2a861ea0a92b27b40882ea38f9422cde0c6 (diff) |
Modify ONAP PAP REST classes basic checkstyle
Modify tabs to space for checkstyle issue fix in ONAP PAP REST
module. It helps future reviews and refactoring. Remaining classes
Issue-ID: POLICY-1014
Change-Id: I677eadac9e8364b388be922024528c27fd1e2545
Signed-off-by: Krishnajinka <kris.jinka@samsung.com>
Diffstat (limited to 'ONAP-PAP-REST/src/main')
29 files changed, 7861 insertions, 7861 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java index 38e2c96f5..ce9cad408 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java @@ -27,31 +27,31 @@ package org.onap.policy.pap.xacml.rest; * */ public enum DictionaryNames { - - Attribute, - ActionPolicyDictionary, - OnapName, - MSPolicyDictionary, - OptimizationPolicyDictionary, - VNFType, - VSCLAction, - ClosedLoopService, - ClosedLoopSite, - PEPOptions, - VarbindDictionary, - BRMSParamDictionary, - BRMSControllerDictionary, - BRMSDependencyDictionary, - Settings, - PrefixList, - SecurityZone, - Zone, - ServiceList, - ServiceGroup, - AddressGroup, - ProtocolList, - ActionList, - TermList, - SearchCriteria + + Attribute, + ActionPolicyDictionary, + OnapName, + MSPolicyDictionary, + OptimizationPolicyDictionary, + VNFType, + VSCLAction, + ClosedLoopService, + ClosedLoopSite, + PEPOptions, + VarbindDictionary, + BRMSParamDictionary, + BRMSControllerDictionary, + BRMSDependencyDictionary, + Settings, + PrefixList, + SecurityZone, + Zone, + ServiceList, + ServiceGroup, + AddressGroup, + ProtocolList, + ActionList, + TermList, + SearchCriteria } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java index c1891b352..bd000381b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java @@ -64,177 +64,177 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class UpdateOthersPAPS { - - private static final Logger policyLogger = FlexLogger.getLogger(UpdateOthersPAPS.class); - - private static CommonClassDao commonClassDao; - - private static final String contentType = "application/json"; - private static String configType =".Config_"; - private static String actionType =".Action_"; - private static String error ="error"; - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - UpdateOthersPAPS.commonClassDao = commonClassDao; - } - - @Autowired - private UpdateOthersPAPS(CommonClassDao commonClassDao){ - UpdateOthersPAPS.commonClassDao = commonClassDao; - } - - public UpdateOthersPAPS() { - //Empty Constructor - } - - @RequestMapping(value="/notifyOtherPAPs", method= RequestMethod.POST) - public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response){ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - UpdateObjectData body = new UpdateObjectData(); - body.setAction(request.getParameter("action")); - body.setNewPolicyName(request.getParameter("newPolicyName")); - body.setOldPolicyName(request.getParameter("oldPolicyName")); - - String currentPap = XACMLRestProperties.getProperty("xacml.rest.pap.url"); - List<Object> getPAPUrls = commonClassDao.getData(PolicyDBDaoEntity.class); - if(getPAPUrls != null && !getPAPUrls.isEmpty()){ - for(int i = 0; i < getPAPUrls.size(); i++){ - PolicyDBDaoEntity papId = (PolicyDBDaoEntity) getPAPUrls.get(i); - String papUrl = papId.getPolicyDBDaoUrl(); - if(!papUrl.equals(currentPap)){ - String userName = papId.getUsername(); - String password = papId.getPassword(); - Base64.Encoder encoder = Base64.getEncoder(); - String txt; - try{ - txt = new String(CryptoUtils.decryptTxt(password), StandardCharsets.UTF_8); - } catch(Exception e){ - policyLogger.debug(e); - //if we can't decrypt, might as well try it anyway - txt = password; - } - String encoding = encoder.encodeToString((userName+":"+txt).getBytes(StandardCharsets.UTF_8)); - HttpHeaders headers = new HttpHeaders(); - headers.set("Authorization", "Basic " + encoding); - headers.set("Content-Type", contentType); - - RestTemplate restTemplate = new RestTemplate(); - HttpEntity<?> requestEntity = new HttpEntity<>(body, headers); - HttpClientErrorException exception = null; - - try{ - restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, String.class); - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); - exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - if("409 Conflict".equals(e.getMessage())){ - policyLogger.error(e.getMessage()); - response.addHeader(error, e.getMessage()); - } - } - if(exception != null && exception.getStatusCode()!=null){ - String message; - if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ - message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ; - policyLogger.error(message); - }else if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); - policyLogger.error(message); - }else if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ - message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; - policyLogger.error(message); - }else{ - message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); - policyLogger.error(message); - } - model.put(papUrl, message); - }else{ - model.put(papUrl, "Success"); - } - } - } - JsonMessage msg; - try { - msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - policyLogger.error("Exception Occured"+e); - } - } - } - - @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST) - @ResponseBody - public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response){ - String action = data.getAction(); - String newPolicyName = data.getNewPolicyName(); - String oldPolicyName = data.getOldPolicyName(); - try{ - if("rename".equals(action)){ - if(oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)){ - File file; - if(oldPolicyName.contains(configType)){ - file = new File(Policy.getConfigHome() + File.separator + oldPolicyName); - }else{ - file = new File(Policy.getActionHome() + File.separator + oldPolicyName); - } - if(file.exists()){ - File renamefile; - if(oldPolicyName.contains(configType)){ - renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName); - }else{ - renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName); - } - if(file.renameTo(renamefile)){ - policyLogger.info("Policy has been renamed Successfully"+newPolicyName); - response.addHeader("rename", "Success"); - }else{ - response.addHeader("rename", "Failure"); - } - } - } - }else if("delete".equals(action)){ - if(oldPolicyName.contains(configType)){ - Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName)); - }else if(oldPolicyName.contains("Action_")){ - Files.deleteIfExists(Paths.get(Policy.getActionHome() + File.separator + oldPolicyName)); - } - }else if("clonePolicy".equals(action) || "exportPolicy".equals(action)){ - if(newPolicyName.contains(configType)){ - ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName); - saveConfigurationData(configEntiy, newPolicyName); - }else if(newPolicyName.contains(actionType)){ - ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName); - saveActionBodyData(actionEntiy, newPolicyName); - } - } - } catch (IOException e) { - policyLogger.error("Exception Occured While updating Configuration"+e); - } - } - - private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName){ - try(FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)){ - BufferedWriter bw = new BufferedWriter(fw); - bw.write(configEntiy.getConfigBody()); - bw.close(); - }catch (IOException e) { - policyLogger.error("Exception Occured While closing the File input stream"+e); - } - } - - private void saveActionBodyData(ActionBodyEntity actionEntiy , String newPolicyName){ - try(FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)){ - BufferedWriter bw = new BufferedWriter(fw); - bw.write(actionEntiy.getActionBody()); - bw.close(); - }catch (IOException e) { - policyLogger.error("Exception Occured While closing the File input stream"+e); - } - } + + private static final Logger policyLogger = FlexLogger.getLogger(UpdateOthersPAPS.class); + + private static CommonClassDao commonClassDao; + + private static final String contentType = "application/json"; + private static String configType =".Config_"; + private static String actionType =".Action_"; + private static String error ="error"; + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + UpdateOthersPAPS.commonClassDao = commonClassDao; + } + + @Autowired + private UpdateOthersPAPS(CommonClassDao commonClassDao){ + UpdateOthersPAPS.commonClassDao = commonClassDao; + } + + public UpdateOthersPAPS() { + //Empty Constructor + } + + @RequestMapping(value="/notifyOtherPAPs", method= RequestMethod.POST) + public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response){ + Map<String, Object> model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + UpdateObjectData body = new UpdateObjectData(); + body.setAction(request.getParameter("action")); + body.setNewPolicyName(request.getParameter("newPolicyName")); + body.setOldPolicyName(request.getParameter("oldPolicyName")); + + String currentPap = XACMLRestProperties.getProperty("xacml.rest.pap.url"); + List<Object> getPAPUrls = commonClassDao.getData(PolicyDBDaoEntity.class); + if(getPAPUrls != null && !getPAPUrls.isEmpty()){ + for(int i = 0; i < getPAPUrls.size(); i++){ + PolicyDBDaoEntity papId = (PolicyDBDaoEntity) getPAPUrls.get(i); + String papUrl = papId.getPolicyDBDaoUrl(); + if(!papUrl.equals(currentPap)){ + String userName = papId.getUsername(); + String password = papId.getPassword(); + Base64.Encoder encoder = Base64.getEncoder(); + String txt; + try{ + txt = new String(CryptoUtils.decryptTxt(password), StandardCharsets.UTF_8); + } catch(Exception e){ + policyLogger.debug(e); + //if we can't decrypt, might as well try it anyway + txt = password; + } + String encoding = encoder.encodeToString((userName+":"+txt).getBytes(StandardCharsets.UTF_8)); + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", "Basic " + encoding); + headers.set("Content-Type", contentType); + + RestTemplate restTemplate = new RestTemplate(); + HttpEntity<?> requestEntity = new HttpEntity<>(body, headers); + HttpClientErrorException exception = null; + + try{ + restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, String.class); + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); + exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); + if("409 Conflict".equals(e.getMessage())){ + policyLogger.error(e.getMessage()); + response.addHeader(error, e.getMessage()); + } + } + if(exception != null && exception.getStatusCode()!=null){ + String message; + if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ + message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ; + policyLogger.error(message); + }else if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + policyLogger.error(message); + }else if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ + message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; + policyLogger.error(message); + }else{ + message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + policyLogger.error(message); + } + model.put(papUrl, message); + }else{ + model.put(papUrl, "Success"); + } + } + } + JsonMessage msg; + try { + msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + policyLogger.error("Exception Occured"+e); + } + } + } + + @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST) + @ResponseBody + public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response){ + String action = data.getAction(); + String newPolicyName = data.getNewPolicyName(); + String oldPolicyName = data.getOldPolicyName(); + try{ + if("rename".equals(action)){ + if(oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)){ + File file; + if(oldPolicyName.contains(configType)){ + file = new File(Policy.getConfigHome() + File.separator + oldPolicyName); + }else{ + file = new File(Policy.getActionHome() + File.separator + oldPolicyName); + } + if(file.exists()){ + File renamefile; + if(oldPolicyName.contains(configType)){ + renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName); + }else{ + renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName); + } + if(file.renameTo(renamefile)){ + policyLogger.info("Policy has been renamed Successfully"+newPolicyName); + response.addHeader("rename", "Success"); + }else{ + response.addHeader("rename", "Failure"); + } + } + } + }else if("delete".equals(action)){ + if(oldPolicyName.contains(configType)){ + Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName)); + }else if(oldPolicyName.contains("Action_")){ + Files.deleteIfExists(Paths.get(Policy.getActionHome() + File.separator + oldPolicyName)); + } + }else if("clonePolicy".equals(action) || "exportPolicy".equals(action)){ + if(newPolicyName.contains(configType)){ + ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName); + saveConfigurationData(configEntiy, newPolicyName); + }else if(newPolicyName.contains(actionType)){ + ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName); + saveActionBodyData(actionEntiy, newPolicyName); + } + } + } catch (IOException e) { + policyLogger.error("Exception Occured While updating Configuration"+e); + } + } + + private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName){ + try(FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)){ + BufferedWriter bw = new BufferedWriter(fw); + bw.write(configEntiy.getConfigBody()); + bw.close(); + }catch (IOException e) { + policyLogger.error("Exception Occured While closing the File input stream"+e); + } + } + + private void saveActionBodyData(ActionBodyEntity actionEntiy , String newPolicyName){ + try(FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)){ + BufferedWriter bw = new BufferedWriter(fw); + bw.write(actionEntiy.getActionBody()); + bw.close(); + }catch (IOException e) { + policyLogger.error("Exception Occured While closing the File input stream"+e); + } + } }
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java index 89ab8bc8a..88ad91b5f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java @@ -28,16 +28,16 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.servlet.DispatcherServlet; public class WebConfig implements WebApplicationInitializer { - - @Override - public void onStartup(ServletContext container) { - AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - ctx.register(PAPRestConfig.class); - ctx.setServletContext(container); - ctx.refresh(); - ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(ctx)); - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/onap/*"); - } + + @Override + public void onStartup(ServletContext container) { + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(PAPRestConfig.class); + ctx.setServletContext(container); + ctx.refresh(); + ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(ctx)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/onap/*"); + } } 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 1acec1bd9..4406ad3da 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 @@ -107,191 +107,191 @@ import com.google.common.base.Splitter; * Servlet implementation class XacmlPapServlet */ @WebServlet( - description = "Implements the XACML PAP RESTful API.", - urlPatterns = { "/" }, - loadOnStartup=1, - initParams = { - @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.") - }) + description = "Implements the XACML PAP RESTful API.", + urlPatterns = { "/" }, + loadOnStartup=1, + initParams = { + @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); - // audit (transaction) LOGGER - private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); - //Persistence Unit for JPA - private static final String PERSISTENCE_UNIT = "XACML-PAP-REST"; - private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU"; - // Client Headers. - private static final String ENVIRONMENT_HEADER = "Environment"; - private static final String ADD_GROUP_ERROR = "addGroupError"; - private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password"; - - private static final String REGEX = "[0-9a-zA-Z._ ]*"; - - /* - * List of Admin Console URLs. - * Used to send notifications when configuration changes. - * - * The CopyOnWriteArrayList *should* protect from concurrency errors. - * This list is seldom changed but often read, so the costs of this approach make sense. - */ - private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>(); - - private static String configHome; - private static String actionHome; - /* - * This PAP instance's own URL. - * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. - */ - private static String papURL = null; - // The heartbeat thread. - private static Heartbeat heartbeat = null; - private static Thread heartbeatThread = null; - //The entity manager factory for JPA access - private static EntityManagerFactory emf; - private static PolicyDBDao policyDBDao; - /* - * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes. - */ - private static PAPPolicyEngine papEngine = null; - /* - * These are the parameters needed for DB access from the PAP - */ - private static int papIntegrityAuditPeriodSeconds = -1; - private static String papDbDriver = null; - private static String papDbUrl = null; - private static String papDbUser = null; - private static String papDbPassword = null; - private static String papResourceName = null; - private static String[] papDependencyGroupsFlatArray = null; - private static String environment = null; - private static String pdpFile = null; - - private transient IntegrityMonitor im; - private transient IntegrityAudit ia; - - //MicroService Model Properties - private static String msOnapName; - private static String msPolicyName; - /* - * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when - * this servlet starts. Its configurable by the admin. - */ - private static transient Thread initiateThread = null; - private transient ONAPLoggingContext baseLoggingContext = null; - - /** - * @see HttpServlet#HttpServlet() - */ - public XACMLPapServlet() { - super(); - } - - /** - * @see Servlet#init(ServletConfig) - */ - public void init(ServletConfig config) throws ServletException { - try { - // Logging - baseLoggingContext = new ONAPLoggingContext(); - // fixed data that will be the same in all logging output goes here - try { - String hostname = InetAddress.getLocalHost().getCanonicalHostName(); - baseLoggingContext.setServer(hostname); - } catch (UnknownHostException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e); - } - // Initialize - XACMLRest.xacmlInit(config); - // Load the properties - XACMLRest.loadXacmlProperties(null, null); - /* - * Retrieve the property values - */ - setCommonProperties(); - String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); - 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"); - 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)); - //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)); - String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); - 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)); - LOGGER.debug("\n\n\n**************************************" - + "\n*************************************" - + "\n" - + "\n papDbDriver = " + papDbDriver - + "\n papDbUrl = " + papDbUrl - + "\n papDbUser = " + papDbUser - + "\n papTransWait = " + papTransWait - + "\n papTransTimeout = " + papTransTimeout - + "\n papAuditTimeout = " + papAuditTimeout - + "\n papAuditFlag = " + papAuditFlag - + "\n papFileSystemAudit = " + papFileSystemAudit - + "\n papResourceName = " + papResourceName - + "\n fpMonitorInterval = " + fpMonitorInterval - + "\n failedCounterThreshold = " + failedCounterThreshold - + "\n testTransInterval = " + testTransInterval - + "\n writeFpcInterval = " + writeFpcInterval - + "\n papSiteName = " + papSiteName - + "\n papNodeType = " + papNodeType - + "\n papDependencyGroupsList = " + papDependencyGroups - + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds - + "\n\n*************************************" - + "\n**************************************"); - // Pull custom persistence settings - Properties properties; - try { - properties = XACMLProperties.getProperties(); - LOGGER.debug("\n\n\n**************************************" - + "\n**************************************" - + "\n\n" - + "properties = " + properties - + "\n\n**************************************"); - } catch (IOException e) { - 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, ""))); - } - im = IntegrityMonitor.getInstance(papResourceName,properties); - // Create an IntegrityAudit - ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties); - ia.startAuditThread(); - // Create the entity manager factory - setEMF(properties); - // we are about to call the PDPs and give them their configuration. - // To do that we need to have the URL of this PAP so we can construct the Policy file URLs - setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); - //Create the policyDBDao - setPolicyDBDao(); - // Load our PAP engine, first create a factory - 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; + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class); + // audit (transaction) LOGGER + private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); + //Persistence Unit for JPA + private static final String PERSISTENCE_UNIT = "XACML-PAP-REST"; + private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU"; + // Client Headers. + private static final String ENVIRONMENT_HEADER = "Environment"; + private static final String ADD_GROUP_ERROR = "addGroupError"; + private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password"; + + private static final String REGEX = "[0-9a-zA-Z._ ]*"; + + /* + * List of Admin Console URLs. + * Used to send notifications when configuration changes. + * + * The CopyOnWriteArrayList *should* protect from concurrency errors. + * This list is seldom changed but often read, so the costs of this approach make sense. + */ + private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>(); + + private static String configHome; + private static String actionHome; + /* + * This PAP instance's own URL. + * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. + */ + private static String papURL = null; + // The heartbeat thread. + private static Heartbeat heartbeat = null; + private static Thread heartbeatThread = null; + //The entity manager factory for JPA access + private static EntityManagerFactory emf; + private static PolicyDBDao policyDBDao; + /* + * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes. + */ + private static PAPPolicyEngine papEngine = null; + /* + * These are the parameters needed for DB access from the PAP + */ + private static int papIntegrityAuditPeriodSeconds = -1; + private static String papDbDriver = null; + private static String papDbUrl = null; + private static String papDbUser = null; + private static String papDbPassword = null; + private static String papResourceName = null; + private static String[] papDependencyGroupsFlatArray = null; + private static String environment = null; + private static String pdpFile = null; + + private transient IntegrityMonitor im; + private transient IntegrityAudit ia; + + //MicroService Model Properties + private static String msOnapName; + private static String msPolicyName; + /* + * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when + * this servlet starts. Its configurable by the admin. + */ + private static transient Thread initiateThread = null; + private transient ONAPLoggingContext baseLoggingContext = null; + + /** + * @see HttpServlet#HttpServlet() + */ + public XACMLPapServlet() { + super(); + } + + /** + * @see Servlet#init(ServletConfig) + */ + public void init(ServletConfig config) throws ServletException { + try { + // Logging + baseLoggingContext = new ONAPLoggingContext(); + // fixed data that will be the same in all logging output goes here + try { + String hostname = InetAddress.getLocalHost().getCanonicalHostName(); + baseLoggingContext.setServer(hostname); + } catch (UnknownHostException e) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e); + } + // Initialize + XACMLRest.xacmlInit(config); + // Load the properties + XACMLRest.loadXacmlProperties(null, null); + /* + * Retrieve the property values + */ + setCommonProperties(); + String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); + 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"); + 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)); + //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)); + String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); + 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)); + LOGGER.debug("\n\n\n**************************************" + + "\n*************************************" + + "\n" + + "\n papDbDriver = " + papDbDriver + + "\n papDbUrl = " + papDbUrl + + "\n papDbUser = " + papDbUser + + "\n papTransWait = " + papTransWait + + "\n papTransTimeout = " + papTransTimeout + + "\n papAuditTimeout = " + papAuditTimeout + + "\n papAuditFlag = " + papAuditFlag + + "\n papFileSystemAudit = " + papFileSystemAudit + + "\n papResourceName = " + papResourceName + + "\n fpMonitorInterval = " + fpMonitorInterval + + "\n failedCounterThreshold = " + failedCounterThreshold + + "\n testTransInterval = " + testTransInterval + + "\n writeFpcInterval = " + writeFpcInterval + + "\n papSiteName = " + papSiteName + + "\n papNodeType = " + papNodeType + + "\n papDependencyGroupsList = " + papDependencyGroups + + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds + + "\n\n*************************************" + + "\n**************************************"); + // Pull custom persistence settings + Properties properties; + try { + properties = XACMLProperties.getProperties(); + LOGGER.debug("\n\n\n**************************************" + + "\n**************************************" + + "\n\n" + + "properties = " + properties + + "\n\n**************************************"); + } catch (IOException e) { + 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, ""))); + } + im = IntegrityMonitor.getInstance(papResourceName,properties); + // Create an IntegrityAudit + ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties); + ia.startAuditThread(); + // Create the entity manager factory + setEMF(properties); + // we are about to call the PDPs and give them their configuration. + // To do that we need to have the URL of this PAP so we can construct the Policy file URLs + setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); + //Create the policyDBDao + setPolicyDBDao(); + // Load our PAP engine, first create a factory + 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; if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) { try { addNewGroup = policyDBDao.getNewTransaction(); @@ -310,52 +310,52 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } } - policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine); - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){ - /* - * Auditing the local File System groups to be in sync with the Database - */ - - //get an AuditTransaction to lock out all other transactions - PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction(); - - LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit"); + policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine); + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){ + /* + * Auditing the local File System groups to be in sync with the Database + */ + + //get an AuditTransaction to lock out all other transactions + PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction(); + + LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit"); LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString()); - //get the current filesystem group and update from the database if needed + //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) { - papEngine.updateGroup(updatedGroup); + 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); - } - // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration - // to all its known PDP nodes. - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { - startInitiateThreadService(new Thread(this)); - } - // After startup, the PAP does Heartbeat's to each of the PDPs periodically - startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine)); - - } 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); - } 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); - } - } - - private static void startInitiateThreadService(Thread thread) { - initiateThread = thread; + //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); + } + // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration + // to all its known PDP nodes. + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { + startInitiateThreadService(new Thread(this)); + } + // After startup, the PAP does Heartbeat's to each of the PDPs periodically + startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine)); + + } 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); + } 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); + } + } + + private static void startInitiateThreadService(Thread thread) { + initiateThread = thread; initiateThread.start(); } @@ -368,13 +368,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private static void startHeartBeatService(Heartbeat heartbeat) { - XACMLPapServlet.heartbeat = heartbeat; + XACMLPapServlet.heartbeat = heartbeat; XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat); XACMLPapServlet.heartbeatThread.start(); } private static void setPolicyDBDao() throws ServletException { - try { + try { policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf()); } catch (Exception e) { throw new ServletException("Unable to Create Policy DBDao Instance",e); @@ -382,7 +382,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private static void setEMF(Properties properties) throws ServletException { - emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); + emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); if (emf == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: " + PERSISTENCE_UNIT); @@ -391,15 +391,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private static void setPAPURL(String papURL) { - XACMLPapServlet.papURL = papURL; + XACMLPapServlet.papURL = papURL; } private static void setPAPEngine(PAPPolicyEngine newEngine) { - XACMLPapServlet.papEngine = newEngine; + XACMLPapServlet.papEngine = newEngine; } 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 @@ -423,7 +423,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private static void setCommonProperties() throws PAPException { - setConfigHome(); + setConfigHome(); setActionHome(); papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); if(papDbDriver == null){ @@ -470,1686 +470,1686 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } /** - * Thread used only during PAP startup to initiate change messages to all known PDPs. - * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced. - */ - @Override - public void run() { - // send the current configuration to all the PDPs that we know about - changed(); - } - - /** - * @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. - */ - @Override - public void destroy() { - // Make sure our threads are destroyed - if (XACMLPapServlet.heartbeatThread != null) { - // stop the heartbeat - try { - if (XACMLPapServlet.heartbeat != null) { - XACMLPapServlet.heartbeat.terminate(); - } - XACMLPapServlet.heartbeatThread.interrupt(); - XACMLPapServlet.heartbeatThread.join(); - } catch (InterruptedException e) { - XACMLPapServlet.heartbeatThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); - } - } - if (initiateThread != null) { - try { - initiateThread.interrupt(); - initiateThread.join(); - } catch (InterruptedException e) { - initiateThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); - } - } - } - - /** - * Called by: - * - 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 { - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - loggingContext.setServiceName("PAP.post"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)"); - } - PolicyDBDaoTransaction pdpTransaction = null; - loggingContext.metricStarted(); - try { - im.startTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); - } 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; - 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); - return; - }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(); - LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se); - 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); - return; - } catch (IntegrityMonitorException e) { - String message = "POST interface called for PAP " + papResourceName + " but an exception occurred" - + "\n Exception Message: " + e.getMessage(); - LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e); - 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); - return; - } - try { - loggingContext.metricStarted(); - XACMLRest.dumpRequest(request); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest"); - // since getParameter reads the content string, explicitly get the content before doing that. - // Simply getting the inputStream seems to protect it against being consumed by getParameter. - request.getInputStream(); - String groupId = request.getParameter("groupId"); - String apiflag = request.getParameter("apiflag"); - if(groupId != null) { - // Is this from the Admin Console or 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)){ - 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); - im.endTransaction(); - return; - } - } - loggingContext.metricStarted(); - doACPost(request, response, groupId, loggingContext); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPost doACPost"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - // Request is from a PDP asking for its config. - loggingContext.setServiceName("PDP:PAP.register"); - // Get the PDP's ID - String id = this.getPDPID(request); - String jmxport = this.getPDPJMX(request); - LOGGER.info("Request(doPost) from PDP coming up: " + id); - // Get the PDP Object - OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id); - // Is it known? - if (pdp == null) { - LOGGER.info("Unknown PDP: " + id); - // Check PDP 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)); - } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) { - pdpTransaction.rollbackTransaction(); - String message = "Failed to create new PDP for id: " + id; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - im.endTransaction(); - return; - } - // get the PDP we just created - try{ - pdp = XACMLPapServlet.papEngine.getPDP(id); - }catch(PAPException e){ - LOGGER.error(e); - } - if (pdp == null) { - if(pdpTransaction != null){ - pdpTransaction.rollbackTransaction(); - } - String message = "Failed to create new PDP for id: " + id; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - im.endTransaction(); - return; - } - } else { - 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."); - PolicyLogger.audit("Transaction Failed - See Error.log"); - im.endTransaction(); - return; - } - 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"); - } - } - if (jmxport != null && jmxport != ""){ - try{ - ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport)); - }catch(NumberFormatException e){ - LOGGER.error(e); - } - } - // Get the PDP's Group - 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"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default"); - im.endTransaction(); - return; - } - // Determine what group the PDP node is in and get - // its policy/pip properties. - Properties policies = group.getPolicyProperties(); - Properties pipconfig = group.getPipConfigProperties(); - // Get the current policy/pip configuration that the PDP has - Properties pdpProperties = new Properties(); - try{ - pdpProperties.load(request.getInputStream()); - }catch(IOException e){ - LOGGER.error(e); - } - LOGGER.info("PDP Current Properties: " + pdpProperties.toString()); - LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null")); - LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null")); - // Validate the node's properties - boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties); - // Send back current configuration - if (isCurrent == false) { - // Tell the PDP we are sending back the current policies/pip config - LOGGER.info("PDP configuration NOT current."); - if (policies != null) { - // Put URL's into the properties in case the PDP needs to - // retrieve them. - this.populatePolicyURL(request.getRequestURL(), policies); - // Copy the properties to the output stream - try{ - policies.store(response.getOutputStream(), ""); - }catch(IOException e){ - LOGGER.error(e); - } - } - if (pipconfig != null) { - // Copy the properties to the output stream - try{ - pipconfig.store(response.getOutputStream(), ""); - }catch(IOException e){ - LOGGER.error(e); - } - } - // We are good - and we are sending them information - response.setStatus(HttpServletResponse.SC_OK); - try{ - setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); - }catch(PAPException e){ - LOGGER.error(e); - } - } else { - // Tell them they are good - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - try{ - setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); - }catch(PAPException e){ - LOGGER.error(e); - } - } - // tell the AC that something changed - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPost notifyAC"); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - } catch (PAPException | IOException | NumberFormatException e) { - if(pdpTransaction != null){ - pdpTransaction.rollbackTransaction(); - } - LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - im.endTransaction(); - return; - } - //Catch anything that fell through - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended"); - im.endTransaction(); - } - - private void setResponseError(HttpServletResponse response,int responseCode, String message) { - try { - if(message != null && !message.isEmpty()){ - response.sendError(responseCode, message); - } + * Thread used only during PAP startup to initiate change messages to all known PDPs. + * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced. + */ + @Override + public void run() { + // send the current configuration to all the PDPs that we know about + changed(); + } + + /** + * @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. + */ + @Override + public void destroy() { + // Make sure our threads are destroyed + if (XACMLPapServlet.heartbeatThread != null) { + // stop the heartbeat + try { + if (XACMLPapServlet.heartbeat != null) { + XACMLPapServlet.heartbeat.terminate(); + } + XACMLPapServlet.heartbeatThread.interrupt(); + XACMLPapServlet.heartbeatThread.join(); + } catch (InterruptedException e) { + XACMLPapServlet.heartbeatThread.interrupt(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); + } + } + if (initiateThread != null) { + try { + initiateThread.interrupt(); + initiateThread.join(); + } catch (InterruptedException e) { + initiateThread.interrupt(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); + } + } + } + + /** + * Called by: + * - 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 { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + loggingContext.setServiceName("PAP.post"); + if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)"); + } + PolicyDBDaoTransaction pdpTransaction = null; + loggingContext.metricStarted(); + try { + im.startTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); + } 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; + 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); + return; + }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(); + LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se); + 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); + return; + } catch (IntegrityMonitorException e) { + String message = "POST interface called for PAP " + papResourceName + " but an exception occurred" + + "\n Exception Message: " + e.getMessage(); + LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e); + 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); + return; + } + try { + loggingContext.metricStarted(); + XACMLRest.dumpRequest(request); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest"); + // since getParameter reads the content string, explicitly get the content before doing that. + // Simply getting the inputStream seems to protect it against being consumed by getParameter. + request.getInputStream(); + String groupId = request.getParameter("groupId"); + String apiflag = request.getParameter("apiflag"); + if(groupId != null) { + // Is this from the Admin Console or 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)){ + 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); + im.endTransaction(); + return; + } + } + loggingContext.metricStarted(); + doACPost(request, response, groupId, loggingContext); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPost doACPost"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + // Request is from a PDP asking for its config. + loggingContext.setServiceName("PDP:PAP.register"); + // Get the PDP's ID + String id = this.getPDPID(request); + String jmxport = this.getPDPJMX(request); + LOGGER.info("Request(doPost) from PDP coming up: " + id); + // Get the PDP Object + OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id); + // Is it known? + if (pdp == null) { + LOGGER.info("Unknown PDP: " + id); + // Check PDP 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)); + } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) { + pdpTransaction.rollbackTransaction(); + String message = "Failed to create new PDP for id: " + id; + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + im.endTransaction(); + return; + } + // get the PDP we just created + try{ + pdp = XACMLPapServlet.papEngine.getPDP(id); + }catch(PAPException e){ + LOGGER.error(e); + } + if (pdp == null) { + if(pdpTransaction != null){ + pdpTransaction.rollbackTransaction(); + } + String message = "Failed to create new PDP for id: " + id; + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + im.endTransaction(); + return; + } + } else { + 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."); + PolicyLogger.audit("Transaction Failed - See Error.log"); + im.endTransaction(); + return; + } + 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"); + } + } + if (jmxport != null && jmxport != ""){ + try{ + ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport)); + }catch(NumberFormatException e){ + LOGGER.error(e); + } + } + // Get the PDP's Group + 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"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default"); + im.endTransaction(); + return; + } + // Determine what group the PDP node is in and get + // its policy/pip properties. + Properties policies = group.getPolicyProperties(); + Properties pipconfig = group.getPipConfigProperties(); + // Get the current policy/pip configuration that the PDP has + Properties pdpProperties = new Properties(); + try{ + pdpProperties.load(request.getInputStream()); + }catch(IOException e){ + LOGGER.error(e); + } + LOGGER.info("PDP Current Properties: " + pdpProperties.toString()); + LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null")); + LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null")); + // Validate the node's properties + boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties); + // Send back current configuration + if (isCurrent == false) { + // Tell the PDP we are sending back the current policies/pip config + LOGGER.info("PDP configuration NOT current."); + if (policies != null) { + // Put URL's into the properties in case the PDP needs to + // retrieve them. + this.populatePolicyURL(request.getRequestURL(), policies); + // Copy the properties to the output stream + try{ + policies.store(response.getOutputStream(), ""); + }catch(IOException e){ + LOGGER.error(e); + } + } + if (pipconfig != null) { + // Copy the properties to the output stream + try{ + pipconfig.store(response.getOutputStream(), ""); + }catch(IOException e){ + LOGGER.error(e); + } + } + // We are good - and we are sending them information + response.setStatus(HttpServletResponse.SC_OK); + try{ + setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); + }catch(PAPException e){ + LOGGER.error(e); + } + } else { + // Tell them they are good + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + try{ + setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); + }catch(PAPException e){ + LOGGER.error(e); + } + } + // tell the AC that something changed + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPost notifyAC"); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + } catch (PAPException | IOException | NumberFormatException e) { + if(pdpTransaction != null){ + pdpTransaction.rollbackTransaction(); + } + LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + im.endTransaction(); + return; + } + //Catch anything that fell through + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended"); + im.endTransaction(); + } + + private void setResponseError(HttpServletResponse response,int responseCode, String message) { + try { + if(message != null && !message.isEmpty()){ + response.sendError(responseCode, message); + } } catch (IOException e) { LOGGER.error("Error setting Error response Header ", e); } - return; + return; } /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) - */ - 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() == "")){ - 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; - } - } - //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{ - loggingContext.metricStarted(); - doACGet(request, response, groupId, loggingContext); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doGet doACGet"); - } catch(IOException e){ + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + */ + 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() == "")){ + 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; + } + } + //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{ + loggingContext.metricStarted(); + doACGet(request, response, groupId, loggingContext); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doGet doACGet"); + } 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<OnapPDPGroup> 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(); - 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(); - } - - /** - * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) - */ - 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() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)"); - } - try { - loggingContext.metricStarted(); - im.startTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction"); - } catch (IntegrityMonitorException e) { - String message = "PUT interface called for PAP " + papResourceName; - if (e instanceof AdministrativeStateException) { - message += " but it has an Administrative state of " - + im.getStateManager().getAdminState(); - } else if (e instanceof StandbyStatusException) { - message += " but it has a Standby Status of " - + im.getStateManager().getStandbyStatus(); - } else { - message += " but an exception occurred"; - - } - message += "\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; - } - - loggingContext.metricStarted(); - XACMLRest.dumpRequest(request); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest"); - //need to check if request is from the API or Admin console - 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." ); - 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"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - loggingContext.metricStarted(); - LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification"); - policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification"); - response.setStatus(200); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - /* - * Request for ImportService - */ - String importService = request.getParameter("importService"); - if (importService != null) { - if(authorizeRequest(request)){ - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - try{ - loggingContext.metricStarted(); - apiRequestHandler.doPut(request, response, importService); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut"); - }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 ); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); - return; - } - } - // - // See if this is Admin Console registering itself with us - // - String acURLString = request.getParameter("adminConsoleURL"); - if (acURLString != null) { - loggingContext.setServiceName("AC:PAP.register"); - // remember this Admin Console for future updates - if ( ! adminConsoleURLStringList.contains(acURLString)) { - adminConsoleURLStringList.add(acURLString); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Admin Console registering with URL: " + acURLString); - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - /* - * This is to update the PDP Group with the policy/policies being pushed - * Part of a 2 step process to push policies to the PDP that can now be done - * From both the Admin Console and the PolicyEngine API - */ - 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. "; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); - return; - } - if(apiflag.equalsIgnoreCase("addPolicyToGroup")){ - try{ - updateGroupsFromAPI(request, response, groupId, loggingContext); - }catch(IOException e){ - LOGGER.error(e); - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - } - // this is from the Admin Console, so handle separately - try { - loggingContext.metricEnded(); - doACPut(request, response, groupId, loggingContext); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet goPut doACPut"); - } catch (IOException 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); } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - // - // Request is for policy validation and creation - // - if (apiflag != null && apiflag.equalsIgnoreCase("admin")){ - // this request is from the Admin Console - SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance(); - try{ - loggingContext.metricStarted(); - savePolicyHandler.doPolicyAPIPut(request, response); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler"); - } catch (IOException 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<OnapPDPGroup> 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(); + 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); } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) { - // this request is from the Policy Creation API - if(authorizeRequest(request)){ - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - try{ - loggingContext.metricStarted(); - apiRequestHandler.doPut(request, response, request.getHeader("ClientScope")); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut"); - } 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!!"; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); - im.endTransaction(); - return; - } - } - // We do not expect anything from anywhere else. - // This method is here in case we ever need to support other operations. - 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"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See error.log"); - im.endTransaction(); - } - - /** - * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response) - */ - 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() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)"); - } - try { - loggingContext.metricStarted(); - im.startTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction"); - } 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(); - 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 = "PUT 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 = "PUT 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; - } - loggingContext.metricStarted(); - XACMLRest.dumpRequest(request); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest"); - String groupId = request.getParameter("groupId"); - 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. "; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); - return; - } - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - try { - loggingContext.metricStarted(); - apiRequestHandler.doDelete(request, response, loggingContext, apiflag); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete"); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - if(apiRequestHandler.getNewGroup()!=null){ - groupChanged(apiRequestHandler.getNewGroup(), loggingContext); - } - return; - } - // this is from the Admin Console, so handle separately - try{ - loggingContext.metricStarted(); - doACDelete(request, response, groupId, loggingContext); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete"); - } catch (IOException 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); } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - //Catch anything that fell through - 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"); - im.endTransaction(); - } - - private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) { - 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); - return false; - } - // Compare the policies and pipconfig properties to the pdpProperties - try { - // the policy properties includes only xacml.rootPolicies and - // xacml.referencedPolicies without any .url entries - Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false); - Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties); - if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) && - localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) && - pdpPipConfig.equals(pipconfig)) { - // The PDP is current - return true; - } - } catch (Exception e) { - // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines, - // or if there are policies that do not have a corresponding ".url" property. - // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false. - PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error"); - } - return false; - } - - private void populatePolicyURL(StringBuffer urlPath, Properties policies) { - String lists[] = new String[2]; - lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - for (String list : lists) { - if (list != null && list.isEmpty() == false) { - for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) { - String url = urlPath + "?id=" + id; - LOGGER.info("Policy URL for " + id + ": " + url); - policies.setProperty(id + ".url", url); - } - } - } - } - - protected String getPDPID(HttpServletRequest request) { - String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID); - if (pdpURL == null || pdpURL.isEmpty()) { - // Should send back its port for identification - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header"); - pdpURL = ""; - } - return pdpURL; - } - - protected String getPDPJMX(HttpServletRequest request) { - 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"); - return null; - } - return pdpJMMX; - } - - /** - * Requests from the PolicyEngine API to update the PDP Group with pushed policy - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @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 { - // for PUT operations the group may or may not need to exist before the operation can be done - StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId); - - // get the request input stream content into a String - String json = null; - java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - - PolicyLogger.info("pushPolicy request from API: " + json); - - // convert Object sent as JSON into local object - StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class); - - //Get the current policies from the Group and Add the new one - Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>(); - 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())){ - group.removePolicy(existingPolicy); - LOGGER.info("Removing policy: " + existingPolicy); - break; - } - } - - // Assume that this is an update of an existing PDP Group - loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); - 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()); - throw new PAPException(e.getMessage()); - } - - LOGGER.info("Calling updatGroup() with new group"); - papEngine.updateGroup(group); - String policyId = "empty"; - if(policy !=null && policy.getId() != null){ - policyId = policy.getId(); - } - if(!policyId.matches(REGEX) ){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); - response.addHeader("message", "Policy Id is not valid"); - return; - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - response.addHeader("operation", "push"); - response.addHeader("policyId", policyId); - response.addHeader("groupId", groupId); - - LOGGER.info("Group '" + group.getId() + "' updated"); - - loggingContext.metricStarted(); - acPutTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction"); - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC"); - - // Group changed, which might include changing the policies - groupChanged(group, loggingContext); - loggingContext.transactionEnded(); - LOGGER.info("Success"); - - 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."); - } - } - - 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."; - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error",ADD_GROUP_ERROR); - response.addHeader("message", message); - return; - } - } - - /** - * Requests from the Admin Console for operations not on single specific objects - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @throws 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=<groupId> groupName=<name> groupDescription=<description> <= create a new group - loggingContext.setServiceName("AC:PAP.createGroup"); - String unescapedName = null; - String unescapedDescription = null; - try{ - unescapedName = URLDecoder.decode(groupName, "UTF-8"); - unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8"); - } catch (UnsupportedEncodingException e) { - LOGGER.error(e); - } - PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction(); - try { - newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost"); - papEngine.newGroup(unescapedName, unescapedDescription); - loggingContext.metricStarted(); - newGroupTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); - } catch (Exception e) { - newGroupTransaction.rollbackTransaction(); - 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 + "'"); - return; - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("New Group '" + groupId + "' created"); - } - // tell the Admin Consoles there is a change - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC"); - // new group by definition has no PDPs, so no need to notify them of changes - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - // for all remaining POST operations the group must exist before the operation can be done - OnapPDPGroup group = null; - try{ - group = papEngine.getGroup(groupId); - } 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)){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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){ - 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); - } - return; - } - - // If the request contains a policyId then we know we are pushing the policy to PDP - if (request.getParameter("policyId") != null) { - - if(apiflag!=null){ - loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy"); - LOGGER.info("PushPolicy Request From The API"); - } else { - loggingContext.setServiceName("AC:PAP.postPolicy"); - LOGGER.info("PushPolicy Request From The AC"); - } - - String policyId = request.getParameter("policyId"); - PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction(); - StdPDPGroup updatedGroup = null; - 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"); - loggingContext.metricStarted(); - addPolicyToGroupTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); - LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed"); - - } catch (Exception e) { - addPolicyToGroupTransaction.rollbackTransaction(); - String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e; - //for fixing Header Manipulation of Fortify issue - if(!message.matches(REGEX)){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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){ - response.addHeader("error", "policyCopyError"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } else { - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - } - return; - } - - if(apiflag != null){ - /* - * 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. - */ - - // Get new transaction to perform updateGroup() - PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); - try { - // 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() : ""; - scanner.close(); - - // convert Object sent as JSON into local object - ObjectMapper mapper = new ObjectMapper(); - Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class); - StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON; - - LOGGER.info("Request JSON Payload: " + json); - - // Assume that this is an update of an existing PDP Group - loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); - 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); - throw new PAPException(e.getMessage()); - } - - LOGGER.info("Calling updatGroup() with new group"); - papEngine.updateGroup(updatedGroup); - - LOGGER.info("Group '" + updatedGroup.getId() + "' updated"); - - // Commit transaction to send notification to other PAPs - loggingContext.metricStarted(); - acPutTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction"); - loggingContext.metricStarted(); - - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC"); - - // Group changed to send notification to PDPs, which might include changing the policies - groupChanged(updatedGroup,loggingContext); - loggingContext.transactionEnded(); - LOGGER.info("Success"); - - 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."); - } - } - - //delete temporary policy file from the bin directory - Files.deleteIfExists(Paths.get(policy.getId())); - - } catch (Exception 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 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("message", message); - return; - } - } - - // policy file copied ok and the Group was updated on the PDP - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - response.addHeader("operation", "push"); - response.addHeader("policyId", policyId); - response.addHeader("groupId", groupId); - - LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'"); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - LOGGER.info("Transaction Ended Successfully"); - - return; - } else if (request.getParameter("default") != null) { - // Args: group=<groupId> 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. - PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction(); - try { - setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost"); - papEngine.setDefaultGroup(group); - loggingContext.metricStarted(); - setDefaultGroupTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); - } catch (Exception e) { - setDefaultGroupTransaction.rollbackTransaction(); - 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"); - return; - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - 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 - loggingContext.metricStarted(); - notifyAC(); - // This does not affect any PDPs in the existing groups, so no need to notify them of this change - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC"); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - LOGGER.info("Transaction Ended Successfully"); - return; - } else if (request.getParameter("pdpId") != null) { - doACPostTransaction = policyDBDao.getNewTransaction(); - // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group - loggingContext.setServiceName("AC:PAP.movePDP"); - String pdpId = request.getParameter("pdpId"); - OnapPDP pdp = papEngine.getPDP(pdpId); - OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp); - try{ - doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost"); - }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()); - 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"); - } - // update the status of both the original group and the new one - ((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 - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC"); - // Need to notify the PDP that it's config may have changed - pdpChanged(pdp, loggingContext); - loggingContext.metricStarted(); - doACPostTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); - 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; - } - } - - /** - * Requests from the Admin Console to GET info about the Groups and PDPs - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @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"); - String pdpGroup = request.getParameter("getPDPGroup"); - if ("".equals(groupId)) { - // request IS from AC but does not identify a group by name - if (parameterDefault != null) { - // Request is for the Default group (whatever its id) - loggingContext.setServiceName("AC:PAP.getDefaultGroup"); - OnapPDPGroup group = papEngine.getDefaultGroup(); - // convert response object to JSON and include in the response - 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 (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(); + } + + /** + * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) + */ + 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() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)"); + } + try { + loggingContext.metricStarted(); + im.startTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction"); + } catch (IntegrityMonitorException e) { + String message = "PUT interface called for PAP " + papResourceName; + if (e instanceof AdministrativeStateException) { + message += " but it has an Administrative state of " + + im.getStateManager().getAdminState(); + } else if (e instanceof StandbyStatusException) { + message += " but it has a Standby Status of " + + im.getStateManager().getStandbyStatus(); + } else { + message += " but an exception occurred"; + + } + message += "\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; + } + + loggingContext.metricStarted(); + XACMLRest.dumpRequest(request); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest"); + //need to check if request is from the API or Admin console + 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." ); + 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"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + loggingContext.metricStarted(); + LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification"); + policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification"); + response.setStatus(200); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + /* + * Request for ImportService + */ + String importService = request.getParameter("importService"); + if (importService != null) { + if(authorizeRequest(request)){ + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + try{ + loggingContext.metricStarted(); + apiRequestHandler.doPut(request, response, importService); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut"); + }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 ); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + return; + } + } + // + // See if this is Admin Console registering itself with us + // + String acURLString = request.getParameter("adminConsoleURL"); + if (acURLString != null) { + loggingContext.setServiceName("AC:PAP.register"); + // remember this Admin Console for future updates + if ( ! adminConsoleURLStringList.contains(acURLString)) { + adminConsoleURLStringList.add(acURLString); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Admin Console registering with URL: " + acURLString); + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + /* + * This is to update the PDP Group with the policy/policies being pushed + * Part of a 2 step process to push policies to the PDP that can now be done + * From both the Admin Console and the PolicyEngine API + */ + 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. "; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + return; + } + if(apiflag.equalsIgnoreCase("addPolicyToGroup")){ + try{ + updateGroupsFromAPI(request, response, groupId, loggingContext); + }catch(IOException e){ + LOGGER.error(e); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + } + // this is from the Admin Console, so handle separately + try { + loggingContext.metricEnded(); + doACPut(request, response, groupId, loggingContext); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet goPut doACPut"); + } catch (IOException e) { + LOGGER.error(e); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + // + // Request is for policy validation and creation + // + if (apiflag != null && apiflag.equalsIgnoreCase("admin")){ + // this request is from the Admin Console + SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance(); + try{ + loggingContext.metricStarted(); + savePolicyHandler.doPolicyAPIPut(request, response); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler"); + } catch (IOException e) { + LOGGER.error(e); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) { + // this request is from the Policy Creation API + if(authorizeRequest(request)){ + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + try{ + loggingContext.metricStarted(); + apiRequestHandler.doPut(request, response, request.getHeader("ClientScope")); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut"); + } 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!!"; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + im.endTransaction(); + return; + } + } + // We do not expect anything from anywhere else. + // This method is here in case we ever need to support other operations. + 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"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See error.log"); + im.endTransaction(); + } + + /** + * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response) + */ + 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() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)"); + } + try { + loggingContext.metricStarted(); + im.startTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction"); + } 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(); + 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 = "PUT 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 = "PUT 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; + } + loggingContext.metricStarted(); + XACMLRest.dumpRequest(request); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest"); + String groupId = request.getParameter("groupId"); + 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. "; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message); + return; + } + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + try { + loggingContext.metricStarted(); + apiRequestHandler.doDelete(request, response, loggingContext, apiflag); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete"); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + if(apiRequestHandler.getNewGroup()!=null){ + groupChanged(apiRequestHandler.getNewGroup(), loggingContext); + } + return; + } + // this is from the Admin Console, so handle separately + try{ + loggingContext.metricStarted(); + doACDelete(request, response, groupId, loggingContext); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete"); + } catch (IOException e) { + LOGGER.error(e); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + //Catch anything that fell through + 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"); + im.endTransaction(); + } + + private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) { + 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); + return false; + } + // Compare the policies and pipconfig properties to the pdpProperties + try { + // the policy properties includes only xacml.rootPolicies and + // xacml.referencedPolicies without any .url entries + Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false); + Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties); + if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) && + localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) && + pdpPipConfig.equals(pipconfig)) { + // The PDP is current + return true; + } + } catch (Exception e) { + // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines, + // or if there are policies that do not have a corresponding ".url" property. + // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false. + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error"); + } + return false; + } + + private void populatePolicyURL(StringBuffer urlPath, Properties policies) { + String lists[] = new String[2]; + lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + for (String list : lists) { + if (list != null && list.isEmpty() == false) { + for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) { + String url = urlPath + "?id=" + id; + LOGGER.info("Policy URL for " + id + ": " + url); + policies.setProperty(id + ".url", url); + } + } + } + } + + protected String getPDPID(HttpServletRequest request) { + String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID); + if (pdpURL == null || pdpURL.isEmpty()) { + // Should send back its port for identification + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header"); + pdpURL = ""; + } + return pdpURL; + } + + protected String getPDPJMX(HttpServletRequest request) { + 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"); + return null; + } + return pdpJMMX; + } + + /** + * Requests from the PolicyEngine API to update the PDP Group with pushed policy + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @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 { + // for PUT operations the group may or may not need to exist before the operation can be done + StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId); + + // get the request input stream content into a String + String json = null; + java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + + PolicyLogger.info("pushPolicy request from API: " + json); + + // convert Object sent as JSON into local object + StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class); + + //Get the current policies from the Group and Add the new one + Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>(); + 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())){ + group.removePolicy(existingPolicy); + LOGGER.info("Removing policy: " + existingPolicy); + break; + } + } + + // Assume that this is an update of an existing PDP Group + loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); + 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()); + throw new PAPException(e.getMessage()); + } + + LOGGER.info("Calling updatGroup() with new group"); + papEngine.updateGroup(group); + String policyId = "empty"; + if(policy !=null && policy.getId() != null){ + policyId = policy.getId(); + } + if(!policyId.matches(REGEX) ){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("message", "Policy Id is not valid"); + return; + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + response.addHeader("operation", "push"); + response.addHeader("policyId", policyId); + response.addHeader("groupId", groupId); + + LOGGER.info("Group '" + group.getId() + "' updated"); + + loggingContext.metricStarted(); + acPutTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction"); + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC"); + + // Group changed, which might include changing the policies + groupChanged(group, loggingContext); + loggingContext.transactionEnded(); + LOGGER.info("Success"); + + 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."); + } + } + + 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."; + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error",ADD_GROUP_ERROR); + response.addHeader("message", message); + return; + } + } + + /** + * Requests from the Admin Console for operations not on single specific objects + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @throws 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=<groupId> groupName=<name> groupDescription=<description> <= create a new group + loggingContext.setServiceName("AC:PAP.createGroup"); + String unescapedName = null; + String unescapedDescription = null; + try{ + unescapedName = URLDecoder.decode(groupName, "UTF-8"); + unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8"); + } catch (UnsupportedEncodingException e) { + LOGGER.error(e); + } + PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction(); + try { + newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost"); + papEngine.newGroup(unescapedName, unescapedDescription); + loggingContext.metricStarted(); + newGroupTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); + } catch (Exception e) { + newGroupTransaction.rollbackTransaction(); + 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 + "'"); + return; + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("New Group '" + groupId + "' created"); + } + // tell the Admin Consoles there is a change + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC"); + // new group by definition has no PDPs, so no need to notify them of changes + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + // for all remaining POST operations the group must exist before the operation can be done + OnapPDPGroup group = null; + try{ + group = papEngine.getGroup(groupId); + } 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)){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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){ + 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); + } + return; + } + + // If the request contains a policyId then we know we are pushing the policy to PDP + if (request.getParameter("policyId") != null) { + + if(apiflag!=null){ + loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy"); + LOGGER.info("PushPolicy Request From The API"); + } else { + loggingContext.setServiceName("AC:PAP.postPolicy"); + LOGGER.info("PushPolicy Request From The AC"); + } + + String policyId = request.getParameter("policyId"); + PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction(); + StdPDPGroup updatedGroup = null; + 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"); + loggingContext.metricStarted(); + addPolicyToGroupTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); + LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed"); + + } catch (Exception e) { + addPolicyToGroupTransaction.rollbackTransaction(); + String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e; + //for fixing Header Manipulation of Fortify issue + if(!message.matches(REGEX)){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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){ + response.addHeader("error", "policyCopyError"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } else { + setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } + return; + } + + if(apiflag != null){ + /* + * 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. + */ + + // Get new transaction to perform updateGroup() + PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); + try { + // 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() : ""; + scanner.close(); + + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class); + StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON; + + LOGGER.info("Request JSON Payload: " + json); + + // Assume that this is an update of an existing PDP Group + loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); + 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); + throw new PAPException(e.getMessage()); + } + + LOGGER.info("Calling updatGroup() with new group"); + papEngine.updateGroup(updatedGroup); + + LOGGER.info("Group '" + updatedGroup.getId() + "' updated"); + + // Commit transaction to send notification to other PAPs + loggingContext.metricStarted(); + acPutTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction"); + loggingContext.metricStarted(); + + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC"); + + // Group changed to send notification to PDPs, which might include changing the policies + groupChanged(updatedGroup,loggingContext); + loggingContext.transactionEnded(); + LOGGER.info("Success"); + + 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."); + } + } + + //delete temporary policy file from the bin directory + Files.deleteIfExists(Paths.get(policy.getId())); + + } catch (Exception 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 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("message", message); + return; + } + } + + // policy file copied ok and the Group was updated on the PDP + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + response.addHeader("operation", "push"); + response.addHeader("policyId", policyId); + response.addHeader("groupId", groupId); + + LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'"); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + LOGGER.info("Transaction Ended Successfully"); + + return; + } else if (request.getParameter("default") != null) { + // Args: group=<groupId> 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. + PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction(); + try { + setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost"); + papEngine.setDefaultGroup(group); + loggingContext.metricStarted(); + setDefaultGroupTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); + } catch (Exception e) { + setDefaultGroupTransaction.rollbackTransaction(); + 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"); + return; + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + 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 + loggingContext.metricStarted(); + notifyAC(); + // This does not affect any PDPs in the existing groups, so no need to notify them of this change + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC"); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + LOGGER.info("Transaction Ended Successfully"); + return; + } else if (request.getParameter("pdpId") != null) { + doACPostTransaction = policyDBDao.getNewTransaction(); + // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group + loggingContext.setServiceName("AC:PAP.movePDP"); + String pdpId = request.getParameter("pdpId"); + OnapPDP pdp = papEngine.getPDP(pdpId); + OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp); + try{ + doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost"); + }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()); + 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"); + } + // update the status of both the original group and the new one + ((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 + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC"); + // Need to notify the PDP that it's config may have changed + pdpChanged(pdp, loggingContext); + loggingContext.metricStarted(); + doACPostTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction"); + 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; + } + } + + /** + * Requests from the Admin Console to GET info about the Groups and PDPs + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @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"); + String pdpGroup = request.getParameter("getPDPGroup"); + if ("".equals(groupId)) { + // request IS from AC but does not identify a group by name + if (parameterDefault != null) { + // Request is for the Default group (whatever its id) + loggingContext.setServiceName("AC:PAP.getDefaultGroup"); + OnapPDPGroup group = papEngine.getDefaultGroup(); + // convert response object to JSON and include in the response + 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{ response.getOutputStream().close(); } catch (IOException e){ LOGGER.error(e); } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else if (pdpId != null) { - // Request is related to a PDP - if (pdpGroup == null) { - // Request is for the (unspecified) group containing a given PDP - loggingContext.setServiceName("AC:PAP.getPDP"); - OnapPDP pdp = null; - try{ - pdp = papEngine.getPDP(pdpId); - }catch(PAPException e){ - LOGGER.error(e); - } - // convert response object to JSON and include in the response - 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{ + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else if (pdpId != null) { + // Request is related to a PDP + if (pdpGroup == null) { + // Request is for the (unspecified) group containing a given PDP + loggingContext.setServiceName("AC:PAP.getPDP"); + OnapPDP pdp = null; + try{ + pdp = papEngine.getPDP(pdpId); + }catch(PAPException e){ + LOGGER.error(e); + } + // convert response object to JSON and include in the response + 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{ + response.getOutputStream().close(); + } catch (IOException e){ + LOGGER.error(e); + } + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else { + // Request is for the group containing a given PDP + loggingContext.setServiceName("AC:PAP.getGroupForPDP"); + OnapPDPGroup group =null; + try{ + OnapPDP pdp = papEngine.getPDP(pdpId); + group = papEngine.getPDPGroup((OnapPDP) pdp); + }catch(PAPException e){ + LOGGER.error(e); + } + // convert response object to JSON and include in the response + 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{ response.getOutputStream().close(); } catch (IOException e){ LOGGER.error(e); } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else { - // Request is for the group containing a given PDP - loggingContext.setServiceName("AC:PAP.getGroupForPDP"); - OnapPDPGroup group =null; - try{ - OnapPDP pdp = papEngine.getPDP(pdpId); - group = papEngine.getPDPGroup((OnapPDP) pdp); - }catch(PAPException e){ - LOGGER.error(e); - } - // convert response object to JSON and include in the response - 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{ - response.getOutputStream().close(); - } catch (IOException e){ - LOGGER.error(e); - } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } else { - // request is for top-level properties about all groups - loggingContext.setServiceName("AC:PAP.getAllGroups"); - Set<OnapPDPGroup> groups = null; - try { - groups = papEngine.getOnapPDPGroups(); - } 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; - } - // convert response object to JSON and include in the response - 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{ - response.getOutputStream().close(); - } catch (IOException e){ - LOGGER.error(e); - } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } - // for all other GET operations the group must exist before the operation can be done - OnapPDPGroup group = null; - try{ - group = papEngine.getGroup(groupId); - } 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)){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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); - return; - } - // Figure out which request this is based on the parameters - String policyId = request.getParameter("policyId"); - if (policyId != null) { - // retrieve a policy - loggingContext.setServiceName("AC:PAP.getPolicy"); - // convert response object to JSON and include in the response - 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"); - } 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); - 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{ - response.getOutputStream().close(); - } catch (IOException e){ - LOGGER.error(e); - } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - 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. - // Other GETs that could be called: - // Specific Group (groupId=<groupId>) - // A Policy (groupId=<groupId> policyId=<policyId>) - // A PDP (groupId=<groupId> pdpId=<pdpId>) - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED "); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - 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; - } - } - - /** - * Requests from the Admin Console to create new items or update existing ones - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @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 - OnapPDPGroup group = papEngine.getGroup(groupId); - // determine the operation needed based on the parameters in the request - // for remaining operations the group must exist before the operation can be done - if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); - return; - } - if (request.getParameter("policy") != null) { - // group=<groupId> policy=<policyId> contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties) - loggingContext.setServiceName("AC:PAP.putPolicy"); - 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=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one - String pdpId = request.getParameter("pdpId"); - if (papEngine.getPDP(pdpId) == null) { - loggingContext.setServiceName("AC:PAP.createPDP"); - } else { - loggingContext.setServiceName("AC:PAP.updatePDP"); - } - // 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{ - Scanner scanner = new Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - }catch(IOException e){ - LOGGER.error(e); - } - LOGGER.info("JSON request from AC: " + json); - // convert Object sent as JSON into local object - ObjectMapper mapper = new ObjectMapper(); - Object objectFromJSON = null; - try { - objectFromJSON = mapper.readValue(json, StdPDP.class); - } 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); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON); - } - StdPDP pdp = (StdPDP) objectFromJSON; - if(pdp != null){ - OnapPDP oPDP = null; - try{ - oPDP = papEngine.getPDP(pdpId); - }catch (PAPException e){ - LOGGER.error(e); - } - if (oPDP == null) { - // this is a request to create a new PDP object - 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()); - throw new PAPException(e.getMessage()); - } - try{ - papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); - }catch(PAPException e){ - LOGGER.error(e); - } - } else { - 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()); - throw new PAPException(e.getMessage()); - } - // this is a request to update the pdp - try{ - papEngine.updatePDP(pdp); - }catch(PAPException e){ + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } else { + // request is for top-level properties about all groups + loggingContext.setServiceName("AC:PAP.getAllGroups"); + Set<OnapPDPGroup> groups = null; + try { + groups = papEngine.getOnapPDPGroups(); + } 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; + } + // convert response object to JSON and include in the response + 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{ + response.getOutputStream().close(); + } catch (IOException e){ + LOGGER.error(e); + } + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } + // for all other GET operations the group must exist before the operation can be done + OnapPDPGroup group = null; + try{ + group = papEngine.getGroup(groupId); + } 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)){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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); + return; + } + // Figure out which request this is based on the parameters + String policyId = request.getParameter("policyId"); + if (policyId != null) { + // retrieve a policy + loggingContext.setServiceName("AC:PAP.getPolicy"); + // convert response object to JSON and include in the response + 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"); + } 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); + 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{ + response.getOutputStream().close(); + } catch (IOException e){ + LOGGER.error(e); + } + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + 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. + // Other GETs that could be called: + // Specific Group (groupId=<groupId>) + // A Policy (groupId=<groupId> policyId=<policyId>) + // A PDP (groupId=<groupId> pdpId=<pdpId>) + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED "); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + 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; + } + } + + /** + * Requests from the Admin Console to create new items or update existing ones + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @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 + OnapPDPGroup group = papEngine.getGroup(groupId); + // determine the operation needed based on the parameters in the request + // for remaining operations the group must exist before the operation can be done + if (group == null) { + String message = "Unknown groupId '" + groupId + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message); + return; + } + if (request.getParameter("policy") != null) { + // group=<groupId> policy=<policyId> contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties) + loggingContext.setServiceName("AC:PAP.putPolicy"); + 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=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one + String pdpId = request.getParameter("pdpId"); + if (papEngine.getPDP(pdpId) == null) { + loggingContext.setServiceName("AC:PAP.createPDP"); + } else { + loggingContext.setServiceName("AC:PAP.updatePDP"); + } + // 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{ + Scanner scanner = new Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + }catch(IOException e){ + LOGGER.error(e); + } + LOGGER.info("JSON request from AC: " + json); + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + Object objectFromJSON = null; + try { + objectFromJSON = mapper.readValue(json, StdPDP.class); + } 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); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON); + } + StdPDP pdp = (StdPDP) objectFromJSON; + if(pdp != null){ + OnapPDP oPDP = null; + try{ + oPDP = papEngine.getPDP(pdpId); + }catch (PAPException e){ + LOGGER.error(e); + } + if (oPDP == null) { + // this is a request to create a new PDP object + 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()); + throw new PAPException(e.getMessage()); + } + try{ + papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); + }catch(PAPException e){ + LOGGER.error(e); + } + } else { + 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()); + throw new PAPException(e.getMessage()); + } + // this is a request to update the pdp + try{ + papEngine.updatePDP(pdp); + }catch(PAPException e){ LOGGER.error(e); } - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("PDP '" + pdpId + "' created/updated"); - } - // adjust the group's state including the new PDP - ((StdPDPGroup)group).resetStatus(); - // tell the Admin Consoles there is a change - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); - // this might affect the PDP, so notify it of the change - pdpChanged(pdp, loggingContext); - loggingContext.metricStarted(); - acPutTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); - 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()); - throw new PAPException("PDP is null"); - } catch(Exception e){ - throw new PAPException("PDP is null" + e.getMessage() +e); - } - } - } else if (request.getParameter("pipId") != null) { - // group=<groupId> pipId=<pipEngineId> 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; - } else { - // Assume that this is an update of an existing PDP Group - // ARGS: group=<groupId> <= Update an Existing Group - loggingContext.setServiceName("AC:PAP.updateGroup"); - // 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) + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("PDP '" + pdpId + "' created/updated"); + } + // adjust the group's state including the new PDP + ((StdPDPGroup)group).resetStatus(); + // tell the Admin Consoles there is a change + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); + // this might affect the PDP, so notify it of the change + pdpChanged(pdp, loggingContext); + loggingContext.metricStarted(); + acPutTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + 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()); + throw new PAPException("PDP is null"); + } catch(Exception e){ + throw new PAPException("PDP is null" + e.getMessage() +e); + } + } + } else if (request.getParameter("pipId") != null) { + // group=<groupId> pipId=<pipEngineId> 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; + } else { + // Assume that this is an update of an existing PDP Group + // ARGS: group=<groupId> <= Update an Existing Group + loggingContext.setServiceName("AC:PAP.updateGroup"); + // 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{ Scanner scanner = new Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); @@ -2158,880 +2158,880 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList }catch(IOException e){ LOGGER.error(e); } - LOGGER.info("JSON request from AC: " + json); - // convert Object sent as JSON into local object - ObjectMapper mapper = new ObjectMapper(); - Object objectFromJSON = null; - try { - 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); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - 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()); - } - try{ - if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){ - acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete"); - } else { - acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); - } - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " - +"group="+group.getId()); - LOGGER.error(e); - throw new PAPException(e.getMessage()); - } - - PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); - OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON; - if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) { - LOGGER.debug("Precheck Successful."); - } - try{ - papEngine.updateGroup((StdPDPGroup)objectFromJSON); - }catch(PAPException e){ - LOGGER.error(e); - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Group '" + group.getId() + "' updated"); - } - loggingContext.metricStarted(); - acPutTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); - // tell the Admin Consoles there is a change - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); - // Group changed, which might include changing the policies - groupChanged(group, loggingContext); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } catch (PAPException e) { - LOGGER.debug(e); - acPutTransaction.rollbackTransaction(); - 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; - } - } - - /** - * Requests from the Admin Console to delete/remove items - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @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 - loggingContext.setServiceName("AC:PAP.delete"); - OnapPDPGroup group = papEngine.getGroup(groupId); - if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; - 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 +"'"); - return; - } - // determine the operation needed based on the parameters in the request - if (request.getParameter("policy") != null) { - // group=<groupId> policy=<policyId> [delete=<true|false>] <= 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; - } else if (request.getParameter("pdpId") != null) { - // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP - String pdpId = request.getParameter("pdpId"); - OnapPDP pdp = papEngine.getPDP(pdpId); - try{ - removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete"); - } catch(Exception e){ - throw new PAPException(e); - } - try{ - papEngine.removePDP((OnapPDP) pdp); - }catch(PAPException e){ + LOGGER.info("JSON request from AC: " + json); + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + Object objectFromJSON = null; + try { + 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); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + 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()); + } + try{ + if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){ + acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete"); + } else { + acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); + } + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " + +"group="+group.getId()); + LOGGER.error(e); + throw new PAPException(e.getMessage()); + } + + PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); + OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON; + if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) { + LOGGER.debug("Precheck Successful."); + } + try{ + papEngine.updateGroup((StdPDPGroup)objectFromJSON); + }catch(PAPException e){ LOGGER.error(e); } - // adjust the status of the group, which may have changed when we removed this PDP - ((StdPDPGroup)group).resetStatus(); - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); - // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests) - pdpChanged(pdp, loggingContext); - loggingContext.metricStarted(); - removePdpOrGroupTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else if (request.getParameter("pipId") != null) { - // group=<groupId> pipId=<pipEngineId> <= 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; - } else { - // ARGS: group=<groupId> movePDPsToGroupId=<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{ - moveToGroup = papEngine.getGroup(moveToGroupId); - }catch(PAPException e){ - LOGGER.error(e); - } - } - // get list of PDPs in the group being deleted so we can notify them that they got changed - Set<OnapPDP> 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"); - throw new PAPException(e.getMessage()); - } - try{ - papEngine.removeGroup(group, moveToGroup); - }catch(PAPException e){ + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Group '" + group.getId() + "' updated"); + } + loggingContext.metricStarted(); + acPutTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + // tell the Admin Consoles there is a change + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); + // Group changed, which might include changing the policies + groupChanged(group, loggingContext); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } catch (PAPException e) { + LOGGER.debug(e); + acPutTransaction.rollbackTransaction(); + 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; + } + } + + /** + * Requests from the Admin Console to delete/remove items + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @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 + loggingContext.setServiceName("AC:PAP.delete"); + OnapPDPGroup group = papEngine.getGroup(groupId); + if (group == null) { + String message = "Unknown groupId '" + groupId + "'"; + 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 +"'"); + return; + } + // determine the operation needed based on the parameters in the request + if (request.getParameter("policy") != null) { + // group=<groupId> policy=<policyId> [delete=<true|false>] <= 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; + } else if (request.getParameter("pdpId") != null) { + // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP + String pdpId = request.getParameter("pdpId"); + OnapPDP pdp = papEngine.getPDP(pdpId); + try{ + removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete"); + } catch(Exception e){ + throw new PAPException(e); + } + try{ + papEngine.removePDP((OnapPDP) pdp); + }catch(PAPException e){ LOGGER.error(e); } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - loggingContext.metricStarted(); - notifyAC(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); - // notify any PDPs in the removed set that their config may have changed - for (OnapPDP pdp : movedPDPs) { - pdpChanged(pdp, loggingContext); - } - loggingContext.metricStarted(); - removePdpOrGroupTransaction.commitTransaction(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); - 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; - } - } - - /** - * 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 - * 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. - * 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. - */ - private class Heartbeat implements Runnable { - private PAPPolicyEngine papEngine; - private Set<OnapPDP> pdps = new HashSet<>(); - private int heartbeatInterval; - private int heartbeatTimeout; - - public volatile boolean isRunning = false; - - public synchronized boolean isRunning() { - return this.isRunning; - } - - public synchronized void terminate() { - this.isRunning = false; - } - - 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")); - } - - @Override - public void run() { - // Set ourselves as running - synchronized(this) { - this.isRunning = true; - } - HashMap<String, URL> idToURLMap = new HashMap<>(); - try { - while (this.isRunning()) { - // Wait the given time - Thread.sleep(heartbeatInterval); - // get the list of PDPs (may have changed since last time) - pdps.clear(); - synchronized(papEngine) { - try { - for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) { - for (OnapPDP p : g.getOnapPdps()) { - pdps.add(p); - } - } - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine"); - } - } - // Check for shutdown - if (this.isRunning() == false) { - LOGGER.info("isRunning is false, getting out of loop."); - break; - } - // try to get the summary status from each PDP - boolean changeSeen = false; - for (OnapPDP pdp : pdps) { - // Check for shutdown - if (this.isRunning() == false) { - LOGGER.info("isRunning is false, getting out of loop."); - break; - } - // the id of the PDP is its url (though we add a query parameter) - URL pdpURL = idToURLMap.get(pdp.getId()); - if (pdpURL == null) { - // haven't seen this PDP before - String fullURLString = null; - try { - // Check PDP ID - 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"); - continue; - } - } - // Do a GET with type HeartBeat - String newStatus = ""; - HttpURLConnection connection = null; - try { - // Open up the connection - 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){ - connection.setRequestProperty("Authorization", "Basic " + encoding); - } - // Do the connect - connection.connect(); - if (connection.getResponseCode() == 204) { - newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'"); - } - } 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()); - } - } - } catch (UnknownHostException e) { - newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); - 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"); - } catch (ConnectException e) { - newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); - 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"); - } finally { - // cleanup the connection - if(connection != null) - connection.disconnect(); - } - if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) { - if (LOGGER.isDebugEnabled()) { - 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()); - } - changeSeen = true; - } - } - // Check for shutdown - if (this.isRunning() == false) { - LOGGER.info("isRunning is false, getting out of loop."); - break; - } - // if any of the PDPs changed state, tell the ACs to update - if (changeSeen) { - notifyAC(); - } - } - } catch (InterruptedException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down"); - this.terminate(); - Thread.currentThread().interrupt(); - } - } - } - - /* - * HELPER to change Group status when PDP status is changed - * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock) - */ - private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException { - setPDPSummaryStatus(pdp, newStatus.toString()); - } - - private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException { - synchronized(papEngine) { - StdPDPStatus status = new StdPDPStatus(); - status.setStatus(PDPStatus.Status.valueOf(newStatus)); - ((StdPDP)pdp).setStatus(status); - // now adjust the group - 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(); - } - } - } - - /* - * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine - * in the PDP group directories - */ - @Override - public void changed() { - // all PDPs in all groups need to be updated/sync'd - Set<OnapPDPGroup> groups; - try { - groups = papEngine.getOnapPDPGroups(); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); - throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); - } - for (OnapPDPGroup group : groups) { - groupChanged(group); - } - } - - public void changed(ONAPLoggingContext loggingContext) { - // all PDPs in all groups need to be updated/sync'd - Set<OnapPDPGroup> groups; - try { - groups = papEngine.getOnapPDPGroups(); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); - throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); - } - for (OnapPDPGroup group : groups) { - groupChanged(group, loggingContext); - } - } - - @Override - public void groupChanged(OnapPDPGroup group) { - // all PDPs within one group need to be updated/sync'd - for (OnapPDP pdp : group.getOnapPdps()) { - pdpChanged(pdp); - } - } - - public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) { - // all PDPs within one group need to be updated/sync'd - for (OnapPDP pdp : group.getOnapPdps()) { - pdpChanged(pdp, loggingContext); - } - } - - @Override - 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. - Thread t = new Thread(new UpdatePDPThread(pdp)); - if(CheckPDP.validateID(pdp.getId())){ - t.start(); - } - } - - 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. - Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext)); - if(CheckPDP.validateID(pdp.getId())){ - t.start(); - } - } - - private class UpdatePDPThread implements Runnable { - private OnapPDP pdp; - private String requestId; - private ONAPLoggingContext loggingContext; - - public UpdatePDPThread(OnapPDP pdp) { - this.pdp = pdp; - } - - public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) { - this.pdp = pdp; - if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) { - this.requestId = loggingContext.getRequestID(); - } - this.loggingContext = loggingContext; - } - - public void run() { - // send the current configuration to one PDP - HttpURLConnection connection = null; - // get a new logging context for the thread - try { - if (this.loggingContext == null) { - loggingContext = new ONAPLoggingContext(baseLoggingContext); - } - } catch (Exception e) { - 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 == "")) { - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - 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()); - } - 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 (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(); - // Setup our method and headers - connection.setRequestMethod("PUT"); - // Authentication - String encoding = CheckPDP.getEncoding(pdp.getId()); - if(encoding !=null){ - connection.setRequestProperty("Authorization", "Basic " + encoding); - } - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID()); - connection.setInstanceFollowRedirects(true); - connection.setDoOutput(true); - try (OutputStream os = connection.getOutputStream()) { - OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp); - // if the PDP was just deleted, there is no group, but we want to send an update anyway - if (group == null) { - // create blank properties files - Properties policyProperties = new Properties(); - policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, ""); - policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); - policyProperties.store(os, ""); - Properties pipProps = new Properties(); - pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, ""); - pipProps.store(os, ""); - } else { - // send properties from the current group - group.getPolicyProperties().store(os, ""); - Properties policyLocations = new Properties(); - for (PDPPolicy policy : group.getPolicies()) { - 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()); - // 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; - } - // Do the connect - loggingContext.metricStarted(); - connection.connect(); - loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect"); - if (connection.getResponseCode() == 204) { - LOGGER.info("Success. We are configured correctly."); - loggingContext.transactionEnded(); - auditLogger.info("Success. PDP is configured correctly."); - PolicyLogger.audit("Transaction Success. PDP is configured correctly."); - setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); - } else if (connection.getResponseCode() == 200) { - LOGGER.info("Success. PDP needs to update its configuration."); - loggingContext.transactionEnded(); - auditLogger.info("Success. PDP needs to update its configuration."); - PolicyLogger.audit("Transaction Success. PDP is configured correctly."); - setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); - } else { - 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()); - 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() + "'"); - 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"); - } - } finally { - // cleanup the connection - if(connection != null){ - connection.disconnect(); - } - // tell the AC to update it's status info - notifyAC(); - } - } - } - - /* - * RESTful Interface from PAP to ACs notifying them of changes - */ - private void notifyAC() { - // kick off a thread to do one event notification for all registered ACs - // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data - // as part of processing this message on their end. - Thread t = new Thread(new NotifyACThread()); - t.start(); - } - - private class NotifyACThread implements Runnable { - public void run() { - List<String> disconnectedACs = new ArrayList<>(); - // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList. - // The "for each" loop uses the collection's iterator under the covers, so it should be correct. - for (String acURL : adminConsoleURLStringList) { - 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 - 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 (need to change "cache=", implying getting some input saying which to change) - URL url = new URL(acURL ); - // Open up the connection - connection = (HttpURLConnection)url.openConnection(); - // Setup our method and headers - connection.setRequestMethod("PUT"); - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // So we need to handle this ourselves. - //TODO - is this needed for a PUT? seems better to leave in for now? - connection.setInstanceFollowRedirects(false); - // Do not include any data in the PUT because this is just a - // notification to the AC. - // The AC will use GETs back to the PAP to get what it needs - // to fill in the screens. - // Do the connect - connection.connect(); - if (connection.getResponseCode() == 204) { - LOGGER.info("Success. We updated correctly."); - } else { - 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 + "'"); - disconnectedACs.add(acURL); - } finally { - // cleanup the connection - if(connection != null) - connection.disconnect(); - } - } - // remove any ACs that are no longer connected - if (!disconnectedACs.isEmpty()) { - adminConsoleURLStringList.removeAll(disconnectedACs); - } - } - } - - private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{ - LOGGER.info("Test request received"); - try { - im.evaluateSanity(); - //If we make it this far, all is well - String message = "GET:/pap/test called and PAP " + papResourceName + " is OK"; - LOGGER.info(message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.setStatus(HttpServletResponse.SC_OK); - return; - }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){ - String submsg; - if (e instanceof ForwardProgressException) { - submsg = " is not making forward progress."; - } else if (e instanceof AdministrativeStateException) { - submsg = " Administrative State is LOCKED."; - } else { - submsg = " Standby Status is NOT PROVIDING SERVICE."; - } - - String message = "GET:/pap/test called and PAP " + papResourceName + submsg - + " 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; - }catch (Exception e) { - //A subsystem is not making progress, is locked, standby or is not responding - String eMsg = e.getMessage(); - if(eMsg == null){ - eMsg = "No Exception Message"; - } - String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." - + " Exception Message: " + eMsg; - LOGGER.info(message, e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - 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){ - ssFailureList = failedSS; - }else{ - ssFailureList = ssFailureList.concat(","+failedSS); - } - } - } - if(ssFailureList == null){ - ssFailureList = "UnknownSubSystem"; - } - response.addHeader("X-ONAP-SubsystemFailure", ssFailureList); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - } - } - - /* - * Authorizing the PEP Requests. - */ - private boolean authorizeRequest(HttpServletRequest request) { - String clientCredentials = request.getHeader(ENVIRONMENT_HEADER); - // Check if the Client is Authorized. - if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ - return true; - }else{ - return false; - } - } - - 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); - } - 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()); - } - } - if (Files.notExists(webappsPathAction)) { - try { - Files.createDirectories(webappsPathAction); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: " - + webappsPathAction.toAbsolutePath().toString(), e); - } - } - actionHome = webappsPathAction.toString(); - configHome = webappsPathConfig.toString(); - } - } - - public static String getConfigHome(){ - try { - loadWebapps(); - } catch (PAPException e) { - LOGGER.debug(e); - return null; - } - return configHome; - } - - private static void setConfigHome(){ - configHome = getConfigHome(); - } - - public static String getActionHome(){ - try { - loadWebapps(); - } catch (PAPException e) { - LOGGER.debug(e); - return null; - } - return actionHome; - } - - private static void setActionHome(){ - actionHome = getActionHome(); - } - - public static EntityManagerFactory getEmf() { - return emf; - } - - public IntegrityAudit getIa() { - return ia; - } - - public static String getPDPFile(){ - return XACMLPapServlet.pdpFile; - } - - public static String getPersistenceUnit(){ - return PERSISTENCE_UNIT; - } - - public static PAPPolicyEngine getPAPEngine(){ - return papEngine; - } - - public static PolicyDBDaoTransaction getDbDaoTransaction(){ - return policyDBDao.getNewTransaction(); - } - public static String getPapDbDriver() { - return papDbDriver; - } - - public static void setPapDbDriver(String papDbDriver) { - XACMLPapServlet.papDbDriver = papDbDriver; - } - - public static String getPapDbUrl() { - return papDbUrl; - } - - public static void setPapDbUrl(String papDbUrl) { - XACMLPapServlet.papDbUrl = papDbUrl; - } - - public static String getPapDbUser() { - return papDbUser; - } - - public static void setPapDbUser(String papDbUser) { - XACMLPapServlet.papDbUser = papDbUser; - } - - public static String getPapDbPassword() { - return papDbPassword; - } - - public static void setPapDbPassword(String papDbPassword) { - XACMLPapServlet.papDbPassword = papDbPassword; - } - - public static String getMsOnapName() { - return msOnapName; - } - - public static void setMsOnapName(String msOnapName) { - XACMLPapServlet.msOnapName = msOnapName; - } - - public static String getMsPolicyName() { - return msPolicyName; - } - - public static void setMsPolicyName(String msPolicyName) { - XACMLPapServlet.msPolicyName = msPolicyName; - } + // adjust the status of the group, which may have changed when we removed this PDP + ((StdPDPGroup)group).resetStatus(); + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); + // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests) + pdpChanged(pdp, loggingContext); + loggingContext.metricStarted(); + removePdpOrGroupTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else if (request.getParameter("pipId") != null) { + // group=<groupId> pipId=<pipEngineId> <= 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; + } else { + // ARGS: group=<groupId> movePDPsToGroupId=<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{ + moveToGroup = papEngine.getGroup(moveToGroupId); + }catch(PAPException e){ + LOGGER.error(e); + } + } + // get list of PDPs in the group being deleted so we can notify them that they got changed + Set<OnapPDP> 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"); + throw new PAPException(e.getMessage()); + } + try{ + papEngine.removeGroup(group, moveToGroup); + }catch(PAPException e){ + LOGGER.error(e); + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + loggingContext.metricStarted(); + notifyAC(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC"); + // notify any PDPs in the removed set that their config may have changed + for (OnapPDP pdp : movedPDPs) { + pdpChanged(pdp, loggingContext); + } + loggingContext.metricStarted(); + removePdpOrGroupTransaction.commitTransaction(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + 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; + } + } + + /** + * 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 + * 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. + * 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. + */ + private class Heartbeat implements Runnable { + private PAPPolicyEngine papEngine; + private Set<OnapPDP> pdps = new HashSet<>(); + private int heartbeatInterval; + private int heartbeatTimeout; + + public volatile boolean isRunning = false; + + public synchronized boolean isRunning() { + return this.isRunning; + } + + public synchronized void terminate() { + this.isRunning = false; + } + + 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")); + } + + @Override + public void run() { + // Set ourselves as running + synchronized(this) { + this.isRunning = true; + } + HashMap<String, URL> idToURLMap = new HashMap<>(); + try { + while (this.isRunning()) { + // Wait the given time + Thread.sleep(heartbeatInterval); + // get the list of PDPs (may have changed since last time) + pdps.clear(); + synchronized(papEngine) { + try { + for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) { + for (OnapPDP p : g.getOnapPdps()) { + pdps.add(p); + } + } + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine"); + } + } + // Check for shutdown + if (this.isRunning() == false) { + LOGGER.info("isRunning is false, getting out of loop."); + break; + } + // try to get the summary status from each PDP + boolean changeSeen = false; + for (OnapPDP pdp : pdps) { + // Check for shutdown + if (this.isRunning() == false) { + LOGGER.info("isRunning is false, getting out of loop."); + break; + } + // the id of the PDP is its url (though we add a query parameter) + URL pdpURL = idToURLMap.get(pdp.getId()); + if (pdpURL == null) { + // haven't seen this PDP before + String fullURLString = null; + try { + // Check PDP ID + 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"); + continue; + } + } + // Do a GET with type HeartBeat + String newStatus = ""; + HttpURLConnection connection = null; + try { + // Open up the connection + 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){ + connection.setRequestProperty("Authorization", "Basic " + encoding); + } + // Do the connect + connection.connect(); + if (connection.getResponseCode() == 204) { + newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'"); + } + } 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()); + } + } + } catch (UnknownHostException e) { + newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); + 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"); + } catch (ConnectException e) { + newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); + 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"); + } finally { + // cleanup the connection + if(connection != null) + connection.disconnect(); + } + if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) { + if (LOGGER.isDebugEnabled()) { + 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()); + } + changeSeen = true; + } + } + // Check for shutdown + if (this.isRunning() == false) { + LOGGER.info("isRunning is false, getting out of loop."); + break; + } + // if any of the PDPs changed state, tell the ACs to update + if (changeSeen) { + notifyAC(); + } + } + } catch (InterruptedException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down"); + this.terminate(); + Thread.currentThread().interrupt(); + } + } + } + + /* + * HELPER to change Group status when PDP status is changed + * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock) + */ + private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException { + setPDPSummaryStatus(pdp, newStatus.toString()); + } + + private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException { + synchronized(papEngine) { + StdPDPStatus status = new StdPDPStatus(); + status.setStatus(PDPStatus.Status.valueOf(newStatus)); + ((StdPDP)pdp).setStatus(status); + // now adjust the group + 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(); + } + } + } + + /* + * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine + * in the PDP group directories + */ + @Override + public void changed() { + // all PDPs in all groups need to be updated/sync'd + Set<OnapPDPGroup> groups; + try { + groups = papEngine.getOnapPDPGroups(); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); + throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + } + for (OnapPDPGroup group : groups) { + groupChanged(group); + } + } + + public void changed(ONAPLoggingContext loggingContext) { + // all PDPs in all groups need to be updated/sync'd + Set<OnapPDPGroup> groups; + try { + groups = papEngine.getOnapPDPGroups(); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); + throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + } + for (OnapPDPGroup group : groups) { + groupChanged(group, loggingContext); + } + } + + @Override + public void groupChanged(OnapPDPGroup group) { + // all PDPs within one group need to be updated/sync'd + for (OnapPDP pdp : group.getOnapPdps()) { + pdpChanged(pdp); + } + } + + public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) { + // all PDPs within one group need to be updated/sync'd + for (OnapPDP pdp : group.getOnapPdps()) { + pdpChanged(pdp, loggingContext); + } + } + + @Override + 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. + Thread t = new Thread(new UpdatePDPThread(pdp)); + if(CheckPDP.validateID(pdp.getId())){ + t.start(); + } + } + + 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. + Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext)); + if(CheckPDP.validateID(pdp.getId())){ + t.start(); + } + } + + private class UpdatePDPThread implements Runnable { + private OnapPDP pdp; + private String requestId; + private ONAPLoggingContext loggingContext; + + public UpdatePDPThread(OnapPDP pdp) { + this.pdp = pdp; + } + + public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) { + this.pdp = pdp; + if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) { + this.requestId = loggingContext.getRequestID(); + } + this.loggingContext = loggingContext; + } + + public void run() { + // send the current configuration to one PDP + HttpURLConnection connection = null; + // get a new logging context for the thread + try { + if (this.loggingContext == null) { + loggingContext = new ONAPLoggingContext(baseLoggingContext); + } + } catch (Exception e) { + 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 == "")) { + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + 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()); + } + 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 (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(); + // Setup our method and headers + connection.setRequestMethod("PUT"); + // Authentication + String encoding = CheckPDP.getEncoding(pdp.getId()); + if(encoding !=null){ + connection.setRequestProperty("Authorization", "Basic " + encoding); + } + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID()); + connection.setInstanceFollowRedirects(true); + connection.setDoOutput(true); + try (OutputStream os = connection.getOutputStream()) { + OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp); + // if the PDP was just deleted, there is no group, but we want to send an update anyway + if (group == null) { + // create blank properties files + Properties policyProperties = new Properties(); + policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, ""); + policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); + policyProperties.store(os, ""); + Properties pipProps = new Properties(); + pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, ""); + pipProps.store(os, ""); + } else { + // send properties from the current group + group.getPolicyProperties().store(os, ""); + Properties policyLocations = new Properties(); + for (PDPPolicy policy : group.getPolicies()) { + 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()); + // 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; + } + // Do the connect + loggingContext.metricStarted(); + connection.connect(); + loggingContext.metricEnded(); + PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect"); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success. We are configured correctly."); + loggingContext.transactionEnded(); + auditLogger.info("Success. PDP is configured correctly."); + PolicyLogger.audit("Transaction Success. PDP is configured correctly."); + setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); + } else if (connection.getResponseCode() == 200) { + LOGGER.info("Success. PDP needs to update its configuration."); + loggingContext.transactionEnded(); + auditLogger.info("Success. PDP needs to update its configuration."); + PolicyLogger.audit("Transaction Success. PDP is configured correctly."); + setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); + } else { + 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()); + 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() + "'"); + 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"); + } + } finally { + // cleanup the connection + if(connection != null){ + connection.disconnect(); + } + // tell the AC to update it's status info + notifyAC(); + } + } + } + + /* + * RESTful Interface from PAP to ACs notifying them of changes + */ + private void notifyAC() { + // kick off a thread to do one event notification for all registered ACs + // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data + // as part of processing this message on their end. + Thread t = new Thread(new NotifyACThread()); + t.start(); + } + + private class NotifyACThread implements Runnable { + public void run() { + List<String> disconnectedACs = new ArrayList<>(); + // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList. + // The "for each" loop uses the collection's iterator under the covers, so it should be correct. + for (String acURL : adminConsoleURLStringList) { + 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 - 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 (need to change "cache=", implying getting some input saying which to change) + URL url = new URL(acURL ); + // Open up the connection + connection = (HttpURLConnection)url.openConnection(); + // Setup our method and headers + connection.setRequestMethod("PUT"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // So we need to handle this ourselves. + //TODO - is this needed for a PUT? seems better to leave in for now? + connection.setInstanceFollowRedirects(false); + // Do not include any data in the PUT because this is just a + // notification to the AC. + // The AC will use GETs back to the PAP to get what it needs + // to fill in the screens. + // Do the connect + connection.connect(); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success. We updated correctly."); + } else { + 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 + "'"); + disconnectedACs.add(acURL); + } finally { + // cleanup the connection + if(connection != null) + connection.disconnect(); + } + } + // remove any ACs that are no longer connected + if (!disconnectedACs.isEmpty()) { + adminConsoleURLStringList.removeAll(disconnectedACs); + } + } + } + + private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{ + LOGGER.info("Test request received"); + try { + im.evaluateSanity(); + //If we make it this far, all is well + String message = "GET:/pap/test called and PAP " + papResourceName + " is OK"; + LOGGER.info(message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.setStatus(HttpServletResponse.SC_OK); + return; + }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){ + String submsg; + if (e instanceof ForwardProgressException) { + submsg = " is not making forward progress."; + } else if (e instanceof AdministrativeStateException) { + submsg = " Administrative State is LOCKED."; + } else { + submsg = " Standby Status is NOT PROVIDING SERVICE."; + } + + String message = "GET:/pap/test called and PAP " + papResourceName + submsg + + " 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; + }catch (Exception e) { + //A subsystem is not making progress, is locked, standby or is not responding + String eMsg = e.getMessage(); + if(eMsg == null){ + eMsg = "No Exception Message"; + } + String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." + + " Exception Message: " + eMsg; + LOGGER.info(message, e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + 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){ + ssFailureList = failedSS; + }else{ + ssFailureList = ssFailureList.concat(","+failedSS); + } + } + } + if(ssFailureList == null){ + ssFailureList = "UnknownSubSystem"; + } + response.addHeader("X-ONAP-SubsystemFailure", ssFailureList); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } + } + + /* + * Authorizing the PEP Requests. + */ + private boolean authorizeRequest(HttpServletRequest request) { + String clientCredentials = request.getHeader(ENVIRONMENT_HEADER); + // Check if the Client is Authorized. + if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ + return true; + }else{ + return false; + } + } + + 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); + } + 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()); + } + } + if (Files.notExists(webappsPathAction)) { + try { + Files.createDirectories(webappsPathAction); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: " + + webappsPathAction.toAbsolutePath().toString(), e); + } + } + actionHome = webappsPathAction.toString(); + configHome = webappsPathConfig.toString(); + } + } + + public static String getConfigHome(){ + try { + loadWebapps(); + } catch (PAPException e) { + LOGGER.debug(e); + return null; + } + return configHome; + } + + private static void setConfigHome(){ + configHome = getConfigHome(); + } + + public static String getActionHome(){ + try { + loadWebapps(); + } catch (PAPException e) { + LOGGER.debug(e); + return null; + } + return actionHome; + } + + private static void setActionHome(){ + actionHome = getActionHome(); + } + + public static EntityManagerFactory getEmf() { + return emf; + } + + public IntegrityAudit getIa() { + return ia; + } + + public static String getPDPFile(){ + return XACMLPapServlet.pdpFile; + } + + public static String getPersistenceUnit(){ + return PERSISTENCE_UNIT; + } + + public static PAPPolicyEngine getPAPEngine(){ + return papEngine; + } + + public static PolicyDBDaoTransaction getDbDaoTransaction(){ + return policyDBDao.getNewTransaction(); + } + public static String getPapDbDriver() { + return papDbDriver; + } + + public static void setPapDbDriver(String papDbDriver) { + XACMLPapServlet.papDbDriver = papDbDriver; + } + + public static String getPapDbUrl() { + return papDbUrl; + } + + public static void setPapDbUrl(String papDbUrl) { + XACMLPapServlet.papDbUrl = papDbUrl; + } + + public static String getPapDbUser() { + return papDbUser; + } + + public static void setPapDbUser(String papDbUser) { + XACMLPapServlet.papDbUser = papDbUser; + } + + public static String getPapDbPassword() { + return papDbPassword; + } + + public static void setPapDbPassword(String papDbPassword) { + XACMLPapServlet.papDbPassword = papDbPassword; + } + + public static String getMsOnapName() { + return msOnapName; + } + + public static void setMsOnapName(String msOnapName) { + XACMLPapServlet.msOnapName = msOnapName; + } + + public static String getMsPolicyName() { + return msPolicyName; + } + + public static void setMsPolicyName(String msPolicyName) { + XACMLPapServlet.msPolicyName = msPolicyName; + } }
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java index c8b8c6a05..e5b6915bd 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java @@ -51,410 +51,410 @@ import org.springframework.stereotype.Service; @Primary public class CommonClassDaoImpl implements CommonClassDao{ - private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); - - - private static SessionFactory sessionFactory; - - - @Autowired - private CommonClassDaoImpl(SessionFactory sessionFactory){ - CommonClassDaoImpl.sessionFactory = sessionFactory; - } - - public CommonClassDaoImpl(){ - //Default Constructor - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List<Object> getData(Class className) { - Session session = sessionFactory.openSession(); - List<Object> data = null; - try{ - Criteria cr = session.createCriteria(className); - data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); - } - } - return data; - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List<Object> getDataById(Class className, String columnName, String key) { - Session session = sessionFactory.openSession(); - List<Object> data = null; - try { - Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ - String[] columns = columnName.split(":"); - String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ - cr.add(Restrictions.eq(columns[i], keys[i])); - } - }else{ - cr.add(Restrictions.eq(columnName, key)); - } - data = cr.list(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List<String> getDataByColumn(Class className, String columnName) { - Session session = sessionFactory.openSession(); - List<String> data = null; - try{ - Criteria cr = session.createCriteria(className); - cr.setProjection(Projections.property(columnName)); - data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); - } - } - return data; - } - - @Override - public void save(Object entity) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.persist(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - @Override - public void delete(Object entity) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.delete(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - - @Override - public void update(Object entity) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.update(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List<Object> checkDuplicateEntry(String value, String columnName, Class className) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - List<Object> data = null; - - String[] columnNames = null; - if(columnName != null && columnName.contains(":")){ - columnNames = columnName.split(":"); - } - String[] values = null; - if(value != null && value.contains(":")){ - values = value.split(":"); - } - try { - Criteria cr = session.createCriteria(className); - if(columnNames != null && values != null && columnNames.length == values.length){ - for (int i = 0; i < columnNames.length; i++){ - cr.add(Restrictions.eq(columnNames[i],values[i])); - } - }else{ - cr.add(Restrictions.eq(columnName,value)); - } - - data = cr.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - - @SuppressWarnings("unchecked") - @Override - public List<Object> getDataByQuery(String query, SimpleBindings params) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - List<Object> data = null; - try { - Query hbquery = session.createQuery(query); - for (Map.Entry<String, Object> paramPair : params.entrySet()) { - if(paramPair.getValue() instanceof java.lang.Long){ - hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue()); - } - else{ - hbquery.setParameter(paramPair.getKey(), paramPair.getValue()); - } - } - data = hbquery.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - throw e; - }finally{ - try{ - session.close(); - }catch(HibernateException e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement",e1); - } - } - return data; - } - - - @Override - public void updateQuery(String query) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - Query hbquery = session.createQuery(query); - hbquery.executeUpdate(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - } - - - @SuppressWarnings("rawtypes") - @Override - public Object getEntityItem(Class className, String columnName, String key) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - Object data = null; - try { - Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ - String[] columns = columnName.split(":"); - String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ - cr.add(Restrictions.eq(columns[i], keys[i])); - } - }else{ - cr.add(Restrictions.eq(columnName, key)); - } - data = cr.list().get(0); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - - @SuppressWarnings("unchecked") - @Override - public List<PolicyRoles> getUserRoles() { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - List<PolicyRoles> rolesData = null; - try { - Criteria cr = session.createCriteria(PolicyRoles.class); - Disjunction disjunction = Restrictions.disjunction(); - Conjunction conjunction1 = Restrictions.conjunction(); - conjunction1.add(Restrictions.eq("role", "admin")); - Conjunction conjunction2 = Restrictions.conjunction(); - conjunction2.add(Restrictions.eq("role", "editor")); - Conjunction conjunction3 = Restrictions.conjunction(); - conjunction3.add(Restrictions.eq("role", "guest")); - disjunction.add(conjunction1); - disjunction.add(conjunction2); - disjunction.add(conjunction3); - rolesData = cr.add(disjunction).list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return rolesData; - } - - - @SuppressWarnings("unchecked") - @Override - public void updateClAlarms(String clName, String alarms) { - Session session = sessionFactory.openSession(); - List<ClosedLoops> closedloopsdata = null; - Transaction tx = session.beginTransaction(); - try { - Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); + private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); + + + private static SessionFactory sessionFactory; + + + @Autowired + private CommonClassDaoImpl(SessionFactory sessionFactory){ + CommonClassDaoImpl.sessionFactory = sessionFactory; + } + + public CommonClassDaoImpl(){ + //Default Constructor + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List<Object> getData(Class className) { + Session session = sessionFactory.openSession(); + List<Object> data = null; + try{ + Criteria cr = session.createCriteria(className); + data = cr.list(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } + } + return data; + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List<Object> getDataById(Class className, String columnName, String key) { + Session session = sessionFactory.openSession(); + List<Object> data = null; + try { + Criteria cr = session.createCriteria(className); + if(columnName.contains(":") && key.contains(":")){ + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for(int i=0; i < columns.length; i++){ + cr.add(Restrictions.eq(columns[i], keys[i])); + } + }else{ + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List<String> getDataByColumn(Class className, String columnName) { + Session session = sessionFactory.openSession(); + List<String> data = null; + try{ + Criteria cr = session.createCriteria(className); + cr.setProjection(Projections.property(columnName)); + data = cr.list(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } + } + return data; + } + + @Override + public void save(Object entity) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(Object entity) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @Override + public void update(Object entity) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List<Object> checkDuplicateEntry(String value, String columnName, Class className) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List<Object> data = null; + + String[] columnNames = null; + if(columnName != null && columnName.contains(":")){ + columnNames = columnName.split(":"); + } + String[] values = null; + if(value != null && value.contains(":")){ + values = value.split(":"); + } + try { + Criteria cr = session.createCriteria(className); + if(columnNames != null && values != null && columnNames.length == values.length){ + for (int i = 0; i < columnNames.length; i++){ + cr.add(Restrictions.eq(columnNames[i],values[i])); + } + }else{ + cr.add(Restrictions.eq(columnName,value)); + } + + data = cr.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @SuppressWarnings("unchecked") + @Override + public List<Object> getDataByQuery(String query, SimpleBindings params) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List<Object> data = null; + try { + Query hbquery = session.createQuery(query); + for (Map.Entry<String, Object> paramPair : params.entrySet()) { + if(paramPair.getValue() instanceof java.lang.Long){ + hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue()); + } + else{ + hbquery.setParameter(paramPair.getKey(), paramPair.getValue()); + } + } + data = hbquery.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + throw e; + }finally{ + try{ + session.close(); + }catch(HibernateException e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement",e1); + } + } + return data; + } + + + @Override + public void updateQuery(String query) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + Query hbquery = session.createQuery(query); + hbquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + + @SuppressWarnings("rawtypes") + @Override + public Object getEntityItem(Class className, String columnName, String key) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + Object data = null; + try { + Criteria cr = session.createCriteria(className); + if(columnName.contains(":") && key.contains(":")){ + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for(int i=0; i < columns.length; i++){ + cr.add(Restrictions.eq(columns[i], keys[i])); + } + }else{ + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list().get(0); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @SuppressWarnings("unchecked") + @Override + public List<PolicyRoles> getUserRoles() { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyRoles> rolesData = null; + try { + Criteria cr = session.createCriteria(PolicyRoles.class); + Disjunction disjunction = Restrictions.disjunction(); + Conjunction conjunction1 = Restrictions.conjunction(); + conjunction1.add(Restrictions.eq("role", "admin")); + Conjunction conjunction2 = Restrictions.conjunction(); + conjunction2.add(Restrictions.eq("role", "editor")); + Conjunction conjunction3 = Restrictions.conjunction(); + conjunction3.add(Restrictions.eq("role", "guest")); + disjunction.add(conjunction1); + disjunction.add(conjunction2); + disjunction.add(conjunction3); + rolesData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return rolesData; + } + + + @SuppressWarnings("unchecked") + @Override + public void updateClAlarms(String clName, String alarms) { + Session session = sessionFactory.openSession(); + List<ClosedLoops> closedloopsdata = null; + Transaction tx = session.beginTransaction(); + try { + Criteria cr = session.createCriteria(ClosedLoops.class); + cr.add(Restrictions.eq("closedLoopControlName",clName)); + closedloopsdata = cr.list(); + ClosedLoops closedloop = closedloopsdata.get(0); + closedloop.setAlarmConditions(alarms); + session.update(closedloop); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); + }finally{ + session.close(); + } + } + + + @SuppressWarnings("unchecked") + @Override + public void updateClYaml(String clName, String yaml) { + Session session = sessionFactory.openSession(); + List<ClosedLoops> closedloopsdata = null; + Transaction tx = session.beginTransaction(); + try { + Criteria cr = session.createCriteria(ClosedLoops.class); + cr.add(Restrictions.eq("closedLoopControlName",clName)); closedloopsdata = cr.list(); - ClosedLoops closedloop = closedloopsdata.get(0); - closedloop.setAlarmConditions(alarms); - session.update(closedloop); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ - session.close(); - } - } - - - @SuppressWarnings("unchecked") - @Override - public void updateClYaml(String clName, String yaml) { - Session session = sessionFactory.openSession(); + ClosedLoops closedloop = closedloopsdata.get(0); + closedloop.setYaml(yaml); + session.update(closedloop); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); + }finally{ + session.close(); + } + } + + + @SuppressWarnings("unchecked") + @Override + public void deleteAll() { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); List<ClosedLoops> closedloopsdata = null; - Transaction tx = session.beginTransaction(); - try { - Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); + try { + Criteria cr = session.createCriteria(ClosedLoops.class); closedloopsdata = cr.list(); - ClosedLoops closedloop = closedloopsdata.get(0); - closedloop.setYaml(yaml); - session.update(closedloop); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ - session.close(); - } - } - - - @SuppressWarnings("unchecked") - @Override - public void deleteAll() { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - List<ClosedLoops> closedloopsdata = null; - try { - Criteria cr = session.createCriteria(ClosedLoops.class); - closedloopsdata = cr.list(); - - if(closedloopsdata!=null && !closedloopsdata.isEmpty()) { - LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); - for(int i=0; i < closedloopsdata.size(); i++) { - ClosedLoops cl = closedloopsdata.get(i); - session.delete(cl); - } - } else { - LOGGER.info("No ClosedLoops exist in the database, no need to delete."); - } - - tx.commit(); - }catch(Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e); - }finally{ - session.close(); - } - } - - @SuppressWarnings({ "unchecked"}) - @Override - public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - List<Object> data = null; - try { - Criteria cr = session.createCriteria(GroupPolicyScopeList.class); - cr.add(Restrictions.eq("groupList",groupListValue)); - Criterion expression = Restrictions.eq("name", groupNameValue); - cr.add(Restrictions.not(expression)); - data = cr.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - - @Override - public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) { - return null; - } + + if(closedloopsdata!=null && !closedloopsdata.isEmpty()) { + LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); + for(int i=0; i < closedloopsdata.size(); i++) { + ClosedLoops cl = closedloopsdata.get(i); + session.delete(cl); + } + } else { + LOGGER.info("No ClosedLoops exist in the database, no need to delete."); + } + + tx.commit(); + }catch(Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e); + }finally{ + session.close(); + } + } + + @SuppressWarnings({ "unchecked"}) + @Override + public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List<Object> data = null; + try { + Criteria cr = session.createCriteria(GroupPolicyScopeList.class); + cr.add(Restrictions.eq("groupList",groupListValue)); + Criterion expression = Restrictions.eq("name", groupNameValue); + cr.add(Restrictions.not(expression)); + data = cr.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @Override + public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) { + return null; + } public static void setSessionfactory(SessionFactory sessionfactory) { sessionFactory = sessionfactory; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java index dcabefcc8..79b07e2b9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java @@ -71,280 +71,280 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; * */ public class ElasticSearchPolicyUpdate { - - private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class); - protected final static JestClientFactory jestFactory = new JestClientFactory(); - - public static void main(String[] args) { - - String elkURL = null; - String databseUrl = null; - String userName = null; - String txt = null; - String databaseDriver = null; - - String propertyFile = System.getProperty("PROPERTY_FILE"); - Properties config = new Properties(); - Path file = Paths.get(propertyFile); - if(!file.toFile().exists()){ - LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString()); - }else{ - if(file.toString().endsWith(".properties")){ - try { - InputStream in = new FileInputStream(file.toFile()); - config.load(in); - elkURL = config.getProperty("policy.elk.url"); - databseUrl = config.getProperty("policy.database.url"); - userName = config.getProperty("policy.database.username"); - txt = CryptoUtils.decryptTxtNoExStr(config.getProperty("policy.database.password")); - databaseDriver = config.getProperty("policy.database.driver"); - if(elkURL == null || databseUrl == null || userName == null || txt == null || databaseDriver == null){ - LOGGER.error("please check the elk configuration"); - } - } catch (Exception e) { - LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e); - } - } - } - - Builder bulk = null; - - HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build(); - jestFactory.setHttpClientConfig(httpClientConfig); - JestHttpClient client = (JestHttpClient) jestFactory.getObject(); - - Connection conn = null; - Statement stmt = null; - ResultSet result = null; - - List<Index> listIndex = new ArrayList<>(); - - try { - Class.forName(databaseDriver); - conn = DriverManager.getConnection(databseUrl, userName, txt); - stmt = conn.createStatement(); - - String policyEntityQuery = "Select * from PolicyEntity"; - result = stmt.executeQuery(policyEntityQuery); - - while(result.next()){ - StringBuilder policyDataString = new StringBuilder("{"); - String scope = result.getString("scope"); - String policyName = result.getString("policyName"); - if(policyName != null){ - policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\","); - } - String description = result.getString("description"); - if(description != null){ - policyDataString.append("\"policyDescription\":\""+description+"\","); - } - Object policyData = result.getString("policydata"); - - if(scope != null){ - policyDataString.append("\"scope\":\""+scope+"\","); - } - String actionbodyid = result.getString("actionbodyid"); - String configurationdataid = result.getString("configurationdataid"); - - - String policyWithScopeName = scope + "." + policyName; - String _type = null; - - if(policyWithScopeName.contains(".Config_")){ - policyDataString.append("\"policyType\":\"Config\","); - if(policyWithScopeName.contains(".Config_Fault_")){ - _type = "closedloop"; - policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\","); - }else if(policyWithScopeName.contains(".Config_PM_")){ - _type = "closedloop"; - policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\","); - }else{ - _type = "config"; - policyDataString.append("\"configPolicyType\":\"Base\","); - } - }else if(policyWithScopeName.contains(".Action_")){ - _type = "action"; - policyDataString.append("\"policyType\":\"Action\","); - }else if(policyWithScopeName.contains(".Decision_")){ - _type = "decision"; - policyDataString.append("\"policyType\":\"Decision\","); - } - - if(!"decision".equals(_type)){ - if(configurationdataid != null){ - updateConfigData(conn, configurationdataid, policyDataString); - } - if(actionbodyid != null){ - updateActionData(conn, actionbodyid, policyDataString); - } - } - - String _id = policyWithScopeName; - - String dataString = constructPolicyData(policyData, policyDataString); - dataString = dataString.substring(0, dataString.length()-1); - dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}"; - dataString = dataString.replace("null", "\"\""); - dataString = dataString.replaceAll("\n", ""); - - try{ - Gson gson = new Gson(); - gson.fromJson(dataString, Object.class); - }catch(Exception e){ - LOGGER.error(e); - continue; - } - - if("config".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build()); - }else if("closedloop".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build()); - }else if("action".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build()); - }else if("decision".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build()); - } - } - - result.close(); - bulk = new Bulk.Builder(); - for(int i =0; i < listIndex.size(); i++){ - bulk.addAction(listIndex.get(i)); - } - BulkResult searchResult = client.execute(bulk.build()); - if(searchResult.isSucceeded()){ - LOGGER.debug("Success"); - }else{ - LOGGER.error("Failure"); - } - } catch (Exception e) { - LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e); - }finally{ - if(result != null){ - try { - result.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the resultset"+e); - } - } - if(stmt != null){ - try { - stmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the statement"+e); - } - } - if(conn != null){ - try { - conn.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the connection"+e); - } - } - } - } - - public static String constructPolicyData(Object policyContent, StringBuilder policyDataString){ - InputStream stream = new ByteArrayInputStream(policyContent.toString().getBytes(StandardCharsets.UTF_8)); - Object policyData = XACMLPolicyScanner.readPolicy(stream); - if(policyData instanceof PolicyType){ - PolicyType policy = (PolicyType) policyData; - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyDataString.append("\"onapName\":\""+value+"\","); - } - if ("RiskType".equals(attributeId)){ - policyDataString.append("\"riskType\":\""+value+"\","); - } - if ("RiskLevel".equals(attributeId)){ - policyDataString.append("\"riskLevel\":\""+value+"\","); - } - if ("guard".equals(attributeId)){ - policyDataString.append("\"guard\":\""+value+"\","); - } - if ("ConfigName".equals(attributeId)){ - policyDataString.append("\"configName\":\""+value+"\","); - } - } - } - } - } - } - } - } - } - return policyDataString.toString(); - } - - private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) throws Exception { - - PreparedStatement pstmt = null; - ResultSet configResult = null; - try { - String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?"; - pstmt = null; - pstmt = conn.prepareStatement(configEntityQuery); - pstmt.setString(1, configurationdataid); - configResult = pstmt.executeQuery(); - while(configResult.next()){ - String configBody = configResult.getString("configbody"); - String configType = configResult.getString("configtype"); - if(configBody!=null){ - configBody = configBody.replace("null", "\"\""); - configBody= configBody.replace("\"", "\\\""); - policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\","); - } - } - } catch(Exception e) { - LOGGER.error("Exception Occured while updating configData"+e); - throw(e); - } finally { - if(configResult != null){ - try { - configResult.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the ResultSet"+e); - } - } - if(pstmt != null){ - try { - pstmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the PreparedStatement"+e); - } - } - } - } - - private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception { + + private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class); + protected final static JestClientFactory jestFactory = new JestClientFactory(); + + public static void main(String[] args) { + + String elkURL = null; + String databseUrl = null; + String userName = null; + String txt = null; + String databaseDriver = null; + + String propertyFile = System.getProperty("PROPERTY_FILE"); + Properties config = new Properties(); + Path file = Paths.get(propertyFile); + if(!file.toFile().exists()){ + LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString()); + }else{ + if(file.toString().endsWith(".properties")){ + try { + InputStream in = new FileInputStream(file.toFile()); + config.load(in); + elkURL = config.getProperty("policy.elk.url"); + databseUrl = config.getProperty("policy.database.url"); + userName = config.getProperty("policy.database.username"); + txt = CryptoUtils.decryptTxtNoExStr(config.getProperty("policy.database.password")); + databaseDriver = config.getProperty("policy.database.driver"); + if(elkURL == null || databseUrl == null || userName == null || txt == null || databaseDriver == null){ + LOGGER.error("please check the elk configuration"); + } + } catch (Exception e) { + LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e); + } + } + } + + Builder bulk = null; + + HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build(); + jestFactory.setHttpClientConfig(httpClientConfig); + JestHttpClient client = (JestHttpClient) jestFactory.getObject(); + + Connection conn = null; + Statement stmt = null; + ResultSet result = null; + + List<Index> listIndex = new ArrayList<>(); + + try { + Class.forName(databaseDriver); + conn = DriverManager.getConnection(databseUrl, userName, txt); + stmt = conn.createStatement(); + + String policyEntityQuery = "Select * from PolicyEntity"; + result = stmt.executeQuery(policyEntityQuery); + + while(result.next()){ + StringBuilder policyDataString = new StringBuilder("{"); + String scope = result.getString("scope"); + String policyName = result.getString("policyName"); + if(policyName != null){ + policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\","); + } + String description = result.getString("description"); + if(description != null){ + policyDataString.append("\"policyDescription\":\""+description+"\","); + } + Object policyData = result.getString("policydata"); + + if(scope != null){ + policyDataString.append("\"scope\":\""+scope+"\","); + } + String actionbodyid = result.getString("actionbodyid"); + String configurationdataid = result.getString("configurationdataid"); + + + String policyWithScopeName = scope + "." + policyName; + String _type = null; + + if(policyWithScopeName.contains(".Config_")){ + policyDataString.append("\"policyType\":\"Config\","); + if(policyWithScopeName.contains(".Config_Fault_")){ + _type = "closedloop"; + policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\","); + }else if(policyWithScopeName.contains(".Config_PM_")){ + _type = "closedloop"; + policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\","); + }else{ + _type = "config"; + policyDataString.append("\"configPolicyType\":\"Base\","); + } + }else if(policyWithScopeName.contains(".Action_")){ + _type = "action"; + policyDataString.append("\"policyType\":\"Action\","); + }else if(policyWithScopeName.contains(".Decision_")){ + _type = "decision"; + policyDataString.append("\"policyType\":\"Decision\","); + } + + if(!"decision".equals(_type)){ + if(configurationdataid != null){ + updateConfigData(conn, configurationdataid, policyDataString); + } + if(actionbodyid != null){ + updateActionData(conn, actionbodyid, policyDataString); + } + } + + String _id = policyWithScopeName; + + String dataString = constructPolicyData(policyData, policyDataString); + dataString = dataString.substring(0, dataString.length()-1); + dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}"; + dataString = dataString.replace("null", "\"\""); + dataString = dataString.replaceAll("\n", ""); + + try{ + Gson gson = new Gson(); + gson.fromJson(dataString, Object.class); + }catch(Exception e){ + LOGGER.error(e); + continue; + } + + if("config".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build()); + }else if("closedloop".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build()); + }else if("action".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build()); + }else if("decision".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build()); + } + } + + result.close(); + bulk = new Bulk.Builder(); + for(int i =0; i < listIndex.size(); i++){ + bulk.addAction(listIndex.get(i)); + } + BulkResult searchResult = client.execute(bulk.build()); + if(searchResult.isSucceeded()){ + LOGGER.debug("Success"); + }else{ + LOGGER.error("Failure"); + } + } catch (Exception e) { + LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e); + }finally{ + if(result != null){ + try { + result.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the resultset"+e); + } + } + if(stmt != null){ + try { + stmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the statement"+e); + } + } + if(conn != null){ + try { + conn.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the connection"+e); + } + } + } + } + + public static String constructPolicyData(Object policyContent, StringBuilder policyDataString){ + InputStream stream = new ByteArrayInputStream(policyContent.toString().getBytes(StandardCharsets.UTF_8)); + Object policyData = XACMLPolicyScanner.readPolicy(stream); + if(policyData instanceof PolicyType){ + PolicyType policy = (PolicyType) policyData; + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if ("ONAPName".equals(attributeId)) { + policyDataString.append("\"onapName\":\""+value+"\","); + } + if ("RiskType".equals(attributeId)){ + policyDataString.append("\"riskType\":\""+value+"\","); + } + if ("RiskLevel".equals(attributeId)){ + policyDataString.append("\"riskLevel\":\""+value+"\","); + } + if ("guard".equals(attributeId)){ + policyDataString.append("\"guard\":\""+value+"\","); + } + if ("ConfigName".equals(attributeId)){ + policyDataString.append("\"configName\":\""+value+"\","); + } + } + } + } + } + } + } + } + } + return policyDataString.toString(); + } + + private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) throws Exception { + + PreparedStatement pstmt = null; + ResultSet configResult = null; + try { + String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?"; + pstmt = null; + pstmt = conn.prepareStatement(configEntityQuery); + pstmt.setString(1, configurationdataid); + configResult = pstmt.executeQuery(); + while(configResult.next()){ + String configBody = configResult.getString("configbody"); + String configType = configResult.getString("configtype"); + if(configBody!=null){ + configBody = configBody.replace("null", "\"\""); + configBody= configBody.replace("\"", "\\\""); + policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\","); + } + } + } catch(Exception e) { + LOGGER.error("Exception Occured while updating configData"+e); + throw(e); + } finally { + if(configResult != null){ + try { + configResult.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the ResultSet"+e); + } + } + if(pstmt != null){ + try { + pstmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the PreparedStatement"+e); + } + } + } + } + + private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception { PreparedStatement pstmt = null; ResultSet actionResult = null; @@ -378,5 +378,5 @@ public class ElasticSearchPolicyUpdate { } } } - } + } }
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java index 83d5c3ff9..e895b6336 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -27,78 +27,78 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter; import io.searchbox.client.JestResult; public interface ElkConnector { - - public static final String ELK_URL = "http://localhost:9200"; - public static final String ELK_INDEX_POLICY = "policy"; - - public enum PolicyIndexType { - config, - action, - decision, - closedloop, - all, - } - - public enum PolicyType { - Config, - Action, - Decision, - Config_Fault, - Config_PM, - Config_FW, - Config_MS, - Config_OOF, - none, - } - - public enum PolicyBodyType { - json, - xml, - properties, - txt, - none, - } - - public boolean delete(PolicyRestAdapter policyData) - throws IllegalStateException; - - public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException; - - public JestResult search(PolicyIndexType type, String text, - Map<String, String> searchKeyValue) - throws IllegalStateException, IllegalArgumentException; - - public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; - - public ElkConnector singleton = new ElkConnectorImpl(); - - public static PolicyIndexType toPolicyIndexType(String policyName) - throws IllegalArgumentException { - if (policyName == null) - throw new IllegalArgumentException("Unsupported NULL policy name conversion"); - - if (policyName.startsWith("Config_Fault")) { - return PolicyIndexType.closedloop; - } else if (policyName.startsWith("Config_PM")) { - return PolicyIndexType.closedloop; - } else if (policyName.startsWith("Config_FW")) { - return PolicyIndexType.config; - } else if (policyName.startsWith("Config_MS")) { - return PolicyIndexType.config; - } else if (policyName.startsWith("Config_OOF")) { - return PolicyIndexType.config; - }else if (policyName.startsWith("Action")) { - return PolicyIndexType.action; - } else if (policyName.startsWith("Decision")) { - return PolicyIndexType.decision; - } else if (policyName.startsWith("Config")) { - return PolicyIndexType.config; - } else { - throw new IllegalArgumentException - ("Unsupported policy name conversion to index: " + - policyName); - } - } - + + public static final String ELK_URL = "http://localhost:9200"; + public static final String ELK_INDEX_POLICY = "policy"; + + public enum PolicyIndexType { + config, + action, + decision, + closedloop, + all, + } + + public enum PolicyType { + Config, + Action, + Decision, + Config_Fault, + Config_PM, + Config_FW, + Config_MS, + Config_OOF, + none, + } + + public enum PolicyBodyType { + json, + xml, + properties, + txt, + none, + } + + public boolean delete(PolicyRestAdapter policyData) + throws IllegalStateException; + + public JestResult search(PolicyIndexType type, String text) + throws IllegalStateException, IllegalArgumentException; + + public JestResult search(PolicyIndexType type, String text, + Map<String, String> searchKeyValue) + throws IllegalStateException, IllegalArgumentException; + + public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; + + public ElkConnector singleton = new ElkConnectorImpl(); + + public static PolicyIndexType toPolicyIndexType(String policyName) + throws IllegalArgumentException { + if (policyName == null) + throw new IllegalArgumentException("Unsupported NULL policy name conversion"); + + if (policyName.startsWith("Config_Fault")) { + return PolicyIndexType.closedloop; + } else if (policyName.startsWith("Config_PM")) { + return PolicyIndexType.closedloop; + } else if (policyName.startsWith("Config_FW")) { + return PolicyIndexType.config; + } else if (policyName.startsWith("Config_MS")) { + return PolicyIndexType.config; + } else if (policyName.startsWith("Config_OOF")) { + return PolicyIndexType.config; + }else if (policyName.startsWith("Action")) { + return PolicyIndexType.action; + } else if (policyName.startsWith("Decision")) { + return PolicyIndexType.decision; + } else if (policyName.startsWith("Config")) { + return PolicyIndexType.config; + } else { + throw new IllegalArgumentException + ("Unsupported policy name conversion to index: " + + policyName); + } + } + } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java index d87e75f71..19a7ed294 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -47,384 +47,384 @@ import io.searchbox.params.Parameters; public class ElkConnectorImpl implements ElkConnector{ - private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class); - - protected final JestClientFactory jestFactory = new JestClientFactory(); - protected final JestClient jestClient; - protected static int QUERY_MAXRECORDS = 1000; - - public ElkConnectorImpl() { - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("ENTER: -"); - } - HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); - jestFactory.setHttpClientConfig(jestClientConfig); - jestClient = jestFactory.getObject(); - } - - protected boolean isType(PolicyIndexType type) throws IOException { - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("ENTER: -"); - } - - try { - Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); - JestResult result = jestClient.execute(typeQuery); - - if (LOGGER.isInfoEnabled()) { - LOGGER.info("JSON:" + result.getJsonString()); - LOGGER.info("ERROR:" + result.getErrorMessage()); - LOGGER.info("PATH:" + result.getPathToResult()); - LOGGER.info(result.getJsonObject()); - } - return result.isSucceeded(); - } catch (IOException e) { - LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); - throw e; - } - } - - protected boolean isIndex() throws IOException { - try { - Action<JestResult> indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build(); - - JestResult result = jestClient.execute(indexQuery); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("JSON:" + result.getJsonString()); - LOGGER.info("ERROR:" + result.getErrorMessage()); - LOGGER.info("PATH:" + result.getPathToResult()); - LOGGER.info(result.getJsonObject()); - } - return result.isSucceeded(); - } catch (IOException e) { - LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); - throw e; - } - } - private boolean isAlphaNumeric(String query){ - return query.matches("[a-zA-Z_0-9]+"); - } - - @Override - public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ - LOGGER.trace("ENTER: " + text); - } - - if (text == null || text.isEmpty()) { - throw new IllegalArgumentException("No search string provided"); - } - - if(!isAlphaNumeric(text)){ - throw new IllegalArgumentException("Search must be alpha numeric"); - } - - QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*"); - SearchSourceBuilder searchSourceBuilder = - new SearchSourceBuilder().query(mQ); - - Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). - addIndex(ELK_INDEX_POLICY). - setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); - - if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { - if (pT != PolicyIndexType.all) { - searchBuilder.addType(pT.toString()); - } - } - } else { - searchBuilder.addType(type.toString()); - } - - Search search = searchBuilder.build(); - JestResult result; - try { - result = jestClient.execute(search); - } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); - throw new IllegalStateException(ioe); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); - } - } else { - /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); - } - - String errorMessage = result.getErrorMessage(); - if (errorMessage != null && !errorMessage.isEmpty()) { - String xMessage; - if (errorMessage.contains("TokenMgrError")) { - int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("QueryParsingException")) { - int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("JsonParseException")) { - int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("Parse Failure")) { - int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("SearchParseException")) { - int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else { - xMessage = result.getErrorMessage(); - } - throw new IllegalStateException(xMessage); - } - } - - return result; - } - - - @Override - public JestResult search(PolicyIndexType type, String text, - Map<String, String> filter_s) - throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ - LOGGER.trace("ENTER: " + text); - } - - if (filter_s == null || filter_s.size() == 0) { - return search(type, text); - } - - if(!isAlphaNumeric(text)){ - throw new IllegalArgumentException("Search must be alpha numeric"); - } - - String matches_s = ""; - matches_s = "{\n" + - " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + - " \"query\": {\n" + - " \"bool\" : {\n" + - " \"must\" : ["; - - String match_params = ""; - boolean first = true; - for(Entry<String, String> entry : filter_s.entrySet()){ - String key = entry.getKey(); - String value = entry.getValue(); - if(first){ - match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},"; - first = false; - }else{ - match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },"; - } - } - if(match_params.endsWith(",")){ - match_params = match_params.substring(0, match_params.length()-2); - } - - matches_s = matches_s + "{\n" + match_params + "\n}" ; - - boolean query = false; - String query_String = ""; - if(text != null){ - query = true; - query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}"; - } - - if(query){ - matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; - }else{ - matches_s = matches_s + "]\n}\n}\n}"; - } - - Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY); - - if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { - if (pT != PolicyIndexType.all) { - searchBuilder.addType(pT.toString()); - } - } - } else { - searchBuilder.addType(type.toString()); - } - - Search search = searchBuilder.build(); - - JestResult result; - try { - result = jestClient.execute(search); - } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); - throw new IllegalStateException(ioe); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); - } - } else { - /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); - } - - String errorMessage = result.getErrorMessage(); - if (errorMessage != null && !errorMessage.isEmpty()) { - String xMessage = errorMessage; - if (errorMessage.contains("TokenMgrError")) { - int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("QueryParsingException")) { - int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("JsonParseException")) { - int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("Parse Failure")) { - int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("SearchParseException")) { - int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else { - xMessage = result.getErrorMessage(); - } - throw new IllegalStateException(xMessage); - } - } - - return result; - } - - public boolean put(PolicyRestAdapter policyData) - throws IOException, IllegalStateException { - if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER"); - - PolicyIndexType indexType; - try { - String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ - policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - policyName = policyName.replace(".Decision_", ":Decision_"); - } - - String[] splitPolicyName = policyName.split(":"); - indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); - } catch (IllegalArgumentException e) { - LOGGER.error(e); - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage()); - } - PolicyElasticData elasticData = new PolicyElasticData(policyData); - JSONObject jsonObj = new JSONObject(elasticData); - Index elkPut = new Index.Builder(jsonObj.toString()). - index(ELK_INDEX_POLICY). - type(indexType.name()). - id(elasticData.getPolicyName()). - refresh(true). - build(); - - JestResult result = jestClient.execute(elkPut); - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()) - LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - } else { - if (LOGGER.isWarnEnabled()) - LOGGER.warn("ElkConnector: FAILURE: PUT operation of "+ "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - - } - - return result.isSucceeded(); - } - - @Override - public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { - PolicyIndexType indexType = null; - JestResult result; - try { - String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ - policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - policyName = policyName.replace(".Decision_", ":Decision_"); - } - - String[] splitPolicyName = policyName.split(":"); - indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); - if (!isType(indexType)) { - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + - " Type: " + indexType + - " is not configured"); - } - PolicyElasticData elasticData = new PolicyElasticData(policyData); - Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY). - type(indexType.name()).build(); - result = jestClient.execute(deleteRequest); - } catch (IllegalArgumentException | IOException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + - indexType + ": null" + ":" + policyData.getNewFileName() + ": " + - e.getMessage(), e); - throw new IllegalStateException(e); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - } else { - if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - } - - return result.isSucceeded(); - } - - @Override - public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("ENTER"); - } - try { - boolean success = put(policyData); - return success; - } catch (Exception e) { - LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e); - throw new IllegalStateException(e); - } - } + private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class); + + protected final JestClientFactory jestFactory = new JestClientFactory(); + protected final JestClient jestClient; + protected static int QUERY_MAXRECORDS = 1000; + + public ElkConnectorImpl() { + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("ENTER: -"); + } + HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); + jestFactory.setHttpClientConfig(jestClientConfig); + jestClient = jestFactory.getObject(); + } + + protected boolean isType(PolicyIndexType type) throws IOException { + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("ENTER: -"); + } + + try { + Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); + JestResult result = jestClient.execute(typeQuery); + + if (LOGGER.isInfoEnabled()) { + LOGGER.info("JSON:" + result.getJsonString()); + LOGGER.info("ERROR:" + result.getErrorMessage()); + LOGGER.info("PATH:" + result.getPathToResult()); + LOGGER.info(result.getJsonObject()); + } + return result.isSucceeded(); + } catch (IOException e) { + LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); + throw e; + } + } + + protected boolean isIndex() throws IOException { + try { + Action<JestResult> indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build(); + + JestResult result = jestClient.execute(indexQuery); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("JSON:" + result.getJsonString()); + LOGGER.info("ERROR:" + result.getErrorMessage()); + LOGGER.info("PATH:" + result.getPathToResult()); + LOGGER.info(result.getJsonObject()); + } + return result.isSucceeded(); + } catch (IOException e) { + LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); + throw e; + } + } + private boolean isAlphaNumeric(String query){ + return query.matches("[a-zA-Z_0-9]+"); + } + + @Override + public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()){ + LOGGER.trace("ENTER: " + text); + } + + if (text == null || text.isEmpty()) { + throw new IllegalArgumentException("No search string provided"); + } + + if(!isAlphaNumeric(text)){ + throw new IllegalArgumentException("Search must be alpha numeric"); + } + + QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*"); + SearchSourceBuilder searchSourceBuilder = + new SearchSourceBuilder().query(mQ); + + Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). + addIndex(ELK_INDEX_POLICY). + setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); + + if (type == null || type == PolicyIndexType.all) { + for (PolicyIndexType pT: PolicyIndexType.values()) { + if (pT != PolicyIndexType.all) { + searchBuilder.addType(pT.toString()); + } + } + } else { + searchBuilder.addType(type.toString()); + } + + Search search = searchBuilder.build(); + JestResult result; + try { + result = jestClient.execute(search); + } catch (IOException ioe) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + search + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()){ + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } + } else { + /* Unsuccessful search */ + if (LOGGER.isWarnEnabled()){ + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + + search.getURI() + ":" + + result.getPathToResult() + ":" + + result.getJsonString() + ":" + + result.getErrorMessage()); + } + + String errorMessage = result.getErrorMessage(); + if (errorMessage != null && !errorMessage.isEmpty()) { + String xMessage; + if (errorMessage.contains("TokenMgrError")) { + int indexError = errorMessage.lastIndexOf("TokenMgrError"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("QueryParsingException")) { + int indexError = errorMessage.lastIndexOf("QueryParsingException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("JsonParseException")) { + int indexError = errorMessage.lastIndexOf("JsonParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("Parse Failure")) { + int indexError = errorMessage.lastIndexOf("Parse Failure"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("SearchParseException")) { + int indexError = errorMessage.lastIndexOf("SearchParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else { + xMessage = result.getErrorMessage(); + } + throw new IllegalStateException(xMessage); + } + } + + return result; + } + + + @Override + public JestResult search(PolicyIndexType type, String text, + Map<String, String> filter_s) + throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()){ + LOGGER.trace("ENTER: " + text); + } + + if (filter_s == null || filter_s.size() == 0) { + return search(type, text); + } + + if(!isAlphaNumeric(text)){ + throw new IllegalArgumentException("Search must be alpha numeric"); + } + + String matches_s = ""; + matches_s = "{\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"must\" : ["; + + String match_params = ""; + boolean first = true; + for(Entry<String, String> entry : filter_s.entrySet()){ + String key = entry.getKey(); + String value = entry.getValue(); + if(first){ + match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},"; + first = false; + }else{ + match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },"; + } + } + if(match_params.endsWith(",")){ + match_params = match_params.substring(0, match_params.length()-2); + } + + matches_s = matches_s + "{\n" + match_params + "\n}" ; + + boolean query = false; + String query_String = ""; + if(text != null){ + query = true; + query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}"; + } + + if(query){ + matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; + }else{ + matches_s = matches_s + "]\n}\n}\n}"; + } + + Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY); + + if (type == null || type == PolicyIndexType.all) { + for (PolicyIndexType pT: PolicyIndexType.values()) { + if (pT != PolicyIndexType.all) { + searchBuilder.addType(pT.toString()); + } + } + } else { + searchBuilder.addType(type.toString()); + } + + Search search = searchBuilder.build(); + + JestResult result; + try { + result = jestClient.execute(search); + } catch (IOException ioe) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + search + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()){ + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } + } else { + /* Unsuccessful search */ + if (LOGGER.isWarnEnabled()){ + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + + search.getURI() + ":" + + result.getPathToResult() + ":" + + result.getJsonString() + ":" + + result.getErrorMessage()); + } + + String errorMessage = result.getErrorMessage(); + if (errorMessage != null && !errorMessage.isEmpty()) { + String xMessage = errorMessage; + if (errorMessage.contains("TokenMgrError")) { + int indexError = errorMessage.lastIndexOf("TokenMgrError"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("QueryParsingException")) { + int indexError = errorMessage.lastIndexOf("QueryParsingException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("JsonParseException")) { + int indexError = errorMessage.lastIndexOf("JsonParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("Parse Failure")) { + int indexError = errorMessage.lastIndexOf("Parse Failure"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("SearchParseException")) { + int indexError = errorMessage.lastIndexOf("SearchParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else { + xMessage = result.getErrorMessage(); + } + throw new IllegalStateException(xMessage); + } + } + + return result; + } + + public boolean put(PolicyRestAdapter policyData) + throws IOException, IllegalStateException { + if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER"); + + PolicyIndexType indexType; + try { + String policyName = policyData.getNewFileName(); + if(policyName.contains("Config_")){ + policyName = policyName.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + policyName = policyName.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + policyName = policyName.replace(".Decision_", ":Decision_"); + } + + String[] splitPolicyName = policyName.split(":"); + indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); + } catch (IllegalArgumentException e) { + LOGGER.error(e); + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage()); + } + PolicyElasticData elasticData = new PolicyElasticData(policyData); + JSONObject jsonObj = new JSONObject(elasticData); + Index elkPut = new Index.Builder(jsonObj.toString()). + index(ELK_INDEX_POLICY). + type(indexType.name()). + id(elasticData.getPolicyName()). + refresh(true). + build(); + + JestResult result = jestClient.execute(elkPut); + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()) + LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } else { + if (LOGGER.isWarnEnabled()) + LOGGER.warn("ElkConnector: FAILURE: PUT operation of "+ "->" + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + + } + + return result.isSucceeded(); + } + + @Override + public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { + PolicyIndexType indexType = null; + JestResult result; + try { + String policyName = policyData.getNewFileName(); + if(policyName.contains("Config_")){ + policyName = policyName.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + policyName = policyName.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + policyName = policyName.replace(".Decision_", ":Decision_"); + } + + String[] splitPolicyName = policyName.split(":"); + indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); + if (!isType(indexType)) { + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + + " Type: " + indexType + + " is not configured"); + } + PolicyElasticData elasticData = new PolicyElasticData(policyData); + Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY). + type(indexType.name()).build(); + result = jestClient.execute(deleteRequest); + } catch (IllegalArgumentException | IOException e) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + + indexType + ": null" + ":" + policyData.getNewFileName() + ": " + + e.getMessage(), e); + throw new IllegalStateException(e); + } + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()) + LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } else { + if (LOGGER.isWarnEnabled()) + LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } + + return result.isSucceeded(); + } + + @Override + public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("ENTER"); + } + try { + boolean success = put(policyData); + return success; + } catch (Exception e) { + LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e); + throw new IllegalStateException(e); + } + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java index e56e82cbf..988640ca6 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java @@ -28,596 +28,596 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.adapter.YAMLParams; public class PolicyElasticData { - - private String scope; - private String policyType; - private String configPolicyType; - private String configBodyData; - private String policyName; - private String policyDescription; - private String onapName; - private String configName; - private String configType; - private String jsonBody; - private Object jsonBodyData; - - private Map<?, ?> serviceTypePolicyName; - private Map<?, ?> verticaMetrics; + + private String scope; + private String policyType; + private String configPolicyType; + private String configBodyData; + private String policyName; + private String policyDescription; + private String onapName; + private String configName; + private String configType; + private String jsonBody; + private Object jsonBodyData; + + private Map<?, ?> serviceTypePolicyName; + private Map<?, ?> verticaMetrics; private Map<?, ?> description; private Map<?, ?> attributeFields; - //Safe Policy - private String policyScope; - private String providerComboBox; - private String riskType; - private String riskLevel; - private String guard; - private String ttlDate; - private Map<String,String> matching; - - private List<Object> triggerSignatures; - private List<Object> symptomSignatures; - private String logicalConnector; - private String policyStatus; - public String gocServerScope; - private String supressionType; - - //MicroSerice - private String serviceType; - private String uuid; - private String location; - private String priority; - private String msLocation; - - //BRMS Policies - private String ruleName; - private Map<String,String> brmsParamBody; - private String brmsController; - private List<String> brmsDependency; - private LinkedHashMap<?, ?> ruleData; - private LinkedHashMap<?,?> ruleListData; - private Map<String,String> drlRuleAndUIParams; - - //ClosedLoop - private String clearTimeOut; - private String trapMaxAge; - private String verificationclearTimeOut; - public Map<String , String> dynamicLayoutMap; - - //FireWall - private String fwPolicyType; - private List<Object> fwattributes; - private String parentForChild; - private String securityZone; - - //Action & Decision - private String ruleCombiningAlgId; - private Map<String,String> dynamicFieldConfigAttributes; - private Map<String,String> dynamicSettingsMap; - private Map<String,String> dropDownMap; - private String actionPerformer; - private String actionAttribute; - private List<String> dynamicRuleAlgorithmLabels; - private List<String> dynamicRuleAlgorithmCombo; - private List<String> dynamicRuleAlgorithmField1; - private List<String> dynamicRuleAlgorithmField2; - private List<Object> dynamicVariableList; - private List<String> dataTypeList; - private String actionAttributeValue; - private String ruleProvider; - private String actionBody; - private String actionDictHeader; - private String actionDictType; - private String actionDictUrl; - private String actionDictMethod; - private YAMLParams yamlparams; - - public PolicyElasticData(PolicyRestAdapter policyData) { - this.scope = policyData.getDomainDir(); - this.policyType = policyData.getPolicyType(); - this.configPolicyType = policyData.getConfigPolicyType(); - this.configBodyData = policyData.getConfigBodyData(); - this.policyName = policyData.getNewFileName(); - this.policyDescription = policyData.getPolicyDescription(); - this.onapName = policyData.getOnapName(); - this.configName = policyData.getConfigName(); - this.configType = policyData.getConfigType(); - this.jsonBody = policyData.getJsonBody(); - if(configPolicyType.startsWith("ClosedLoop")){ - this.jsonBodyData = jsonBody; - }else{ - this.jsonBodyData = policyData.getJsonBodyData(); - } - - this.serviceTypePolicyName = policyData.getServiceTypePolicyName(); - this.verticaMetrics = policyData.getVerticaMetrics(); - this.description = policyData.getDescription(); - this.attributeFields = policyData.getAttributeFields(); - - //Safe Policy - this.policyScope = policyData.getPolicyScope(); - this.providerComboBox = policyData.getProviderComboBox(); - this.riskType = policyData.getRiskType(); - this.riskLevel = policyData.getRiskLevel(); - this.guard = policyData.getGuard(); - this.ttlDate = policyData.getTtlDate(); - this.matching = policyData.getMatching(); - - this.triggerSignatures = policyData.getTriggerSignatures(); - this.symptomSignatures = policyData.getSymptomSignatures(); - this.logicalConnector = policyData.getLogicalConnector(); - this.policyStatus = policyData.getPolicyStatus(); - this.gocServerScope = policyData.getGocServerScope(); - this.supressionType = policyData.getSupressionType(); - - //MicroSerice - this.serviceType = policyData.getServiceType(); - this.uuid = policyData.getUuid(); - this.location = policyData.getLocation(); - this.priority = policyData.getPriority(); - this.msLocation = policyData.getMsLocation(); - - //BRMS Policies - this.ruleName = policyData.getRuleName(); - this.brmsParamBody = policyData.getBrmsParamBody(); - this.brmsController = policyData.getBrmsController(); - this.brmsDependency = policyData.getBrmsDependency(); - this.ruleData = policyData.getRuleData(); - this.ruleListData = policyData.getRuleListData(); - this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams(); - - //ClosedLoop - this.clearTimeOut = policyData.getClearTimeOut(); - this.trapMaxAge = policyData.getTrapMaxAge(); - this.verificationclearTimeOut = policyData.getVerificationclearTimeOut(); - this.dynamicLayoutMap = policyData.getDynamicLayoutMap(); - - //FireWall - this.fwPolicyType = policyData.getFwPolicyType(); - this.fwattributes = policyData.getFwattributes(); - this.parentForChild = policyData.getParentForChild(); - this.securityZone = policyData.getSecurityZone(); - - //Action & Decision - this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId(); - this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes(); - this.dynamicSettingsMap = policyData.getDynamicSettingsMap(); - this.dropDownMap = policyData.getDropDownMap(); - this.actionPerformer = policyData.getActionPerformer(); - this.actionAttribute = policyData.getActionAttribute(); - this.dynamicRuleAlgorithmLabels = policyData.getDynamicRuleAlgorithmLabels(); - this.dynamicRuleAlgorithmCombo = policyData.getDynamicRuleAlgorithmCombo(); - this.dynamicRuleAlgorithmField1 = policyData.getDynamicRuleAlgorithmField1(); - this.dynamicRuleAlgorithmField2 = policyData.getDynamicRuleAlgorithmField2(); - this.dynamicVariableList = policyData.getDynamicVariableList(); - this.dataTypeList = policyData.getDataTypeList(); - this.actionAttributeValue = policyData.getActionAttributeValue(); - this.ruleProvider = policyData.getRuleProvider(); - this.actionBody = policyData.getActionBody(); - this.actionDictHeader = policyData.getActionDictHeader(); - this.actionDictType = policyData.getActionDictType(); - this.actionDictUrl = policyData.getActionDictUrl(); - this.actionDictMethod = policyData.getActionDictMethod(); - this.yamlparams = policyData.getYamlparams(); - } - - public String getScope() { - return scope; - } - public void setScope(String scope) { - this.scope = scope; - } - public String getPolicyType() { - return policyType; - } - public void setPolicyType(String policyType) { - this.policyType = policyType; - } - public String getConfigPolicyType() { - return configPolicyType; - } - public void setConfigPolicyType(String configPolicyType) { - this.configPolicyType = configPolicyType; - } - public String getConfigBodyData() { - return configBodyData; - } - - public void setConfigBodyData(String configBodyData) { - this.configBodyData = configBodyData; - } - public String getPolicyName() { - return policyName; - } - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - public String getPolicyDescription() { - return policyDescription; - } - public void setPolicyDescription(String policyDescription) { - this.policyDescription = policyDescription; - } - public String getOnapName() { - return onapName; - } - public void setOnapName(String onapName) { - this.onapName = onapName; - } - public String getConfigName() { - return configName; - } - public void setConfigName(String configName) { - this.configName = configName; - } - public String getConfigType() { - return configType; - } - public void setConfigType(String configType) { - this.configType = configType; - } - public String getJsonBody() { - return jsonBody; - } - public void setJsonBody(String jsonBody) { - this.jsonBody = jsonBody; - } - public Map<?, ?> getServiceTypePolicyName() { - return serviceTypePolicyName; - } - - public void setServiceTypePolicyName(LinkedHashMap<?, ?> serviceTypePolicyName) { - this.serviceTypePolicyName = serviceTypePolicyName; - } - - public Map<?, ?> getVerticaMetrics() { - return verticaMetrics; - } - - public void setVerticaMetrics(LinkedHashMap<?, ?> verticaMetrics) { - this.verticaMetrics = verticaMetrics; - } - - public Map<?, ?> getDescription() { - return description; - } - - public void setDescription(Map<?, ?> description) { - this.description = description; - } - - public Map<?, ?> getAttributeFields() { - return attributeFields; - } - - public void setAttributeFields(LinkedHashMap<?, ?> attributeFields) { - this.attributeFields = attributeFields; - } - public String getPolicyScope() { - return policyScope; - } - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - public String getProviderComboBox() { - return providerComboBox; - } - public void setProviderComboBox(String providerComboBox) { - this.providerComboBox = providerComboBox; - } - public String getRiskType() { - return riskType; - } - public void setRiskType(String riskType) { - this.riskType = riskType; - } - public String getRiskLevel() { - return riskLevel; - } - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - public String getGuard() { - return guard; - } - public void setGuard(String guard) { - this.guard = guard; - } - public String getTtlDate() { - return ttlDate; - } - public void setTtlDate(String ttlDate) { - this.ttlDate = ttlDate; - } - public Map<String, String> getMatching() { - return matching; - } - public void setMatching(Map<String, String> matching) { - this.matching = matching; - } - public List<Object> getTriggerSignatures() { - return triggerSignatures; - } - public void setTriggerSignatures(ArrayList<Object> triggerSignatures) { - this.triggerSignatures = triggerSignatures; - } - public List<Object> getSymptomSignatures() { - return symptomSignatures; - } - public void setSymptomSignatures(ArrayList<Object> symptomSignatures) { - this.symptomSignatures = symptomSignatures; - } - public String getLogicalConnector() { - return logicalConnector; - } - public void setLogicalConnector(String logicalConnector) { - this.logicalConnector = logicalConnector; - } - public String getPolicyStatus() { - return policyStatus; - } - public void setPolicyStatus(String policyStatus) { - this.policyStatus = policyStatus; - } - public String getGocServerScope() { - return gocServerScope; - } - public void setGocServerScope(String gocServerScope) { - this.gocServerScope = gocServerScope; - } - public String getSupressionType() { - return supressionType; - } - public void setSupressionType(String supressionType) { - this.supressionType = supressionType; - } - public String getServiceType() { - return serviceType; - } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getLocation() { - return location; - } - public void setLocation(String location) { - this.location = location; - } - public String getPriority() { - return priority; - } - public void setPriority(String priority) { - this.priority = priority; - } - public String getMsLocation() { - return msLocation; - } - public void setMsLocation(String msLocation) { - this.msLocation = msLocation; - } - public String getRuleName() { - return ruleName; - } - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - public Map<String, String> getBrmsParamBody() { - return brmsParamBody; - } - public void setBrmsParamBody(Map<String, String> brmsParamBody) { - this.brmsParamBody = brmsParamBody; - } - public String getBrmsController() { - return brmsController; - } - public void setBrmsController(String brmsController) { - this.brmsController = brmsController; - } - public List<String> getBrmsDependency() { - return brmsDependency; - } - public void setBrmsDependency(List<String> brmsDependency) { - this.brmsDependency = brmsDependency; - } - public Map<?, ?> getRuleData() { - return ruleData; - } - public void setRuleData(LinkedHashMap<?, ?> ruleData) { - this.ruleData = ruleData; - } - public Map<?, ?> getRuleListData() { - return ruleListData; - } - public void setRuleListData(LinkedHashMap<?, ?> ruleListData) { - this.ruleListData = ruleListData; - } - public Map<String, String> getDrlRuleAndUIParams() { - return drlRuleAndUIParams; - } - public void setDrlRuleAndUIParams(Map<String, String> drlRuleAndUIParams) { - this.drlRuleAndUIParams = drlRuleAndUIParams; - } - public String getClearTimeOut() { - return clearTimeOut; - } - public void setClearTimeOut(String clearTimeOut) { - this.clearTimeOut = clearTimeOut; - } - public String getTrapMaxAge() { - return trapMaxAge; - } - public void setTrapMaxAge(String trapMaxAge) { - this.trapMaxAge = trapMaxAge; - } - public String getVerificationclearTimeOut() { - return verificationclearTimeOut; - } - public void setVerificationclearTimeOut(String verificationclearTimeOut) { - this.verificationclearTimeOut = verificationclearTimeOut; - } - public Map<String, String> getDynamicLayoutMap() { - return dynamicLayoutMap; - } - public void setDynamicLayoutMap(Map<String, String> dynamicLayoutMap) { - this.dynamicLayoutMap = dynamicLayoutMap; - } - public String getFwPolicyType() { - return fwPolicyType; - } - public void setFwPolicyType(String fwPolicyType) { - this.fwPolicyType = fwPolicyType; - } - public List<Object> getFwattributes() { - return fwattributes; - } - public void setFwattributes(ArrayList<Object> fwattributes) { - this.fwattributes = fwattributes; - } - public String getParentForChild() { - return parentForChild; - } - public void setParentForChild(String parentForChild) { - this.parentForChild = parentForChild; - } - public String getSecurityZone() { - return securityZone; - } - public void setSecurityZone(String securityZone) { - this.securityZone = securityZone; - } - public String getRuleCombiningAlgId() { - return ruleCombiningAlgId; - } - public void setRuleCombiningAlgId(String ruleCombiningAlgId) { - this.ruleCombiningAlgId = ruleCombiningAlgId; - } - public Map<String, String> getDynamicFieldConfigAttributes() { - return dynamicFieldConfigAttributes; - } - public void setDynamicFieldConfigAttributes(Map<String, String> dynamicFieldConfigAttributes) { - this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; - } - public Map<String, String> getDynamicSettingsMap() { - return dynamicSettingsMap; - } - public void setDynamicSettingsMap(Map<String, String> dynamicSettingsMap) { - this.dynamicSettingsMap = dynamicSettingsMap; - } - public Map<String, String> getDropDownMap() { - return dropDownMap; - } - public void setDropDownMap(Map<String, String> dropDownMap) { - this.dropDownMap = dropDownMap; - } - public String getActionPerformer() { - return actionPerformer; - } - public void setActionPerformer(String actionPerformer) { - this.actionPerformer = actionPerformer; - } - public String getActionAttribute() { - return actionAttribute; - } - public void setActionAttribute(String actionAttribute) { - this.actionAttribute = actionAttribute; - } - public List<String> getDynamicRuleAlgorithmLabels() { - return dynamicRuleAlgorithmLabels; - } - public void setDynamicRuleAlgorithmLabels(List<String> dynamicRuleAlgorithmLabels) { - this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; - } - public List<String> getDynamicRuleAlgorithmCombo() { - return dynamicRuleAlgorithmCombo; - } - public void setDynamicRuleAlgorithmCombo(List<String> dynamicRuleAlgorithmCombo) { - this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; - } - public List<String> getDynamicRuleAlgorithmField1() { - return dynamicRuleAlgorithmField1; - } - public void setDynamicRuleAlgorithmField1(List<String> dynamicRuleAlgorithmField1) { - this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; - } - public List<String> getDynamicRuleAlgorithmField2() { - return dynamicRuleAlgorithmField2; - } - public void setDynamicRuleAlgorithmField2(List<String> dynamicRuleAlgorithmField2) { - this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; - } - public List<Object> getDynamicVariableList() { - return dynamicVariableList; - } - public void setDynamicVariableList(List<Object> dynamicVariableList) { - this.dynamicVariableList = dynamicVariableList; - } - public List<String> getDataTypeList() { - return dataTypeList; - } - public void setDataTypeList(List<String> dataTypeList) { - this.dataTypeList = dataTypeList; - } - public String getActionAttributeValue() { - return actionAttributeValue; - } - public void setActionAttributeValue(String actionAttributeValue) { - this.actionAttributeValue = actionAttributeValue; - } - public String getRuleProvider() { - return ruleProvider; - } - public void setRuleProvider(String ruleProvider) { - this.ruleProvider = ruleProvider; - } - public String getActionBody() { - return actionBody; - } - public void setActionBody(String actionBody) { - this.actionBody = actionBody; - } - public String getActionDictHeader() { - return actionDictHeader; - } - public void setActionDictHeader(String actionDictHeader) { - this.actionDictHeader = actionDictHeader; - } - public String getActionDictType() { - return actionDictType; - } - public void setActionDictType(String actionDictType) { - this.actionDictType = actionDictType; - } - public String getActionDictUrl() { - return actionDictUrl; - } - public void setActionDictUrl(String actionDictUrl) { - this.actionDictUrl = actionDictUrl; - } - public String getActionDictMethod() { - return actionDictMethod; - } - public void setActionDictMethod(String actionDictMethod) { - this.actionDictMethod = actionDictMethod; - } - public YAMLParams getYamlparams() { - return yamlparams; - } - - public void setYamlparams(YAMLParams yamlparams) { - this.yamlparams = yamlparams; - } - - public Object getJsonBodyData() { - return jsonBodyData; - } - - public void setJsonBodyData(Object jsonBodyData) { - this.jsonBodyData = jsonBodyData; - } + //Safe Policy + private String policyScope; + private String providerComboBox; + private String riskType; + private String riskLevel; + private String guard; + private String ttlDate; + private Map<String,String> matching; + + private List<Object> triggerSignatures; + private List<Object> symptomSignatures; + private String logicalConnector; + private String policyStatus; + public String gocServerScope; + private String supressionType; + + //MicroSerice + private String serviceType; + private String uuid; + private String location; + private String priority; + private String msLocation; + + //BRMS Policies + private String ruleName; + private Map<String,String> brmsParamBody; + private String brmsController; + private List<String> brmsDependency; + private LinkedHashMap<?, ?> ruleData; + private LinkedHashMap<?,?> ruleListData; + private Map<String,String> drlRuleAndUIParams; + + //ClosedLoop + private String clearTimeOut; + private String trapMaxAge; + private String verificationclearTimeOut; + public Map<String , String> dynamicLayoutMap; + + //FireWall + private String fwPolicyType; + private List<Object> fwattributes; + private String parentForChild; + private String securityZone; + + //Action & Decision + private String ruleCombiningAlgId; + private Map<String,String> dynamicFieldConfigAttributes; + private Map<String,String> dynamicSettingsMap; + private Map<String,String> dropDownMap; + private String actionPerformer; + private String actionAttribute; + private List<String> dynamicRuleAlgorithmLabels; + private List<String> dynamicRuleAlgorithmCombo; + private List<String> dynamicRuleAlgorithmField1; + private List<String> dynamicRuleAlgorithmField2; + private List<Object> dynamicVariableList; + private List<String> dataTypeList; + private String actionAttributeValue; + private String ruleProvider; + private String actionBody; + private String actionDictHeader; + private String actionDictType; + private String actionDictUrl; + private String actionDictMethod; + private YAMLParams yamlparams; + + public PolicyElasticData(PolicyRestAdapter policyData) { + this.scope = policyData.getDomainDir(); + this.policyType = policyData.getPolicyType(); + this.configPolicyType = policyData.getConfigPolicyType(); + this.configBodyData = policyData.getConfigBodyData(); + this.policyName = policyData.getNewFileName(); + this.policyDescription = policyData.getPolicyDescription(); + this.onapName = policyData.getOnapName(); + this.configName = policyData.getConfigName(); + this.configType = policyData.getConfigType(); + this.jsonBody = policyData.getJsonBody(); + if(configPolicyType.startsWith("ClosedLoop")){ + this.jsonBodyData = jsonBody; + }else{ + this.jsonBodyData = policyData.getJsonBodyData(); + } + + this.serviceTypePolicyName = policyData.getServiceTypePolicyName(); + this.verticaMetrics = policyData.getVerticaMetrics(); + this.description = policyData.getDescription(); + this.attributeFields = policyData.getAttributeFields(); + + //Safe Policy + this.policyScope = policyData.getPolicyScope(); + this.providerComboBox = policyData.getProviderComboBox(); + this.riskType = policyData.getRiskType(); + this.riskLevel = policyData.getRiskLevel(); + this.guard = policyData.getGuard(); + this.ttlDate = policyData.getTtlDate(); + this.matching = policyData.getMatching(); + + this.triggerSignatures = policyData.getTriggerSignatures(); + this.symptomSignatures = policyData.getSymptomSignatures(); + this.logicalConnector = policyData.getLogicalConnector(); + this.policyStatus = policyData.getPolicyStatus(); + this.gocServerScope = policyData.getGocServerScope(); + this.supressionType = policyData.getSupressionType(); + + //MicroSerice + this.serviceType = policyData.getServiceType(); + this.uuid = policyData.getUuid(); + this.location = policyData.getLocation(); + this.priority = policyData.getPriority(); + this.msLocation = policyData.getMsLocation(); + + //BRMS Policies + this.ruleName = policyData.getRuleName(); + this.brmsParamBody = policyData.getBrmsParamBody(); + this.brmsController = policyData.getBrmsController(); + this.brmsDependency = policyData.getBrmsDependency(); + this.ruleData = policyData.getRuleData(); + this.ruleListData = policyData.getRuleListData(); + this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams(); + + //ClosedLoop + this.clearTimeOut = policyData.getClearTimeOut(); + this.trapMaxAge = policyData.getTrapMaxAge(); + this.verificationclearTimeOut = policyData.getVerificationclearTimeOut(); + this.dynamicLayoutMap = policyData.getDynamicLayoutMap(); + + //FireWall + this.fwPolicyType = policyData.getFwPolicyType(); + this.fwattributes = policyData.getFwattributes(); + this.parentForChild = policyData.getParentForChild(); + this.securityZone = policyData.getSecurityZone(); + + //Action & Decision + this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId(); + this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes(); + this.dynamicSettingsMap = policyData.getDynamicSettingsMap(); + this.dropDownMap = policyData.getDropDownMap(); + this.actionPerformer = policyData.getActionPerformer(); + this.actionAttribute = policyData.getActionAttribute(); + this.dynamicRuleAlgorithmLabels = policyData.getDynamicRuleAlgorithmLabels(); + this.dynamicRuleAlgorithmCombo = policyData.getDynamicRuleAlgorithmCombo(); + this.dynamicRuleAlgorithmField1 = policyData.getDynamicRuleAlgorithmField1(); + this.dynamicRuleAlgorithmField2 = policyData.getDynamicRuleAlgorithmField2(); + this.dynamicVariableList = policyData.getDynamicVariableList(); + this.dataTypeList = policyData.getDataTypeList(); + this.actionAttributeValue = policyData.getActionAttributeValue(); + this.ruleProvider = policyData.getRuleProvider(); + this.actionBody = policyData.getActionBody(); + this.actionDictHeader = policyData.getActionDictHeader(); + this.actionDictType = policyData.getActionDictType(); + this.actionDictUrl = policyData.getActionDictUrl(); + this.actionDictMethod = policyData.getActionDictMethod(); + this.yamlparams = policyData.getYamlparams(); + } + + public String getScope() { + return scope; + } + public void setScope(String scope) { + this.scope = scope; + } + public String getPolicyType() { + return policyType; + } + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + public String getConfigPolicyType() { + return configPolicyType; + } + public void setConfigPolicyType(String configPolicyType) { + this.configPolicyType = configPolicyType; + } + public String getConfigBodyData() { + return configBodyData; + } + + public void setConfigBodyData(String configBodyData) { + this.configBodyData = configBodyData; + } + public String getPolicyName() { + return policyName; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public String getPolicyDescription() { + return policyDescription; + } + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + public String getOnapName() { + return onapName; + } + public void setOnapName(String onapName) { + this.onapName = onapName; + } + public String getConfigName() { + return configName; + } + public void setConfigName(String configName) { + this.configName = configName; + } + public String getConfigType() { + return configType; + } + public void setConfigType(String configType) { + this.configType = configType; + } + public String getJsonBody() { + return jsonBody; + } + public void setJsonBody(String jsonBody) { + this.jsonBody = jsonBody; + } + public Map<?, ?> getServiceTypePolicyName() { + return serviceTypePolicyName; + } + + public void setServiceTypePolicyName(LinkedHashMap<?, ?> serviceTypePolicyName) { + this.serviceTypePolicyName = serviceTypePolicyName; + } + + public Map<?, ?> getVerticaMetrics() { + return verticaMetrics; + } + + public void setVerticaMetrics(LinkedHashMap<?, ?> verticaMetrics) { + this.verticaMetrics = verticaMetrics; + } + + public Map<?, ?> getDescription() { + return description; + } + + public void setDescription(Map<?, ?> description) { + this.description = description; + } + + public Map<?, ?> getAttributeFields() { + return attributeFields; + } + + public void setAttributeFields(LinkedHashMap<?, ?> attributeFields) { + this.attributeFields = attributeFields; + } + public String getPolicyScope() { + return policyScope; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + public String getProviderComboBox() { + return providerComboBox; + } + public void setProviderComboBox(String providerComboBox) { + this.providerComboBox = providerComboBox; + } + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public String getRiskLevel() { + return riskLevel; + } + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + public String getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getTtlDate() { + return ttlDate; + } + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } + public Map<String, String> getMatching() { + return matching; + } + public void setMatching(Map<String, String> matching) { + this.matching = matching; + } + public List<Object> getTriggerSignatures() { + return triggerSignatures; + } + public void setTriggerSignatures(ArrayList<Object> triggerSignatures) { + this.triggerSignatures = triggerSignatures; + } + public List<Object> getSymptomSignatures() { + return symptomSignatures; + } + public void setSymptomSignatures(ArrayList<Object> symptomSignatures) { + this.symptomSignatures = symptomSignatures; + } + public String getLogicalConnector() { + return logicalConnector; + } + public void setLogicalConnector(String logicalConnector) { + this.logicalConnector = logicalConnector; + } + public String getPolicyStatus() { + return policyStatus; + } + public void setPolicyStatus(String policyStatus) { + this.policyStatus = policyStatus; + } + public String getGocServerScope() { + return gocServerScope; + } + public void setGocServerScope(String gocServerScope) { + this.gocServerScope = gocServerScope; + } + public String getSupressionType() { + return supressionType; + } + public void setSupressionType(String supressionType) { + this.supressionType = supressionType; + } + public String getServiceType() { + return serviceType; + } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getLocation() { + return location; + } + public void setLocation(String location) { + this.location = location; + } + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public String getMsLocation() { + return msLocation; + } + public void setMsLocation(String msLocation) { + this.msLocation = msLocation; + } + public String getRuleName() { + return ruleName; + } + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + public Map<String, String> getBrmsParamBody() { + return brmsParamBody; + } + public void setBrmsParamBody(Map<String, String> brmsParamBody) { + this.brmsParamBody = brmsParamBody; + } + public String getBrmsController() { + return brmsController; + } + public void setBrmsController(String brmsController) { + this.brmsController = brmsController; + } + public List<String> getBrmsDependency() { + return brmsDependency; + } + public void setBrmsDependency(List<String> brmsDependency) { + this.brmsDependency = brmsDependency; + } + public Map<?, ?> getRuleData() { + return ruleData; + } + public void setRuleData(LinkedHashMap<?, ?> ruleData) { + this.ruleData = ruleData; + } + public Map<?, ?> getRuleListData() { + return ruleListData; + } + public void setRuleListData(LinkedHashMap<?, ?> ruleListData) { + this.ruleListData = ruleListData; + } + public Map<String, String> getDrlRuleAndUIParams() { + return drlRuleAndUIParams; + } + public void setDrlRuleAndUIParams(Map<String, String> drlRuleAndUIParams) { + this.drlRuleAndUIParams = drlRuleAndUIParams; + } + public String getClearTimeOut() { + return clearTimeOut; + } + public void setClearTimeOut(String clearTimeOut) { + this.clearTimeOut = clearTimeOut; + } + public String getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(String trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } + public String getVerificationclearTimeOut() { + return verificationclearTimeOut; + } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { + this.verificationclearTimeOut = verificationclearTimeOut; + } + public Map<String, String> getDynamicLayoutMap() { + return dynamicLayoutMap; + } + public void setDynamicLayoutMap(Map<String, String> dynamicLayoutMap) { + this.dynamicLayoutMap = dynamicLayoutMap; + } + public String getFwPolicyType() { + return fwPolicyType; + } + public void setFwPolicyType(String fwPolicyType) { + this.fwPolicyType = fwPolicyType; + } + public List<Object> getFwattributes() { + return fwattributes; + } + public void setFwattributes(ArrayList<Object> fwattributes) { + this.fwattributes = fwattributes; + } + public String getParentForChild() { + return parentForChild; + } + public void setParentForChild(String parentForChild) { + this.parentForChild = parentForChild; + } + public String getSecurityZone() { + return securityZone; + } + public void setSecurityZone(String securityZone) { + this.securityZone = securityZone; + } + public String getRuleCombiningAlgId() { + return ruleCombiningAlgId; + } + public void setRuleCombiningAlgId(String ruleCombiningAlgId) { + this.ruleCombiningAlgId = ruleCombiningAlgId; + } + public Map<String, String> getDynamicFieldConfigAttributes() { + return dynamicFieldConfigAttributes; + } + public void setDynamicFieldConfigAttributes(Map<String, String> dynamicFieldConfigAttributes) { + this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; + } + public Map<String, String> getDynamicSettingsMap() { + return dynamicSettingsMap; + } + public void setDynamicSettingsMap(Map<String, String> dynamicSettingsMap) { + this.dynamicSettingsMap = dynamicSettingsMap; + } + public Map<String, String> getDropDownMap() { + return dropDownMap; + } + public void setDropDownMap(Map<String, String> dropDownMap) { + this.dropDownMap = dropDownMap; + } + public String getActionPerformer() { + return actionPerformer; + } + public void setActionPerformer(String actionPerformer) { + this.actionPerformer = actionPerformer; + } + public String getActionAttribute() { + return actionAttribute; + } + public void setActionAttribute(String actionAttribute) { + this.actionAttribute = actionAttribute; + } + public List<String> getDynamicRuleAlgorithmLabels() { + return dynamicRuleAlgorithmLabels; + } + public void setDynamicRuleAlgorithmLabels(List<String> dynamicRuleAlgorithmLabels) { + this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; + } + public List<String> getDynamicRuleAlgorithmCombo() { + return dynamicRuleAlgorithmCombo; + } + public void setDynamicRuleAlgorithmCombo(List<String> dynamicRuleAlgorithmCombo) { + this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; + } + public List<String> getDynamicRuleAlgorithmField1() { + return dynamicRuleAlgorithmField1; + } + public void setDynamicRuleAlgorithmField1(List<String> dynamicRuleAlgorithmField1) { + this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; + } + public List<String> getDynamicRuleAlgorithmField2() { + return dynamicRuleAlgorithmField2; + } + public void setDynamicRuleAlgorithmField2(List<String> dynamicRuleAlgorithmField2) { + this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; + } + public List<Object> getDynamicVariableList() { + return dynamicVariableList; + } + public void setDynamicVariableList(List<Object> dynamicVariableList) { + this.dynamicVariableList = dynamicVariableList; + } + public List<String> getDataTypeList() { + return dataTypeList; + } + public void setDataTypeList(List<String> dataTypeList) { + this.dataTypeList = dataTypeList; + } + public String getActionAttributeValue() { + return actionAttributeValue; + } + public void setActionAttributeValue(String actionAttributeValue) { + this.actionAttributeValue = actionAttributeValue; + } + public String getRuleProvider() { + return ruleProvider; + } + public void setRuleProvider(String ruleProvider) { + this.ruleProvider = ruleProvider; + } + public String getActionBody() { + return actionBody; + } + public void setActionBody(String actionBody) { + this.actionBody = actionBody; + } + public String getActionDictHeader() { + return actionDictHeader; + } + public void setActionDictHeader(String actionDictHeader) { + this.actionDictHeader = actionDictHeader; + } + public String getActionDictType() { + return actionDictType; + } + public void setActionDictType(String actionDictType) { + this.actionDictType = actionDictType; + } + public String getActionDictUrl() { + return actionDictUrl; + } + public void setActionDictUrl(String actionDictUrl) { + this.actionDictUrl = actionDictUrl; + } + public String getActionDictMethod() { + return actionDictMethod; + } + public void setActionDictMethod(String actionDictMethod) { + this.actionDictMethod = actionDictMethod; + } + public YAMLParams getYamlparams() { + return yamlparams; + } + + public void setYamlparams(YAMLParams yamlparams) { + this.yamlparams = yamlparams; + } + + public Object getJsonBodyData() { + return jsonBodyData; + } + + public void setJsonBodyData(Object jsonBodyData) { + this.jsonBodyData = jsonBodyData; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java index a8320093e..50965bd2b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java @@ -77,388 +77,388 @@ import io.searchbox.client.JestResult; @RequestMapping({"/"}) public class PolicyElasticSearchController{ - private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); - enum Mode{ - attribute, onapName, actionPolicy, brmsParam, pepOptions, - clSite, clService, clVarbind, clVnf, clVSCL, decision, - fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, - psGroupPolicy, safeRisk, safePolicyWarning - } + enum Mode{ + attribute, onapName, actionPolicy, brmsParam, pepOptions, + clSite, clService, clVarbind, clVnf, clVSCL, decision, + fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, + psGroupPolicy, safeRisk, safePolicyWarning + } - protected static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() { - private static final long serialVersionUID = 1L; - }; - - private static CommonClassDao commonClassDao; - private static final String action = "action"; - private static final String config = "config"; - private static final String decision = "decision"; - private static final String pholder = "pholder"; - private static final String jsonBodyData = "jsonBodyData"; - private static final String success = "success"; + protected static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() { + private static final long serialVersionUID = 1L; + }; - @Autowired - public PolicyElasticSearchController(CommonClassDao commonClassDao) { - PolicyElasticSearchController.commonClassDao = commonClassDao; - } + private static CommonClassDao commonClassDao; + private static final String action = "action"; + private static final String config = "config"; + private static final String decision = "decision"; + private static final String pholder = "pholder"; + private static final String jsonBodyData = "jsonBodyData"; + private static final String success = "success"; - public PolicyElasticSearchController() { - super(); - } + @Autowired + public PolicyElasticSearchController(CommonClassDao commonClassDao) { + PolicyElasticSearchController.commonClassDao = commonClassDao; + } - public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { - if (type == null || type.isEmpty()){ - return PolicyIndexType.all; - } - return PolicyIndexType.valueOf(type); - } + public PolicyElasticSearchController() { + super(); + } - public boolean updateElk(PolicyRestAdapter policyData) { - boolean success = true; - try { - success = ElkConnector.singleton.update(policyData); - if (!success) { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName()); - } - } else { - if (LOGGER.isInfoEnabled()) { - LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName()); - } - } - } catch (Exception e) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); - success = false; - } - return success; - } + public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { + if (type == null || type.isEmpty()){ + return PolicyIndexType.all; + } + return PolicyIndexType.valueOf(type); + } - public boolean deleteElk(PolicyRestAdapter policyData) { - boolean success = true; - try { - success = ElkConnector.singleton.delete(policyData); - if (!success) { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName()); - } - } else { - if (LOGGER.isInfoEnabled()) { - LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName()); - } - } - } catch (Exception e) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); - success = false; - } - return success; - } + public boolean updateElk(PolicyRestAdapter policyData) { + boolean success = true; + try { + success = ElkConnector.singleton.update(policyData); + if (!success) { + if (LOGGER.isWarnEnabled()) { + LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName()); + } + } else { + if (LOGGER.isInfoEnabled()) { + LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName()); + } + } + } catch (Exception e) { + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); + success = false; + } + return success; + } - - @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) - public void searchPolicy(HttpServletRequest request, HttpServletResponse response) { - try{ - String message=""; - boolean result = false; - boolean policyResult = false; - boolean validationCheck = true; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - PolicyRestAdapter policyData = new PolicyRestAdapter(); - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - Map<String, String> searchKeyValue = new HashMap<>(); - List<String> policyList = new ArrayList<>(); - if(request.getParameter("policyName") != null){ - String policyName = request.getParameter("policyName"); - policyData.setNewFileName(policyName); - if("delete".equalsIgnoreCase(request.getParameter(action))){ - result = controller.deleteElk(policyData); - }else{ - result = controller.updateElk(policyData); - } - } - if("search".equalsIgnoreCase(request.getParameter(action))){ - try { - JsonNode root = mapper.readTree(request.getReader()); - SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class); + public boolean deleteElk(PolicyRestAdapter policyData) { + boolean success = true; + try { + success = ElkConnector.singleton.delete(policyData); + if (!success) { + if (LOGGER.isWarnEnabled()) { + LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName()); + } + } else { + if (LOGGER.isInfoEnabled()) { + LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName()); + } + } + } catch (Exception e) { + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); + success = false; + } + return success; + } - String policyType = searchData.getPolicyType(); - - String searchText = searchData.getQuery(); - String descriptivevalue = searchData.getDescriptiveScope(); - if(descriptivevalue != null){ - DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); - if(dsSearch != null){ - String[] descriptiveList = dsSearch.getSearch().split("AND"); - for(String keyValue : descriptiveList){ - String[] entry = keyValue.split(":"); - if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){ - if(!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)){ - message = "The Descriptive Scope Dictionary value contains space and it is invalid for Search : "+entry[1]; - validationCheck = false; - } - searchKeyValue.put(jsonBodyData, "*" +entry[1] +"*"); - }else{ - searchText = entry[1]; - } - } - } - } - - if(!PolicyUtils.policySpecialCharValidator(searchText).contains(success)){ - message = "The Search value contains space and it is invalid for Search : "+searchText; - validationCheck = false; - } - - if(searchData.getClosedLooppolicyType() != null){ - String closedLoopType; - if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){ - closedLoopType = "ClosedLoop_Fault"; - }else{ - closedLoopType = "ClosedLoop_PM"; - } - searchKeyValue.put("configPolicyType", closedLoopType); - } - if(searchData.getOnapName() != null){ - searchKeyValue.put("onapName", searchData.getOnapName()); - } - if(searchData.getD2Service() != null){ - String d2Service = searchData.getD2Service().trim(); - if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){ - d2Service = "trinity"; - }else if("vUSP".equalsIgnoreCase(d2Service)){ - d2Service = "vUSP"; - }else if("MCR".equalsIgnoreCase(d2Service)){ - d2Service = "mcr"; - }else if("Gamma".equalsIgnoreCase(d2Service)){ - d2Service = "gamma"; - }else if("vDNS".equalsIgnoreCase(d2Service)){ - d2Service = "vDNS"; - } - searchKeyValue.put("jsonBodyData."+d2Service+"", "true"); - } - if(searchData.getVnfType() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*"); - } - if(searchData.getPolicyStatus() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*"); - } - if(searchData.getVproAction() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*"); - } - if(searchData.getServiceType() != null){ - searchKeyValue.put("serviceType", searchData.getServiceType()); - } - if(searchData.getBindTextSearch() != null){ - searchKeyValue.put(searchData.getBindTextSearch(), searchText); - searchText = null; - } - PolicyIndexType type = null; - if(policyType != null){ - if(action.equalsIgnoreCase(policyType)){ - type = ElkConnector.PolicyIndexType.action; - }else if(decision.equalsIgnoreCase(policyType)){ - type = ElkConnector.PolicyIndexType.decision; - }else if(config.equalsIgnoreCase(policyType)){ - type = ElkConnector.PolicyIndexType.config; - }else if("closedloop".equalsIgnoreCase(policyType)){ - type = ElkConnector.PolicyIndexType.closedloop; - }else{ - type = ElkConnector.PolicyIndexType.all; - } - }else{ - type = ElkConnector.PolicyIndexType.all; - } - if(validationCheck){ - JestResult policyResultList = controller.search(type, searchText, searchKeyValue); - if(policyResultList.isSucceeded()){ - result = true; - policyResult = true; - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ - String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); - policyList.add(policyName); - } - }else{ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); - } - } - }catch(Exception e){ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e); - } - } - if(validationCheck){ - if(result){ - message = "Elastic Server Transaction is success"; - }else{ - message = "Elastic Server Transaction is failed, please check the logs"; - } - } - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message)); - JSONObject j = new JSONObject(msg); - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader(success, success); - if(policyResult){ - JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); - response.getWriter().write(k.toString()); - }else{ - response.getWriter().write(j.toString()); - } - }catch(Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); - LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage(),e); - } - } - - @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException { - try{ - PolicyIndexType config = PolicyIndexType.config; - PolicyIndexType closedloop = PolicyIndexType.closedloop; - PolicyIndexType action = PolicyIndexType.action; - PolicyIndexType decision = PolicyIndexType.decision; - PolicyIndexType all = PolicyIndexType.all; - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String dictionaryType = root.get("type").textValue(); - Mode mode = Mode.valueOf(dictionaryType); - String value; - List<String> policyList = new ArrayList<>(); - switch (mode){ - case attribute : - Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class); - value = attributedata.getXacmlId(); - policyList = searchElkDatabase(all, pholder,value); - break; - case onapName : - OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class); - value = onapName.getOnapName(); - policyList = searchElkDatabase(all, "onapName",value); - break; - case actionPolicy : - ActionPolicyDict actionPolicyDict = mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); - value = actionPolicyDict.getAttributeName(); - policyList = searchElkDatabase(action, "actionAttributeValue",value); - break; - case brmsParam : - BRMSParamTemplate bRMSParamTemplate = mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); - value = bRMSParamTemplate.getRuleName(); - policyList = searchElkDatabase(config, "ruleName",value); - break; - case pepOptions : - PEPOptions pEPOptions = mapper.readValue(root.get("data").toString(), PEPOptions.class); - value = pEPOptions.getPepName(); - policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value); - break; - case clSite : - ClosedLoopSite closedLoopSite = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); - value = closedLoopSite.getSiteName(); - policyList = searchElkDatabase(closedloop,"siteNames",value); - break; - case clService : - ClosedLoopD2Services closedLoopD2Services = mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); - value = closedLoopD2Services.getServiceName(); - policyList = searchElkDatabase(closedloop, pholder,value); - break; - case clVarbind : - VarbindDictionary varbindDictionary = mapper.readValue(root.get("data").toString(), VarbindDictionary.class); - value = varbindDictionary.getVarbindName(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case clVnf : - VNFType vNFType = mapper.readValue(root.get("data").toString(), VNFType.class); - value = vNFType.getVnftype(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case clVSCL : - VSCLAction vsclAction = mapper.readValue(root.get("data").toString(), VSCLAction.class); - value = vsclAction.getVsclaction(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case decision : - DecisionSettings decisionSettings = mapper.readValue(root.get("data").toString(), DecisionSettings.class); - value = decisionSettings.getXacmlId(); - policyList = searchElkDatabase(decision,pholder,value); - break; - case fwTerm : - TermList term = mapper.readValue(root.get("data").toString(), TermList.class); - value = term.getTermName(); - policyList = searchElkDatabase(config, pholder,value); - break; - case msDCAEUUID : - DCAEuuid dcaeUUID = mapper.readValue(root.get("data").toString(), DCAEuuid.class); - value = dcaeUUID.getName(); - policyList = searchElkDatabase(config, "uuid",value); - break; - case msLocation : - MicroServiceLocation mslocation = mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); - value = mslocation.getName(); - policyList = searchElkDatabase(config, "location",value); - break; - case msModels : - MicroServiceModels msModels = mapper.readValue(root.get("data").toString(), MicroServiceModels.class); - value = msModels.getModelName(); - policyList = searchElkDatabase(config, "serviceType",value); - break; - case psGroupPolicy : - GroupPolicyScopeList groupPoilicy = mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); - value = groupPoilicy.getGroupName(); - policyList = searchElkDatabase(config, pholder,value); - break; - case safeRisk : - RiskType riskType= mapper.readValue(root.get("data").toString(), RiskType.class); - value = riskType.getRiskName(); - policyList = searchElkDatabase(config, "riskType",value); - break; - case safePolicyWarning : - SafePolicyWarning safePolicy = mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); - value = safePolicy.getName(); - policyList = searchElkDatabase(config, pholder,value); - break; - default: - } - - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader(success, success); - JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); - response.getWriter().write(k.toString()); - }catch(Exception e){ - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); - } - return null; - } - //Search the Elk database - public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){ - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - Map<String, String> searchKeyValue = new HashMap<>(); - if(!pholder.equals(key)){ - searchKeyValue.put(key, value); - } - - List<String> policyList = new ArrayList<>(); - JestResult policyResultList = controller.search(type, value, searchKeyValue); - if(policyResultList.isSucceeded()){ - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ - String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); - policyList.add(policyName); - } - }else{ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); - } - return policyList; - } - - public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) { - return ElkConnector.singleton.search(type, text, searchKeyValue); - } - + @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) + public void searchPolicy(HttpServletRequest request, HttpServletResponse response) { + try{ + String message=""; + boolean result = false; + boolean policyResult = false; + boolean validationCheck = true; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + PolicyRestAdapter policyData = new PolicyRestAdapter(); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + Map<String, String> searchKeyValue = new HashMap<>(); + List<String> policyList = new ArrayList<>(); + if(request.getParameter("policyName") != null){ + String policyName = request.getParameter("policyName"); + policyData.setNewFileName(policyName); + if("delete".equalsIgnoreCase(request.getParameter(action))){ + result = controller.deleteElk(policyData); + }else{ + result = controller.updateElk(policyData); + } + } + if("search".equalsIgnoreCase(request.getParameter(action))){ + try { + JsonNode root = mapper.readTree(request.getReader()); + SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class); + + String policyType = searchData.getPolicyType(); + + String searchText = searchData.getQuery(); + String descriptivevalue = searchData.getDescriptiveScope(); + if(descriptivevalue != null){ + DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); + if(dsSearch != null){ + String[] descriptiveList = dsSearch.getSearch().split("AND"); + for(String keyValue : descriptiveList){ + String[] entry = keyValue.split(":"); + if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){ + if(!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)){ + message = "The Descriptive Scope Dictionary value contains space and it is invalid for Search : "+entry[1]; + validationCheck = false; + } + searchKeyValue.put(jsonBodyData, "*" +entry[1] +"*"); + }else{ + searchText = entry[1]; + } + } + } + } + + if(!PolicyUtils.policySpecialCharValidator(searchText).contains(success)){ + message = "The Search value contains space and it is invalid for Search : "+searchText; + validationCheck = false; + } + + if(searchData.getClosedLooppolicyType() != null){ + String closedLoopType; + if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){ + closedLoopType = "ClosedLoop_Fault"; + }else{ + closedLoopType = "ClosedLoop_PM"; + } + searchKeyValue.put("configPolicyType", closedLoopType); + } + if(searchData.getOnapName() != null){ + searchKeyValue.put("onapName", searchData.getOnapName()); + } + if(searchData.getD2Service() != null){ + String d2Service = searchData.getD2Service().trim(); + if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){ + d2Service = "trinity"; + }else if("vUSP".equalsIgnoreCase(d2Service)){ + d2Service = "vUSP"; + }else if("MCR".equalsIgnoreCase(d2Service)){ + d2Service = "mcr"; + }else if("Gamma".equalsIgnoreCase(d2Service)){ + d2Service = "gamma"; + }else if("vDNS".equalsIgnoreCase(d2Service)){ + d2Service = "vDNS"; + } + searchKeyValue.put("jsonBodyData."+d2Service+"", "true"); + } + if(searchData.getVnfType() != null){ + searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*"); + } + if(searchData.getPolicyStatus() != null){ + searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*"); + } + if(searchData.getVproAction() != null){ + searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*"); + } + if(searchData.getServiceType() != null){ + searchKeyValue.put("serviceType", searchData.getServiceType()); + } + if(searchData.getBindTextSearch() != null){ + searchKeyValue.put(searchData.getBindTextSearch(), searchText); + searchText = null; + } + PolicyIndexType type = null; + if(policyType != null){ + if(action.equalsIgnoreCase(policyType)){ + type = ElkConnector.PolicyIndexType.action; + }else if(decision.equalsIgnoreCase(policyType)){ + type = ElkConnector.PolicyIndexType.decision; + }else if(config.equalsIgnoreCase(policyType)){ + type = ElkConnector.PolicyIndexType.config; + }else if("closedloop".equalsIgnoreCase(policyType)){ + type = ElkConnector.PolicyIndexType.closedloop; + }else{ + type = ElkConnector.PolicyIndexType.all; + } + }else{ + type = ElkConnector.PolicyIndexType.all; + } + if(validationCheck){ + JestResult policyResultList = controller.search(type, searchText, searchKeyValue); + if(policyResultList.isSucceeded()){ + result = true; + policyResult = true; + JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); + for(int i =0; i < resultObject.size(); i++){ + String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); + policyList.add(policyName); + } + }else{ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); + } + } + }catch(Exception e){ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e); + } + } + if(validationCheck){ + if(result){ + message = "Elastic Server Transaction is success"; + }else{ + message = "Elastic Server Transaction is failed, please check the logs"; + } + } + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message)); + JSONObject j = new JSONObject(msg); + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader(success, success); + if(policyResult){ + JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); + response.getWriter().write(k.toString()); + }else{ + response.getWriter().write(j.toString()); + } + }catch(Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); + LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage(),e); + } + } + + @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException { + try{ + PolicyIndexType config = PolicyIndexType.config; + PolicyIndexType closedloop = PolicyIndexType.closedloop; + PolicyIndexType action = PolicyIndexType.action; + PolicyIndexType decision = PolicyIndexType.decision; + PolicyIndexType all = PolicyIndexType.all; + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String dictionaryType = root.get("type").textValue(); + Mode mode = Mode.valueOf(dictionaryType); + String value; + List<String> policyList = new ArrayList<>(); + switch (mode){ + case attribute : + Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class); + value = attributedata.getXacmlId(); + policyList = searchElkDatabase(all, pholder,value); + break; + case onapName : + OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class); + value = onapName.getOnapName(); + policyList = searchElkDatabase(all, "onapName",value); + break; + case actionPolicy : + ActionPolicyDict actionPolicyDict = mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + value = actionPolicyDict.getAttributeName(); + policyList = searchElkDatabase(action, "actionAttributeValue",value); + break; + case brmsParam : + BRMSParamTemplate bRMSParamTemplate = mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); + value = bRMSParamTemplate.getRuleName(); + policyList = searchElkDatabase(config, "ruleName",value); + break; + case pepOptions : + PEPOptions pEPOptions = mapper.readValue(root.get("data").toString(), PEPOptions.class); + value = pEPOptions.getPepName(); + policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value); + break; + case clSite : + ClosedLoopSite closedLoopSite = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + value = closedLoopSite.getSiteName(); + policyList = searchElkDatabase(closedloop,"siteNames",value); + break; + case clService : + ClosedLoopD2Services closedLoopD2Services = mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + value = closedLoopD2Services.getServiceName(); + policyList = searchElkDatabase(closedloop, pholder,value); + break; + case clVarbind : + VarbindDictionary varbindDictionary = mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + value = varbindDictionary.getVarbindName(); + policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); + break; + case clVnf : + VNFType vNFType = mapper.readValue(root.get("data").toString(), VNFType.class); + value = vNFType.getVnftype(); + policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); + break; + case clVSCL : + VSCLAction vsclAction = mapper.readValue(root.get("data").toString(), VSCLAction.class); + value = vsclAction.getVsclaction(); + policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); + break; + case decision : + DecisionSettings decisionSettings = mapper.readValue(root.get("data").toString(), DecisionSettings.class); + value = decisionSettings.getXacmlId(); + policyList = searchElkDatabase(decision,pholder,value); + break; + case fwTerm : + TermList term = mapper.readValue(root.get("data").toString(), TermList.class); + value = term.getTermName(); + policyList = searchElkDatabase(config, pholder,value); + break; + case msDCAEUUID : + DCAEuuid dcaeUUID = mapper.readValue(root.get("data").toString(), DCAEuuid.class); + value = dcaeUUID.getName(); + policyList = searchElkDatabase(config, "uuid",value); + break; + case msLocation : + MicroServiceLocation mslocation = mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + value = mslocation.getName(); + policyList = searchElkDatabase(config, "location",value); + break; + case msModels : + MicroServiceModels msModels = mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + value = msModels.getModelName(); + policyList = searchElkDatabase(config, "serviceType",value); + break; + case psGroupPolicy : + GroupPolicyScopeList groupPoilicy = mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + value = groupPoilicy.getGroupName(); + policyList = searchElkDatabase(config, pholder,value); + break; + case safeRisk : + RiskType riskType= mapper.readValue(root.get("data").toString(), RiskType.class); + value = riskType.getRiskName(); + policyList = searchElkDatabase(config, "riskType",value); + break; + case safePolicyWarning : + SafePolicyWarning safePolicy = mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); + value = safePolicy.getName(); + policyList = searchElkDatabase(config, pholder,value); + break; + default: + } + + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader(success, success); + JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); + response.getWriter().write(k.toString()); + }catch(Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(PolicyUtils.CATCH_EXCEPTION); + LOGGER.error(e); + } + return null; + } + + //Search the Elk database + public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){ + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + Map<String, String> searchKeyValue = new HashMap<>(); + if(!pholder.equals(key)){ + searchKeyValue.put(key, value); + } + + List<String> policyList = new ArrayList<>(); + JestResult policyResultList = controller.search(type, value, searchKeyValue); + if(policyResultList.isSucceeded()){ + JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); + for(int i =0; i < resultObject.size(); i++){ + String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); + policyList.add(policyName); + } + }else{ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); + } + return policyList; + } + + public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) { + return ElkConnector.singleton.search(type, text, searchKeyValue); + } + }
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java index 58c89f781..9338cdbbd 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java @@ -20,32 +20,32 @@ package org.onap.policy.pap.xacml.rest.elk.client; public class PolicyLocator { - public final String policyType; - public final String policyName; - public final String owner; - public final String scope; - public final String policyId; - public final String version; - - public PolicyLocator(String policyType, String policyName, - String owner, String scope, String policyId, - String version) { - this.policyType = policyType; - this.policyName= policyName; - this.owner = owner; - this.scope = scope; - this.policyId = policyId; - this.version = version; - } - - public String toString() { - return "[" + - this.owner + "|" + - this.scope + "|" + - this.policyType + "|" + - this.policyName + "|" + - this.policyId + "|" + - "v" + this.version + "|" + "]"; - - } + public final String policyType; + public final String policyName; + public final String owner; + public final String scope; + public final String policyId; + public final String version; + + public PolicyLocator(String policyType, String policyName, + String owner, String scope, String policyId, + String version) { + this.policyType = policyType; + this.policyName= policyName; + this.owner = owner; + this.scope = scope; + this.policyId = policyId; + this.version = version; + } + + public String toString() { + return "[" + + this.owner + "|" + + this.scope + "|" + + this.policyType + "|" + + this.policyName + "|" + + this.policyId + "|" + + "v" + this.version + "|" + "]"; + + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java index db7711039..cc9cc16a0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java @@ -32,66 +32,66 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup; public class APIRequestHandler { - private OnapPDPGroup newGroup; + private OnapPDPGroup newGroup; - public void doGet(HttpServletRequest request, HttpServletResponse response, String apiflag) throws IOException{ - // Request from the API to get Dictionary Items - if ("api".equalsIgnoreCase(apiflag)) { - DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); - dictionaryHandler.doDictionaryAPIGet(request, response); - return; - } - // Request from the API to get the ActiveVersion from the PolicyVersion table - if ("version".equalsIgnoreCase(apiflag)){ - PushPolicyHandler pushHandler = new PushPolicyHandler(); - pushHandler.getActiveVersion(request, response); - return; - } - // Request from the API to get the URI from the gitpath - if ("uri".equalsIgnoreCase(apiflag)){ - PushPolicyHandler pushHandler = new PushPolicyHandler(); - pushHandler.getSelectedURI(request, response); - return; - } - if ("getMetrics".equalsIgnoreCase(apiflag)){ - MetricService.doGetPolicyMetrics(response); - return; - } - } + public void doGet(HttpServletRequest request, HttpServletResponse response, String apiflag) throws IOException{ + // Request from the API to get Dictionary Items + if ("api".equalsIgnoreCase(apiflag)) { + DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); + dictionaryHandler.doDictionaryAPIGet(request, response); + return; + } + // Request from the API to get the ActiveVersion from the PolicyVersion table + if ("version".equalsIgnoreCase(apiflag)){ + PushPolicyHandler pushHandler = new PushPolicyHandler(); + pushHandler.getActiveVersion(request, response); + return; + } + // Request from the API to get the URI from the gitpath + if ("uri".equalsIgnoreCase(apiflag)){ + PushPolicyHandler pushHandler = new PushPolicyHandler(); + pushHandler.getSelectedURI(request, response); + return; + } + if ("getMetrics".equalsIgnoreCase(apiflag)){ + MetricService.doGetPolicyMetrics(response); + return; + } + } - public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException { - if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service) || "OPTIMIZATION".equalsIgnoreCase(service)){ - ImportService importService = new ImportService(); - importService.doImportMicroServicePut(request, response); - return; - } - if ("dictionaryItem".equalsIgnoreCase(service)) { - DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); - dictionaryHandler.doDictionaryAPIPut(request, response); - return; - } else { - SavePolicyHandler savePolicy = SavePolicyHandler.getInstance(); - savePolicy.doPolicyAPIPut(request, response); - } - } + public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException { + if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service) || "OPTIMIZATION".equalsIgnoreCase(service)){ + ImportService importService = new ImportService(); + importService.doImportMicroServicePut(request, response); + return; + } + if ("dictionaryItem".equalsIgnoreCase(service)) { + DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); + dictionaryHandler.doDictionaryAPIPut(request, response); + return; + } else { + SavePolicyHandler savePolicy = SavePolicyHandler.getInstance(); + savePolicy.doPolicyAPIPut(request, response); + } + } - public void doDelete(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext, String apiflag) throws IOException, SQLException{ - DeleteHandler deleteHandler = DeleteHandler.getInstance(); - if ("deletePapApi".equalsIgnoreCase(apiflag)) { - deleteHandler.doAPIDeleteFromPAP(request, response); - return; - } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) { - deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext); - setNewGroup(deleteHandler.getDeletedGroup()); - return; - } - } - - private void setNewGroup(OnapPDPGroup newGroup) { - this.newGroup = newGroup; - } + public void doDelete(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext, String apiflag) throws IOException, SQLException{ + DeleteHandler deleteHandler = DeleteHandler.getInstance(); + if ("deletePapApi".equalsIgnoreCase(apiflag)) { + deleteHandler.doAPIDeleteFromPAP(request, response); + return; + } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) { + deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext); + setNewGroup(deleteHandler.getDeletedGroup()); + return; + } + } - public OnapPDPGroup getNewGroup() { - return newGroup; - } + private void setNewGroup(OnapPDPGroup newGroup) { + this.newGroup = newGroup; + } + + public OnapPDPGroup getNewGroup() { + return newGroup; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java index f3dda33fc..e2c348239 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java @@ -59,429 +59,429 @@ import com.att.research.xacml.util.XACMLProperties; public class DeleteHandler { - private OnapPDPGroup newgroup; - private static Logger logger = FlexLogger.getLogger(DeleteHandler.class); - public static final String POLICY_IN_PDP = "PolicyInPDP"; - public static final String ERROR = "error"; - public static final String UNKNOWN = "unknown"; - private static final String REGEX = "[0-9a-zA-Z._]*"; + private OnapPDPGroup newgroup; + private static Logger logger = FlexLogger.getLogger(DeleteHandler.class); + public static final String POLICY_IN_PDP = "PolicyInPDP"; + public static final String ERROR = "error"; + public static final String UNKNOWN = "unknown"; + private static final String REGEX = "[0-9a-zA-Z._]*"; - public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException { - // get the request content into a String - String json = null; - java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - PolicyLogger.info("JSON request from API to Delete Policy from the PAP: " + json); - // convert Object sent as JSON into local object - StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); - String policyName = policy.getPolicyName(); - Boolean policyVersionDeleted = false; - String removeXMLExtension; - int currentVersion; - String removeVersionExtension; - String splitPolicyName = null; - String[] split = null; - String status = ERROR; - PolicyEntity policyEntity = null; - JPAUtils jpaUtils = null; + public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException { + // get the request content into a String + String json = null; + java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + PolicyLogger.info("JSON request from API to Delete Policy from the PAP: " + json); + // convert Object sent as JSON into local object + StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); + String policyName = policy.getPolicyName(); + Boolean policyVersionDeleted = false; + String removeXMLExtension; + int currentVersion; + String removeVersionExtension; + String splitPolicyName = null; + String[] split = null; + String status = ERROR; + PolicyEntity policyEntity = null; + JPAUtils jpaUtils = null; - String papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - String papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - String papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - String papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - Connection con = null; - - try { - jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP"); - response.addHeader(ERROR, "jpautils"); - response.addHeader("operation", "delete"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - if (jpaUtils.dbLockdownIgnoreErrors()) { - PolicyLogger.warn("Policies are locked down"); - response.addHeader("operation", "delete"); - response.addHeader("lockdown", "true"); - response.setStatus(HttpServletResponse.SC_ACCEPTED); - return; - } - EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); - Query policyEntityQuery = null; - try{ - if(policyName.endsWith(".xml")){ - removeXMLExtension = policyName.replace(".xml", ""); - currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf('.')+1)); - removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf('.')); - boolean queryCheck = true; - if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ - if(policyName.contains("Config_")){ - splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_"); - } - if(splitPolicyName != null){ - split = splitPolicyName.split(":"); - }else{ - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname."); - response.addHeader(ERROR, UNKNOWN); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope"); - }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) { - if(policyName.contains("Config_")){ - splitPolicyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - splitPolicyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - splitPolicyName = policyName.replace(".Decision_", ":Decision_"); - } - split = splitPolicyName.split(":"); - queryCheck = false; - policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope"); - } - - if(queryCheck){ - policyEntityQuery.setParameter("pName", "%"+split[1]+"%"); - }else{ - policyEntityQuery.setParameter("pName", split[1]); - } - - policyEntityQuery.setParameter("pScope", split[0]); - List<?> peResult = policyEntityQuery.getResultList(); - if(!peResult.isEmpty()){ - Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); - getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator)); - List<?> pvResult = getPolicyVersion.getResultList(); - PolicyVersion pVersion = (PolicyVersion) pvResult.get(0); - int newVersion = 0; - em.getTransaction().begin(); - Class.forName(papDbDriver); - con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); - - if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ - boolean groupCheck = checkPolicyGroupEntity(con, peResult); - if(!groupCheck){ - for(Object peData : peResult){ - policyEntity = (PolicyEntity) peData; - status = deletePolicyEntityData(em, policyEntity); - } - }else{ - status = POLICY_IN_PDP; - } - if(status.equals(ERROR)){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); - response.addHeader(ERROR, UNKNOWN); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - }else if(status.equals(POLICY_IN_PDP)){ - PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); - response.addHeader(ERROR, POLICY_IN_PDP); - response.setStatus(HttpServletResponse.SC_CONFLICT); - return; - }else{ - try{ - policyVersionDeleted = true; - em.remove(pVersion); - }catch(Exception e){ - logger.error(e.getMessage(),e); - policyVersionDeleted = false; - } - } - }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){ - boolean groupCheck = checkPolicyGroupEntity(con, peResult); - if(!groupCheck){ - policyEntity = (PolicyEntity) peResult.get(0); - status = deletePolicyEntityData(em, policyEntity); - }else{ - status = POLICY_IN_PDP; - } - - if(ERROR.equals(status)){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); - response.addHeader(ERROR, UNKNOWN); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - }else if(POLICY_IN_PDP.equals(status)){ - PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); - response.addHeader(ERROR, POLICY_IN_PDP); - response.setStatus(HttpServletResponse.SC_CONFLICT); - return; - }else{ - if(currentVersion > 1){ - if(!peResult.isEmpty()){ - for(Object object : peResult){ - policyEntity = (PolicyEntity) object; - String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); - int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1)); - if(policyEntityVersion > newVersion){ - newVersion = policyEntityVersion-1; - } - } - } - pVersion.setActiveVersion(newVersion); - pVersion.setHigherVersion(newVersion); - try{ - policyVersionDeleted = true; - em.persist(pVersion); - }catch(Exception e){ - logger.error(e.getMessage(),e); - policyVersionDeleted = false; - } - }else{ - try{ - policyVersionDeleted = true; - em.remove(pVersion); - }catch(Exception e){ - logger.error(e.getMessage(),e); - policyVersionDeleted = false; - } - } - } - } - }else{ - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader(ERROR, UNKNOWN); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - } - em.getTransaction().commit(); - }catch(Exception e){ - em.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR"); - response.addHeader(ERROR, "deleteDB"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } finally { - em.close(); - if(con != null){ - con.close(); - } - } + String papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); + String papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); + String papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); + String papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); + Connection con = null; - if (policyVersionDeleted) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "delete"); - return; - } else { - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader(ERROR, UNKNOWN); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - } - - public static String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity){ - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - PolicyRestAdapter policyData = new PolicyRestAdapter(); - String policyName = policyEntity.getPolicyName(); - try{ - if(policyName.contains("Config_")){ - em.remove(policyEntity.getConfigurationData()); - }else if(policyName.contains("Action_")){ - em.remove(policyEntity.getActionBodyEntity()); - } - String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - policyData.setNewFileName(searchPolicyName); - controller.deleteElk(policyData); - em.remove(policyEntity); - }catch(Exception e){ - logger.error(e.getMessage(),e); - return ERROR; - } - return "success"; - } - - public static boolean checkPolicyGroupEntity(Connection con, List<?> peResult) throws SQLException{ - for(Object peData : peResult){ - PolicyEntity policyEntity = (PolicyEntity) peData; - try(Statement st = con.createStatement(); - ResultSet rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'")){ - boolean gEntityList = rs.next(); - if(gEntityList){ - return true; - } - } - } - return false; - } + try { + jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP"); + response.addHeader(ERROR, "jpautils"); + response.addHeader("operation", "delete"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + if (jpaUtils.dbLockdownIgnoreErrors()) { + PolicyLogger.warn("Policies are locked down"); + response.addHeader("operation", "delete"); + response.addHeader("lockdown", "true"); + response.setStatus(HttpServletResponse.SC_ACCEPTED); + return; + } + EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); + Query policyEntityQuery = null; + try{ + if(policyName.endsWith(".xml")){ + removeXMLExtension = policyName.replace(".xml", ""); + currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf('.')+1)); + removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf('.')); + boolean queryCheck = true; + if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ + if(policyName.contains("Config_")){ + splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_"); + } + if(splitPolicyName != null){ + split = splitPolicyName.split(":"); + }else{ + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname."); + response.addHeader(ERROR, UNKNOWN); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope"); + }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) { + if(policyName.contains("Config_")){ + splitPolicyName = policyName.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + splitPolicyName = policyName.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + splitPolicyName = policyName.replace(".Decision_", ":Decision_"); + } + split = splitPolicyName.split(":"); + queryCheck = false; + policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope"); + } - public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws IOException { - - String policyName = request.getParameter("policyName"); - String groupId = request.getParameter("groupId"); - String responseString = null; - - if(groupId != null && !groupId.matches(REGEX) ){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error",ERROR); - response.addHeader("message", "Group Id is not valid"); - return; - } - - PolicyLogger.info("JSON request from API to Delete Policy from the PDP: " + policyName); + if(queryCheck){ + policyEntityQuery.setParameter("pName", "%"+split[1]+"%"); + }else{ + policyEntityQuery.setParameter("pName", split[1]); + } - // for PUT operations the group may or may not need to exist before the operation can be done - OnapPDPGroup group = null; - try { - group = XACMLPapServlet.getPAPEngine().getGroup(groupId); - } catch (PAPException e) { - PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e); - } - if (group == null) { - String message = "Unknown groupId '" + groupId + "'."; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.addHeader(ERROR, "UnknownGroup"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } else { - loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup"); - if (policyName.contains("xml")) { - PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue."); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... " - + "policyName must be the full name of the file to be deleted including version and extension"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... " - + "policyName must be the full name of the file to be deleted including version and extension"); - response.addHeader(ERROR, message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group); - PDPPolicy policy = group.getPolicy(policyName); - if (policy != null) { - - if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) { - if (preSafetyCheck(policy)) { - PolicyLogger.debug("Precheck Successful."); - } - } - PolicyLogger.info("Preparing to remove policy from group: " + group.getId()); - removePolicy.prepareToRemove(policy); - OnapPDPGroup updatedGroup = removePolicy.getUpdatedObject(); - responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP."; - PolicyLogger.error(message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP."); - response.addHeader(ERROR, message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - } - if (responseString.equals("success")) { - loggingContext.transactionEnded(); - PolicyLogger.info("Policy successfully deleted!"); - PolicyLogger.audit("Policy successfully deleted!"); - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "delete"); - return; - } else if (responseString.equals("No Group")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input."; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input."); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(ERROR, "groupUpdate"); - response.addHeader("message", message); - return; - } else if (responseString.equals("DB Error")) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(ERROR, "deleteDB"); - return; - } else { - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader(ERROR, UNKNOWN); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - } + policyEntityQuery.setParameter("pScope", split[0]); + List<?> peResult = policyEntityQuery.getResultList(); + if(!peResult.isEmpty()){ + Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); + getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator)); + List<?> pvResult = getPolicyVersion.getResultList(); + PolicyVersion pVersion = (PolicyVersion) pvResult.get(0); + int newVersion = 0; + em.getTransaction().begin(); + Class.forName(papDbDriver); + con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); - private String deletePolicyFromPDPGroup (OnapPDPGroup group, ONAPLoggingContext loggingContext){ - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); - String response = null; - loggingContext.setServiceName("API:PAP.DeleteHandler"); - OnapPDPGroup existingGroup = null; - try { - existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId()); - } catch (PAPException e1) { - PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1); - } - if (!(group instanceof StdPDPGroup) || existingGroup == null || !(group.getId().equals(existingGroup.getId()))) { - String existingID = null; - if(existingGroup != null){ - existingID = existingGroup.getId(); - } - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingID + " objectFromJSON="+group); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response = "No Group"; - return response; - } - // 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 - ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory()); - try{ - acPutTransaction.updateGroup(group, "XACMLPapServlet.doDelete"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " - +"group="+existingGroup.getId()); - response = "DB Error"; - return response; - } - try { - XACMLPapServlet.getPAPEngine().updateGroup(group); - } catch (PAPException e) { - PolicyLogger.error("Exception occured While Updating PDP Groups"+e); - response = "error in updateGroup method"; - } - PolicyLogger.debug("Group '" + group.getId() + "' updated"); - acPutTransaction.commitTransaction(); - // Group changed, which might include changing the policies - try { - newgroup = existingGroup; - } catch (Exception e) { - PolicyLogger.error("Exception occured in Group Change Method"+e); - response = "error in groupChanged method"; - } - if (response==null){ - response = "success"; - loggingContext.transactionEnded(); - PolicyLogger.audit("Policy successfully deleted!"); - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended"); - return response; - } - - public OnapPDPGroup getDeletedGroup(){ - return newgroup; - } - - public boolean preSafetyCheck(PDPPolicy policy) { - return true; - } - - public static DeleteHandler getInstance() { - try { - Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName())); - return (DeleteHandler) deleteHandler.newInstance(); - } catch (Exception e) { - logger.error(e.getMessage(),e); - } - return null; - } + if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ + boolean groupCheck = checkPolicyGroupEntity(con, peResult); + if(!groupCheck){ + for(Object peData : peResult){ + policyEntity = (PolicyEntity) peData; + status = deletePolicyEntityData(em, policyEntity); + } + }else{ + status = POLICY_IN_PDP; + } + if(status.equals(ERROR)){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); + response.addHeader(ERROR, UNKNOWN); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + }else if(status.equals(POLICY_IN_PDP)){ + PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); + response.addHeader(ERROR, POLICY_IN_PDP); + response.setStatus(HttpServletResponse.SC_CONFLICT); + return; + }else{ + try{ + policyVersionDeleted = true; + em.remove(pVersion); + }catch(Exception e){ + logger.error(e.getMessage(),e); + policyVersionDeleted = false; + } + } + }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){ + boolean groupCheck = checkPolicyGroupEntity(con, peResult); + if(!groupCheck){ + policyEntity = (PolicyEntity) peResult.get(0); + status = deletePolicyEntityData(em, policyEntity); + }else{ + status = POLICY_IN_PDP; + } + + if(ERROR.equals(status)){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); + response.addHeader(ERROR, UNKNOWN); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + }else if(POLICY_IN_PDP.equals(status)){ + PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); + response.addHeader(ERROR, POLICY_IN_PDP); + response.setStatus(HttpServletResponse.SC_CONFLICT); + return; + }else{ + if(currentVersion > 1){ + if(!peResult.isEmpty()){ + for(Object object : peResult){ + policyEntity = (PolicyEntity) object; + String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); + int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1)); + if(policyEntityVersion > newVersion){ + newVersion = policyEntityVersion-1; + } + } + } + pVersion.setActiveVersion(newVersion); + pVersion.setHigherVersion(newVersion); + try{ + policyVersionDeleted = true; + em.persist(pVersion); + }catch(Exception e){ + logger.error(e.getMessage(),e); + policyVersionDeleted = false; + } + }else{ + try{ + policyVersionDeleted = true; + em.remove(pVersion); + }catch(Exception e){ + logger.error(e.getMessage(),e); + policyVersionDeleted = false; + } + } + } + } + }else{ + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); + response.addHeader(ERROR, UNKNOWN); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + } + em.getTransaction().commit(); + }catch(Exception e){ + em.getTransaction().rollback(); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR"); + response.addHeader(ERROR, "deleteDB"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } finally { + em.close(); + if(con != null){ + con.close(); + } + } + + if (policyVersionDeleted) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "delete"); + return; + } else { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); + response.addHeader(ERROR, UNKNOWN); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + } + + public static String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity){ + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + PolicyRestAdapter policyData = new PolicyRestAdapter(); + String policyName = policyEntity.getPolicyName(); + try{ + if(policyName.contains("Config_")){ + em.remove(policyEntity.getConfigurationData()); + }else if(policyName.contains("Action_")){ + em.remove(policyEntity.getActionBodyEntity()); + } + String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + policyData.setNewFileName(searchPolicyName); + controller.deleteElk(policyData); + em.remove(policyEntity); + }catch(Exception e){ + logger.error(e.getMessage(),e); + return ERROR; + } + return "success"; + } + + public static boolean checkPolicyGroupEntity(Connection con, List<?> peResult) throws SQLException{ + for(Object peData : peResult){ + PolicyEntity policyEntity = (PolicyEntity) peData; + try(Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'")){ + boolean gEntityList = rs.next(); + if(gEntityList){ + return true; + } + } + } + return false; + } + + public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws IOException { + + String policyName = request.getParameter("policyName"); + String groupId = request.getParameter("groupId"); + String responseString = null; + + if(groupId != null && !groupId.matches(REGEX) ){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error",ERROR); + response.addHeader("message", "Group Id is not valid"); + return; + } + + PolicyLogger.info("JSON request from API to Delete Policy from the PDP: " + policyName); + + // for PUT operations the group may or may not need to exist before the operation can be done + OnapPDPGroup group = null; + try { + group = XACMLPapServlet.getPAPEngine().getGroup(groupId); + } catch (PAPException e) { + PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e); + } + if (group == null) { + String message = "Unknown groupId '" + groupId + "'."; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.addHeader(ERROR, "UnknownGroup"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + return; + } else { + loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup"); + if (policyName.contains("xml")) { + PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue."); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... " + + "policyName must be the full name of the file to be deleted including version and extension"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... " + + "policyName must be the full name of the file to be deleted including version and extension"); + response.addHeader(ERROR, message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group); + PDPPolicy policy = group.getPolicy(policyName); + if (policy != null) { + + if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) { + if (preSafetyCheck(policy)) { + PolicyLogger.debug("Precheck Successful."); + } + } + PolicyLogger.info("Preparing to remove policy from group: " + group.getId()); + removePolicy.prepareToRemove(policy); + OnapPDPGroup updatedGroup = removePolicy.getUpdatedObject(); + responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP."; + PolicyLogger.error(message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP."); + response.addHeader(ERROR, message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + } + if (responseString.equals("success")) { + loggingContext.transactionEnded(); + PolicyLogger.info("Policy successfully deleted!"); + PolicyLogger.audit("Policy successfully deleted!"); + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "delete"); + return; + } else if (responseString.equals("No Group")) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input."; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input."); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader(ERROR, "groupUpdate"); + response.addHeader("message", message); + return; + } else if (responseString.equals("DB Error")) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader(ERROR, "deleteDB"); + return; + } else { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); + response.addHeader(ERROR, UNKNOWN); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + } + + private String deletePolicyFromPDPGroup (OnapPDPGroup group, ONAPLoggingContext loggingContext){ + PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); + String response = null; + loggingContext.setServiceName("API:PAP.DeleteHandler"); + OnapPDPGroup existingGroup = null; + try { + existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId()); + } catch (PAPException e1) { + PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1); + } + if (!(group instanceof StdPDPGroup) || existingGroup == null || !(group.getId().equals(existingGroup.getId()))) { + String existingID = null; + if(existingGroup != null){ + existingID = existingGroup.getId(); + } + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingID + " objectFromJSON="+group); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response = "No Group"; + return response; + } + // 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 + ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory()); + try{ + acPutTransaction.updateGroup(group, "XACMLPapServlet.doDelete"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " + +"group="+existingGroup.getId()); + response = "DB Error"; + return response; + } + try { + XACMLPapServlet.getPAPEngine().updateGroup(group); + } catch (PAPException e) { + PolicyLogger.error("Exception occured While Updating PDP Groups"+e); + response = "error in updateGroup method"; + } + PolicyLogger.debug("Group '" + group.getId() + "' updated"); + acPutTransaction.commitTransaction(); + // Group changed, which might include changing the policies + try { + newgroup = existingGroup; + } catch (Exception e) { + PolicyLogger.error("Exception occured in Group Change Method"+e); + response = "error in groupChanged method"; + } + if (response==null){ + response = "success"; + loggingContext.transactionEnded(); + PolicyLogger.audit("Policy successfully deleted!"); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended"); + return response; + } + + public OnapPDPGroup getDeletedGroup(){ + return newgroup; + } + + public boolean preSafetyCheck(PDPPolicy policy) { + return true; + } + + public static DeleteHandler getInstance() { + try { + Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName())); + return (DeleteHandler) deleteHandler.newInstance(); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + return null; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java index 6aec7a9bc..89ce18835 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java @@ -28,38 +28,38 @@ import org.onap.policy.common.logging.flexlogger.Logger; import com.att.research.xacml.util.XACMLProperties; public interface DictionaryHandler { - public static final Logger logger = FlexLogger.getLogger(DictionaryHandler.class); - String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName(); + public static final Logger logger = FlexLogger.getLogger(DictionaryHandler.class); + String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName(); - /* - * Get Instance - */ - public static DictionaryHandler getInstance(){ - try { - Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); - DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance(); - return instance; - } catch (Exception e) { - logger.error(e.getMessage(),e); - } - return null; - } - - /* - * Get Equivalent for Dictionary Services. - */ - public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response); - /* - * Put Equivalent for Dictionary Services. - */ - public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response); - - /** - * Can be used to extend the services. - * - * getflag=true indicates Get Request. - * getflag=false indicates Put Request. - * @return - */ - public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag); + /* + * Get Instance + */ + public static DictionaryHandler getInstance(){ + try { + Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); + DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance(); + return instance; + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + return null; + } + + /* + * Get Equivalent for Dictionary Services. + */ + public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response); + /* + * Put Equivalent for Dictionary Services. + */ + public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response); + + /** + * Can be used to extend the services. + * + * getflag=true indicates Get Request. + * getflag=false indicates Put Request. + * @return + */ + public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java index d0cd985a3..b90592b02 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java @@ -28,302 +28,302 @@ import org.onap.policy.pap.xacml.rest.service.DictionaryService; import org.onap.policy.xacml.api.XACMLErrorConstants; public class DictionaryHandlerImpl implements DictionaryHandler{ - /* - * Get Equivalent for Dictionary Services. - */ - public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response) { - String dictionaryType = request.getParameter("dictionaryType"); - try { - DictionaryService dictionary = new DictionaryService(); - switch (dictionaryType) { - case "OnapName": - dictionary.getOnapDictionary(response); - break; - case "Attribute": - dictionary.getAttributeDictionary(response); - break; - case "Action": - dictionary.getActionPolicyDictionary(response); - break; - case "BRMSParamTemplate": - dictionary.getBRMSParamDictionary(response); - break; - case "VSCLAction": - dictionary.getVSCLAction(response); - break; - case "VNFType": - dictionary.getVnfType(response); - break; - case "PEPOptions": - dictionary.getPEPOptions(response); - break; - case "Varbind": - dictionary.getVarbind(response); - break; - case "Service": - dictionary.getServiceType(response); - break; - case "Site": - dictionary.getSiteType(response); - break; - case "Settings": - dictionary.getSettingsDictionary(response); - break; - case "RainyDayTreatments": - dictionary.getRainyDayDictionary(response); - break; - case "DescriptiveScope": - dictionary.getDescriptiveDictionary(response); - break; - case "ActionList": - dictionary.getActionListDictionary(response); - break; - case "ProtocolList": - dictionary.getProtocolListDictionary(response); - break; - case "Zone": - dictionary.getZoneDictionary(response); - break; - case "SecurityZone": - dictionary.getSecurityZoneDictionary(response); - break; - case "PrefixList": - dictionary.getPrefixListDictionary(response); - break; - case "AddressGroup": - dictionary.getAddressGroupDictionary(response); - break; - case "ServiceGroup": - dictionary.getServiceGroupDictionary(response); - break; - case "ServiceList": - dictionary.getServiceListDictionary(response); - break; - case "TermList": - case "RuleList": - case "FirewallRuleList": - case "Term": - dictionary.getTermListDictionary(response); - break; - case "MicroServiceLocation": - dictionary.getMicroServiceLocationDictionary(response); - break; - case "MicroServiceConfigName": - dictionary.getMicroServiceConfigNameDictionary(response); - break; - case "DCAEUUID": - dictionary.getDCAEUUIDDictionary(response); - break; - case "MicroServiceModels": - dictionary.getMicroServiceModelsDictionary(response); - break; - case "MicroServiceDictionary": - dictionary.getMicroServiceDictionary(response); - break; - case "OptimizationModels": - dictionary.getOptimizationModelsDictionary(response); - break; - case "PolicyScopeService": - dictionary.getPSServiceDictionary(response); - break; - case "PolicyScopeResource": - dictionary.getPSResourceDictionary(response); - break; - case "PolicyScopeType": - dictionary.getPSTypeDictionary(response); - break; - case "PolicyScopeClosedLoop": - dictionary.getPSClosedLoopDictionary(response); - break; - case "GroupPolicyScopeList": - dictionary.getPSGroupScopeDictionary(response); - break; - case "RiskType": - dictionary.getRiskTypeDictionary(response); - break; - case "SafePolicyWarning": - dictionary.getSafePolicyWarningDictionary(response); - break; - default: - extendedOptions(dictionaryType, request, response, true); - return; - } - } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DictionaryHandler", " Error Querying the Database."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - response.addHeader("error", message); - return; - } - } - - /** - * Can be used to extend the services. - * - * getflag=true indicates Get Request. - * getflag=false indicates Put Request. - * @return - */ - public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag) { - // Default code - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Invalid Dictionary in Request."; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "DictionaryHandler", " Invalid Dictionary in Request."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.setHeader("error", "dictionary"); - response.addHeader("error", message); - return null; - } + /* + * Get Equivalent for Dictionary Services. + */ + public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response) { + String dictionaryType = request.getParameter("dictionaryType"); + try { + DictionaryService dictionary = new DictionaryService(); + switch (dictionaryType) { + case "OnapName": + dictionary.getOnapDictionary(response); + break; + case "Attribute": + dictionary.getAttributeDictionary(response); + break; + case "Action": + dictionary.getActionPolicyDictionary(response); + break; + case "BRMSParamTemplate": + dictionary.getBRMSParamDictionary(response); + break; + case "VSCLAction": + dictionary.getVSCLAction(response); + break; + case "VNFType": + dictionary.getVnfType(response); + break; + case "PEPOptions": + dictionary.getPEPOptions(response); + break; + case "Varbind": + dictionary.getVarbind(response); + break; + case "Service": + dictionary.getServiceType(response); + break; + case "Site": + dictionary.getSiteType(response); + break; + case "Settings": + dictionary.getSettingsDictionary(response); + break; + case "RainyDayTreatments": + dictionary.getRainyDayDictionary(response); + break; + case "DescriptiveScope": + dictionary.getDescriptiveDictionary(response); + break; + case "ActionList": + dictionary.getActionListDictionary(response); + break; + case "ProtocolList": + dictionary.getProtocolListDictionary(response); + break; + case "Zone": + dictionary.getZoneDictionary(response); + break; + case "SecurityZone": + dictionary.getSecurityZoneDictionary(response); + break; + case "PrefixList": + dictionary.getPrefixListDictionary(response); + break; + case "AddressGroup": + dictionary.getAddressGroupDictionary(response); + break; + case "ServiceGroup": + dictionary.getServiceGroupDictionary(response); + break; + case "ServiceList": + dictionary.getServiceListDictionary(response); + break; + case "TermList": + case "RuleList": + case "FirewallRuleList": + case "Term": + dictionary.getTermListDictionary(response); + break; + case "MicroServiceLocation": + dictionary.getMicroServiceLocationDictionary(response); + break; + case "MicroServiceConfigName": + dictionary.getMicroServiceConfigNameDictionary(response); + break; + case "DCAEUUID": + dictionary.getDCAEUUIDDictionary(response); + break; + case "MicroServiceModels": + dictionary.getMicroServiceModelsDictionary(response); + break; + case "MicroServiceDictionary": + dictionary.getMicroServiceDictionary(response); + break; + case "OptimizationModels": + dictionary.getOptimizationModelsDictionary(response); + break; + case "PolicyScopeService": + dictionary.getPSServiceDictionary(response); + break; + case "PolicyScopeResource": + dictionary.getPSResourceDictionary(response); + break; + case "PolicyScopeType": + dictionary.getPSTypeDictionary(response); + break; + case "PolicyScopeClosedLoop": + dictionary.getPSClosedLoopDictionary(response); + break; + case "GroupPolicyScopeList": + dictionary.getPSGroupScopeDictionary(response); + break; + case "RiskType": + dictionary.getRiskTypeDictionary(response); + break; + case "SafePolicyWarning": + dictionary.getSafePolicyWarningDictionary(response); + break; + default: + extendedOptions(dictionaryType, request, response, true); + return; + } + } catch (Exception e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DictionaryHandler", " Error Querying the Database."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + response.addHeader("error", message); + return; + } + } - public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response) { - String result = null; - String dictionaryType = request.getParameter("dictionaryType"); - String operation = request.getParameter("operation"); - try { - DictionaryService dictionary = new DictionaryService(); - switch (dictionaryType) { - case "OnapName": - result = dictionary.saveOnapDictionary(request, response); - break; - case "Attribute": - result = dictionary.saveAttributeDictionary(request, response); - break; - case "Action": - result = dictionary.saveActionPolicyDictionary(request, response); - break; - case "BRMSParamTemplate": - result = dictionary.saveBRMSParamDictionary(request, response); - break; - case "VSCLAction": - result = dictionary.saveVSCLAction(request, response); - break; - case "VNFType": - result = dictionary.saveVnfType(request, response); - break; - case "PEPOptions": - result = dictionary.savePEPOptions(request, response); - break; - case "Varbind": - result = dictionary.saveVarbind(request, response); - break; - case "Service": - result = dictionary.saveServiceType(request, response); - break; - case "Site": - result = dictionary.saveSiteType(request, response); - break; - case "Settings": - result = dictionary.saveSettingsDictionary(request, response); - break; - case "RainyDayTreatments": - result = dictionary.saveRainyDayDictionary(request, response); - break; - case "DescriptiveScope": - result = dictionary.saveDescriptiveDictionary(request, response); - break; - case "ActionList": - result = dictionary.saveActionListDictionary(request, response); - break; - case "ProtocolList": - result = dictionary.saveProtocolListDictionary(request, response); - break; - case "Zone": - result = dictionary.saveZoneDictionary(request, response); - break; - case "SecurityZone": - result = dictionary.saveSecurityZoneDictionary(request, response); - break; - case "PrefixList": - result = dictionary.savePrefixListDictionary(request, response); - break; - case "AddressGroup": - result = dictionary.saveAddressGroupDictionary(request, response); - break; - case "ServiceGroup": - result = dictionary.saveServiceGroupDictionary(request, response); - break; - case "ServiceList": - result = dictionary.saveServiceListDictionary(request, response); - break; - case "TermList": - case "RuleList": - case "FirewallRuleList": - case "Term": - result = dictionary.saveTermListDictionary(request, response); - break; - case "MicroServiceLocation": - result = dictionary.saveMicroServiceLocationDictionary(request, response); - break; - case "MicroServiceConfigName": - result = dictionary.saveMicroServiceConfigNameDictionary(request, response); - break; - case "DCAEUUID": - result = dictionary.saveDCAEUUIDDictionary(request, response); - break; - case "MicroServiceModels": - result = dictionary.saveMicroServiceModelsDictionary(request, response); - break; - case "MicroServiceDictionary": - result = dictionary.saveMicroServiceDictionary(request, response); - break; - case "OptimizationModels": - result = dictionary.saveOptimizationModelsDictionary(request, response); - break; - case "PolicyScopeService": - result = dictionary.savePSServiceDictionary(request, response); - break; - case "PolicyScopeResource": - result = dictionary.savePSResourceDictionary(request, response); - break; - case "PolicyScopeType": - result = dictionary.savePSTypeDictionary(request, response); - break; - case "PolicyScopeClosedLoop": - result = dictionary.savePSClosedLoopDictionary(request, response); - break; - case "GroupPolicyScopeList": - result = dictionary.savePSGroupScopeDictionary(request, response); - break; - case "RiskType": - result = dictionary.saveRiskTypeDictionary(request, response); - break; - case "SafePolicyWarning": - result = dictionary.saveSafePolicyWarningDictionary(request, response); - break; - default: - result = extendedOptions(dictionaryType, request, response, false); - if(result==null){ - return; - }else{ - break; - } - } - } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database: " + e.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Updating the Database."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - return; - } - if (result.equalsIgnoreCase("Success")) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - if (operation.equalsIgnoreCase("update")) { - response.addHeader("operation", "updateDictionary"); - } else { - response.addHeader("operation", "createDictionary"); - } - } else if (result.equalsIgnoreCase("Duplicate")) { - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "dictionaryItemExists"); - } else if (result.equalsIgnoreCase("DuplicateGroup")) { - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "duplicateGroup"); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database."; - PolicyLogger.error(message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - } - } + /** + * Can be used to extend the services. + * + * getflag=true indicates Get Request. + * getflag=false indicates Put Request. + * @return + */ + public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag) { + // Default code + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Invalid Dictionary in Request."; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "DictionaryHandler", " Invalid Dictionary in Request."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.setHeader("error", "dictionary"); + response.addHeader("error", message); + return null; + } + + public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response) { + String result = null; + String dictionaryType = request.getParameter("dictionaryType"); + String operation = request.getParameter("operation"); + try { + DictionaryService dictionary = new DictionaryService(); + switch (dictionaryType) { + case "OnapName": + result = dictionary.saveOnapDictionary(request, response); + break; + case "Attribute": + result = dictionary.saveAttributeDictionary(request, response); + break; + case "Action": + result = dictionary.saveActionPolicyDictionary(request, response); + break; + case "BRMSParamTemplate": + result = dictionary.saveBRMSParamDictionary(request, response); + break; + case "VSCLAction": + result = dictionary.saveVSCLAction(request, response); + break; + case "VNFType": + result = dictionary.saveVnfType(request, response); + break; + case "PEPOptions": + result = dictionary.savePEPOptions(request, response); + break; + case "Varbind": + result = dictionary.saveVarbind(request, response); + break; + case "Service": + result = dictionary.saveServiceType(request, response); + break; + case "Site": + result = dictionary.saveSiteType(request, response); + break; + case "Settings": + result = dictionary.saveSettingsDictionary(request, response); + break; + case "RainyDayTreatments": + result = dictionary.saveRainyDayDictionary(request, response); + break; + case "DescriptiveScope": + result = dictionary.saveDescriptiveDictionary(request, response); + break; + case "ActionList": + result = dictionary.saveActionListDictionary(request, response); + break; + case "ProtocolList": + result = dictionary.saveProtocolListDictionary(request, response); + break; + case "Zone": + result = dictionary.saveZoneDictionary(request, response); + break; + case "SecurityZone": + result = dictionary.saveSecurityZoneDictionary(request, response); + break; + case "PrefixList": + result = dictionary.savePrefixListDictionary(request, response); + break; + case "AddressGroup": + result = dictionary.saveAddressGroupDictionary(request, response); + break; + case "ServiceGroup": + result = dictionary.saveServiceGroupDictionary(request, response); + break; + case "ServiceList": + result = dictionary.saveServiceListDictionary(request, response); + break; + case "TermList": + case "RuleList": + case "FirewallRuleList": + case "Term": + result = dictionary.saveTermListDictionary(request, response); + break; + case "MicroServiceLocation": + result = dictionary.saveMicroServiceLocationDictionary(request, response); + break; + case "MicroServiceConfigName": + result = dictionary.saveMicroServiceConfigNameDictionary(request, response); + break; + case "DCAEUUID": + result = dictionary.saveDCAEUUIDDictionary(request, response); + break; + case "MicroServiceModels": + result = dictionary.saveMicroServiceModelsDictionary(request, response); + break; + case "MicroServiceDictionary": + result = dictionary.saveMicroServiceDictionary(request, response); + break; + case "OptimizationModels": + result = dictionary.saveOptimizationModelsDictionary(request, response); + break; + case "PolicyScopeService": + result = dictionary.savePSServiceDictionary(request, response); + break; + case "PolicyScopeResource": + result = dictionary.savePSResourceDictionary(request, response); + break; + case "PolicyScopeType": + result = dictionary.savePSTypeDictionary(request, response); + break; + case "PolicyScopeClosedLoop": + result = dictionary.savePSClosedLoopDictionary(request, response); + break; + case "GroupPolicyScopeList": + result = dictionary.savePSGroupScopeDictionary(request, response); + break; + case "RiskType": + result = dictionary.saveRiskTypeDictionary(request, response); + break; + case "SafePolicyWarning": + result = dictionary.saveSafePolicyWarningDictionary(request, response); + break; + default: + result = extendedOptions(dictionaryType, request, response, false); + if(result==null){ + return; + }else{ + break; + } + } + } catch (Exception e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database: " + e.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Updating the Database."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + return; + } + if (result.equalsIgnoreCase("Success")) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + if (operation.equalsIgnoreCase("update")) { + response.addHeader("operation", "updateDictionary"); + } else { + response.addHeader("operation", "createDictionary"); + } + } else if (result.equalsIgnoreCase("Duplicate")) { + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader("error", "dictionaryItemExists"); + } else if (result.equalsIgnoreCase("DuplicateGroup")) { + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader("error", "duplicateGroup"); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database."; + PolicyLogger.error(message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + } + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java index 6e348fb1b..4dd87e22f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java @@ -39,86 +39,86 @@ import org.onap.policy.common.logging.flexlogger.Logger; import com.att.research.xacml.util.XACMLProperties; public class PushPolicyHandler { - private static final Logger logger = FlexLogger.getLogger(PushPolicyHandler.class); - /* - * Get Active Version. - */ - public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) { - EntityManager em = null; - if(XACMLPapServlet.getEmf()!=null){ - em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); - } - if (em==null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); - return; - } - String policyScope = request.getParameter("policyScope"); - String filePrefix = request.getParameter("filePrefix"); - String policyName = request.getParameter("policyName"); + private static final Logger logger = FlexLogger.getLogger(PushPolicyHandler.class); + /* + * Get Active Version. + */ + public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) { + EntityManager em = null; + if(XACMLPapServlet.getEmf()!=null){ + em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); + } + if (em==null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); + return; + } + String policyScope = request.getParameter("policyScope"); + String filePrefix = request.getParameter("filePrefix"); + String policyName = request.getParameter("policyName"); - String pvName = policyScope + File.separator + filePrefix + policyName; - int activeVersion = 0; + String pvName = policyScope + File.separator + filePrefix + policyName; + int activeVersion = 0; - //Get the Active Version to use in the ID - em.getTransaction().begin(); - Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); - query.setParameter("pname", pvName); + //Get the Active Version to use in the ID + em.getTransaction().begin(); + Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); + query.setParameter("pname", pvName); - @SuppressWarnings("rawtypes") - List result = query.getResultList(); - PolicyVersion versionEntity = null; - if (!result.isEmpty()) { - versionEntity = (PolicyVersion) result.get(0); - em.persist(versionEntity); - activeVersion = versionEntity.getActiveVersion(); - em.getTransaction().commit(); - } else { - PolicyLogger.debug("No PolicyVersion using policyName found"); - } + @SuppressWarnings("rawtypes") + List result = query.getResultList(); + PolicyVersion versionEntity = null; + if (!result.isEmpty()) { + versionEntity = (PolicyVersion) result.get(0); + em.persist(versionEntity); + activeVersion = versionEntity.getActiveVersion(); + em.getTransaction().commit(); + } else { + PolicyLogger.debug("No PolicyVersion using policyName found"); + } - //clean up connection - em.close(); - if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("version", String.valueOf(activeVersion)); - } else { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - } - } - - /* - * Get Selected URI path. - */ - public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) { - String gitPath = request.getParameter("gitPath"); - File file = new File(gitPath); - PolicyLogger.debug("The fileItem is : " + file.toString()); - URI selectedURI = file.toURI(); - String uri = selectedURI.toString(); - if (!uri.equalsIgnoreCase("")) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("selectedURI", uri); - } else { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - } - } - - public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){ - return true; - } - - public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){ - return true; - } - - public static PushPolicyHandler getInstance() { - try { - Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); - PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance(); - return instance; - } catch (Exception e) { - logger.error(e.getMessage(),e); - } - return null; - } + //clean up connection + em.close(); + if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("version", String.valueOf(activeVersion)); + } else { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + } + + /* + * Get Selected URI path. + */ + public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) { + String gitPath = request.getParameter("gitPath"); + File file = new File(gitPath); + PolicyLogger.debug("The fileItem is : " + file.toString()); + URI selectedURI = file.toURI(); + String uri = selectedURI.toString(); + if (!uri.equalsIgnoreCase("")) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("selectedURI", uri); + } else { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + } + + public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){ + return true; + } + + public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){ + return true; + } + + public static PushPolicyHandler getInstance() { + try { + Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); + PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance(); + return instance; + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + return null; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java index 6606d383b..335434fd4 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java @@ -40,127 +40,127 @@ import org.xml.sax.SAXException; import com.att.research.xacml.util.XACMLProperties; public class SavePolicyHandler { - private static final Logger logger = FlexLogger.getLogger(SavePolicyHandler.class); - private HashMap<String, String> ErrorHeaders = null; - - public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException { - String operation = request.getParameter("operation"); - String policyType = request.getParameter("policyType"); - String apiflag = request.getParameter("apiflag"); - PolicyCreation creation = new PolicyCreation(); + private static final Logger logger = FlexLogger.getLogger(SavePolicyHandler.class); + private HashMap<String, String> ErrorHeaders = null; + + public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException { + String operation = request.getParameter("operation"); + String policyType = request.getParameter("policyType"); + String apiflag = request.getParameter("apiflag"); + PolicyCreation creation = new PolicyCreation(); if ( policyType != null ) { - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - if("update".equalsIgnoreCase(operation)){ - policyAdapter.setEditPolicy(true); - }else{ - policyAdapter.setEditPolicy(false); - } - - // 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) - java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - - if(policyAdapter.isEditPolicy()){ - PolicyLogger.info("SavePolicyHandler: JSON request from API to update a policy: " + json); - } else { - PolicyLogger.info("SavePolicyHandler: JSON request from API to create a policy: " + json); - } - - // convert Object sent as JSON into local object - StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); - //Set policyAdapter values including parentPath (Common to all policy types) - try { - PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter"); + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + if("update".equalsIgnoreCase(operation)){ + policyAdapter.setEditPolicy(true); + }else{ + policyAdapter.setEditPolicy(false); + } + + // 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) + java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + + if(policyAdapter.isEditPolicy()){ + PolicyLogger.info("SavePolicyHandler: JSON request from API to update a policy: " + json); + } else { + PolicyLogger.info("SavePolicyHandler: JSON request from API to create a policy: " + json); + } + + // convert Object sent as JSON into local object + StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); + //Set policyAdapter values including parentPath (Common to all policy types) + try { + PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter"); policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag); if(!extendedPolicyOptions(policyAdapter, response)){ - creation.savePolicy(policyAdapter, response); + creation.savePolicy(policyAdapter, response); } if ("update".equalsIgnoreCase(operation)) { - response.addHeader("operation", "update"); - } else { - response.addHeader("operation", "create"); - } - } catch (Exception e1) { - logger.error("Could not set data to policy adapter "+e1.getMessage(),e1); - } + response.addHeader("operation", "update"); + } else { + response.addHeader("operation", "create"); + } + } catch (Exception e1) { + logger.error("Could not set data to policy adapter "+e1.getMessage(),e1); + } } - } + } - private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{ - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - policyAdapter.setApiflag(apiflag); - /* - * set policy adapter values for Building JSON object containing policy data - */ - //Common among policy types - policyAdapter.setPolicyName(policy.getPolicyName()); - policyAdapter.setPolicyDescription(policy.getPolicyDescription()); - policyAdapter.setOnapName(policy.getOnapName()); //Config Base and Decision Policies - policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); - - policyAdapter.setPolicyType(policyType); - policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes()); - policyAdapter.setEditPolicy(policy.isEditPolicy()); - policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf()); - //Config Specific - policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall - policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base - policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base - policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop - policyAdapter.setConfigPolicyType(policy.getConfigPolicyType()); - policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault - policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM - policyAdapter.setUuid(policy.getUuid()); //Micro Service - policyAdapter.setLocation(policy.getMsLocation()); //Micro Service - policyAdapter.setPriority(policy.getPriority()); //Micro Service - policyAdapter.setPolicyScope(policy.getDomainDir()); - policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes - policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes - policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes - policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes - policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams()); + private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{ + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + policyAdapter.setApiflag(apiflag); + /* + * set policy adapter values for Building JSON object containing policy data + */ + //Common among policy types + policyAdapter.setPolicyName(policy.getPolicyName()); + policyAdapter.setPolicyDescription(policy.getPolicyDescription()); + policyAdapter.setOnapName(policy.getOnapName()); //Config Base and Decision Policies + policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); + + policyAdapter.setPolicyType(policyType); + policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes()); + policyAdapter.setEditPolicy(policy.isEditPolicy()); + policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf()); + //Config Specific + policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall + policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base + policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base + policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop + policyAdapter.setConfigPolicyType(policy.getConfigPolicyType()); + policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault + policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM + policyAdapter.setUuid(policy.getUuid()); //Micro Service + policyAdapter.setLocation(policy.getMsLocation()); //Micro Service + policyAdapter.setPriority(policy.getPriority()); //Micro Service + policyAdapter.setPolicyScope(policy.getDomainDir()); + policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes + policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes + policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes + policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes + policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams()); policyAdapter.setBrmsDependency(policy.getBrmsDependency()); // BRMS Policies. policyAdapter.setBrmsController(policy.getBrmsController()); // BRMS Policies. - //Action Policy Specific - policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue - policyAdapter.setActionPerformer(policy.getActionPerformer()); - policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels()); - policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo()); - policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1()); - policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2()); - //Decision Policy Specific - policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap()); - policyAdapter.setRuleProvider(policy.getProviderComboBox()); - policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); - policyAdapter.setRainydayMap(policy.getTreatments()); + //Action Policy Specific + policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue + policyAdapter.setActionPerformer(policy.getActionPerformer()); + policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels()); + policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo()); + policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1()); + policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2()); + //Decision Policy Specific + policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap()); + policyAdapter.setRuleProvider(policy.getProviderComboBox()); + policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); + policyAdapter.setRainydayMap(policy.getTreatments()); + + return policyAdapter; + } - return policyAdapter; - } - - public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){ - return false; - } - - public void addErrorHeader(String key, String value){ - if(ErrorHeaders==null){ - ErrorHeaders= new HashMap<>(); - } - ErrorHeaders.put(key, value); - } + public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){ + return false; + } - public static SavePolicyHandler getInstance() { - try { - Class<?> savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); - SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance(); - return instance; - } catch (Exception e) { - logger.error(e.getMessage(),e); - } - return null; - } + public void addErrorHeader(String key, String value){ + if(ErrorHeaders==null){ + ErrorHeaders= new HashMap<>(); + } + ErrorHeaders.put(key, value); + } + + public static SavePolicyHandler getInstance() { + try { + Class<?> savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); + SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance(); + return instance; + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + return null; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java index 8c891bf69..2d98b820d 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java @@ -32,74 +32,74 @@ import com.att.research.xacml.api.pap.PDPPolicy; public class RemoveGroupPolicy { - - //Container from where we are fetching the policies - private static PDPPolicyContainer policyContainer; - - private RemoveGroupPolicy self = this; - private StdPDPGroup updatedObject; - private final StdPDPGroup group; - private boolean isSaved = false; - - public RemoveGroupPolicy(StdPDPGroup group) { - - this.group = group; - - } - - public void prepareToRemove(PDPPolicy policy) { - - if (this.group == null) { - return; - } - setRemoveGroupPolicy(new PDPPolicyContainer(group)); - - RemoveGroupPolicy.policyContainer.removeItem(policy); - - self.doSave(); - - self.isSaved = true; - - } - - private static void setRemoveGroupPolicy(PDPPolicyContainer pdpPolicyContainer) { + + //Container from where we are fetching the policies + private static PDPPolicyContainer policyContainer; + + private RemoveGroupPolicy self = this; + private StdPDPGroup updatedObject; + private final StdPDPGroup group; + private boolean isSaved = false; + + public RemoveGroupPolicy(StdPDPGroup group) { + + this.group = group; + + } + + public void prepareToRemove(PDPPolicy policy) { + + if (this.group == null) { + return; + } + setRemoveGroupPolicy(new PDPPolicyContainer(group)); + + RemoveGroupPolicy.policyContainer.removeItem(policy); + + self.doSave(); + + self.isSaved = true; + + } + + private static void setRemoveGroupPolicy(PDPPolicyContainer pdpPolicyContainer) { RemoveGroupPolicy.policyContainer = pdpPolicyContainer; } @SuppressWarnings("unchecked") - protected void doSave() { - if (this.group == null) { - return; - } - - StdPDPGroup updatedGroupObject = new StdPDPGroup( - group.getId(), - group.isDefaultGroup(), - group.getName(), - group.getDescription(), - null); - - // replace the original set of Policies with the set from the container (possibly modified by the user) - Set<PDPPolicy> changedPolicies = new HashSet<>(); - changedPolicies.addAll((Collection<PDPPolicy>) RemoveGroupPolicy.policyContainer.getItemIds()); - updatedGroupObject.setPolicies(changedPolicies); - updatedGroupObject.setOnapPdps(this.group.getOnapPdps()); - - // replace the original set of PIP Configs with the set from the container - updatedGroupObject.setPipConfigs(this.group.getPipConfigs()); - - // copy those things that the user cannot change from the original to the new object - updatedGroupObject.setStatus(this.group.getStatus()); - - this.updatedObject = updatedGroupObject; - } - - public boolean isRemoved() { - return this.isSaved; - } - - public OnapPDPGroup getUpdatedObject() { - return this.updatedObject; - } + protected void doSave() { + if (this.group == null) { + return; + } + + StdPDPGroup updatedGroupObject = new StdPDPGroup( + group.getId(), + group.isDefaultGroup(), + group.getName(), + group.getDescription(), + null); + + // replace the original set of Policies with the set from the container (possibly modified by the user) + Set<PDPPolicy> changedPolicies = new HashSet<>(); + changedPolicies.addAll((Collection<PDPPolicy>) RemoveGroupPolicy.policyContainer.getItemIds()); + updatedGroupObject.setPolicies(changedPolicies); + updatedGroupObject.setOnapPdps(this.group.getOnapPdps()); + + // replace the original set of PIP Configs with the set from the container + updatedGroupObject.setPipConfigs(this.group.getPipConfigs()); + + // copy those things that the user cannot change from the original to the new object + updatedGroupObject.setStatus(this.group.getStatus()); + + this.updatedObject = updatedGroupObject; + } + + public boolean isRemoved() { + return this.isSaved; + } + + public OnapPDPGroup getUpdatedObject() { + return this.updatedObject; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index a6cda5e68..951f25c25 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -76,428 +76,428 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RequestMapping("/") public class PolicyCreation extends AbstractPolicyCreation{ - private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); - - private String ruleID = ""; - private PolicyDBDao policyDBDao; - String CLName = null; - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - PolicyCreation.commonClassDao = commonClassDao; - } - - @Autowired - public PolicyCreation(CommonClassDao commonClassDao){ - PolicyCreation.commonClassDao = commonClassDao; - } - - public PolicyCreation(){} - - @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response){ - String body = null; - HttpStatus status = HttpStatus.BAD_REQUEST; - Map<String, String> successMap = new HashMap<>(); - Map<String, String> attributeMap = new HashMap<>(); - PolicyVersion policyVersionDao; - try { - - Policy newPolicy = null; - String policyConfigType = null; - String userId = policyData.getUserId(); - - if (policyData.getTtlDate()==null){ - policyData.setTtlDate("NA"); - }else{ - String dateTTL = policyData.getTtlDate(); - String newDate = convertDate(dateTTL); - policyData.setTtlDate(newDate); - } - - String policyType = policyData.getPolicyType(); - - String filePrefix = null; - if ("Config".equalsIgnoreCase(policyType)) { - policyConfigType = policyData.getConfigPolicyType(); - if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { - filePrefix = "Config_FW_"; - }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { - filePrefix = "Config_Fault_"; - }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { - filePrefix = "Config_PM_"; - }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { - filePrefix = "Config_MS_"; - }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { - filePrefix = "Config_OOF_"; - }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { - filePrefix = "Config_BRMS_Raw_"; - }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { - filePrefix = "Config_BRMS_Param_"; - }else { - filePrefix = "Config_"; - } - } else if ("Action".equalsIgnoreCase(policyType)) { - filePrefix = "Action_"; - } else if ("Decision".equalsIgnoreCase(policyType)) { - filePrefix = "Decision_"; - } - - int version = 0; - int highestVersion = 0; - String createdBy; - String modifiedBy; - String scopeCheck = policyData.getDomainDir().replace(".", File.separator); - PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); - if(policyEditorScope == null){ - UserInfo userInfo = new UserInfo(); - userInfo.setUserName("API"); - userInfo.setUserLoginId("API"); - PolicyEditorScopes editorScope = new PolicyEditorScopes(); - editorScope.setScopeName(scopeCheck); - editorScope.setUserCreatedBy(userInfo); - editorScope.setUserModifiedBy(userInfo); - commonClassDao.save(editorScope); - } - //get the highest version of policy from policy version table. - String dbCheckPolicyName = policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); - PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName); - if(policyVersion == null){ - highestVersion = 0; - }else{ - highestVersion = policyVersion.getHigherVersion(); - } - - if(highestVersion != 0 && policyVersion != null){ - if(policyData.isEditPolicy()){ - version = highestVersion +1; - if(userId ==null){ - modifiedBy = "API"; - }else{ - modifiedBy = userId; - } - policyData.setUserId("API"); - createdBy = policyVersion.getCreatedBy(); - policyVersionDao = policyVersion; - policyVersionDao.setActiveVersion(version); - policyVersionDao.setHigherVersion(version); - policyVersionDao.setModifiedBy(modifiedBy); - policyVersionDao.setModifiedDate(new Date()); - }else{ - body = "policyExists"; - status = HttpStatus.CONFLICT; - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "policyExists"); - response.addHeader("policyName", policyData.getPolicyName()); - return new ResponseEntity<>(body, status); - } - }else{ - // if policy does not exist and the request is updatePolicy return error - if(policyData.isEditPolicy()){ - body = "policyNotAvailableForEdit"; - status = HttpStatus.NOT_FOUND; - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - response.addHeader("error", body); - response.addHeader("message", policyData.getPolicyName() + " does not exist on the PAP and cannot be updated."); - return new ResponseEntity<>(body, status); - } - version = 1; - if(userId == null){ - createdBy = "API"; - modifiedBy = "API"; - policyData.setUserId("API"); - }else{ - createdBy = userId; - modifiedBy = userId; - policyData.setUserId("API"); - } - policyVersionDao = new PolicyVersion(); - policyVersionDao.setPolicyName(dbCheckPolicyName); - policyVersionDao.setActiveVersion(version); - policyVersionDao.setHigherVersion(version); - policyVersionDao.setCreatedBy(createdBy); - policyVersionDao.setModifiedBy(modifiedBy); - } - - policyData.setPolicyID(newPolicyID()); - policyData.setRuleID(ruleID); - - String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml"; - policyData.setNewFileName(policyFileName); - policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); - policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); - if(policyData.getApiflag() == null){ - //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON - if(policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); - attributeMap.put(key, value); - } - } - } - policyData.setDynamicFieldConfigAttributes(attributeMap); - } - - policyData.setVersion(String.valueOf(version)); - policyData.setHighestVersion(version); - - // Calling Component class per policy type - if ("Config".equalsIgnoreCase(policyType)) { - if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { - newPolicy = new FirewallConfigPolicy(policyData); - }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { - policyData.setOnapName("DROOLS"); - policyData.setConfigName("BRMS_RAW_RULE"); - newPolicy = new CreateBrmsRawPolicy(policyData); - }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { - policyData.setOnapName("DROOLS"); - policyData.setConfigName("BRMS_PARAM_RULE"); - Map<String, String> drlRuleAndUIParams = new HashMap<>(); - if(policyData.getApiflag() == null){ - // If there is any dynamic field create the matches here - String key="templateName"; - String value= policyData.getRuleName(); - drlRuleAndUIParams.put(key, value); - if(policyData.getRuleData().size() > 0){ - for(Object keyValue: policyData.getRuleData().keySet()){ - drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); - } - } - policyData.setBrmsParamBody(drlRuleAndUIParams); - }else{ - drlRuleAndUIParams=policyData.getBrmsParamBody(); - String modelName= drlRuleAndUIParams.get("templateName"); - PolicyLogger.info("Template name from API is: "+modelName); - - BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", modelName); - if(template == null){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " - + modelName + " was not found in the dictionary."; - body = message; - status = HttpStatus.BAD_REQUEST; - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("modelName", modelName); - return new ResponseEntity<String>(body, status); - } - } - newPolicy = new CreateBrmsParamPolicy(policyData); - }else if ("Base".equalsIgnoreCase(policyConfigType)) { - newPolicy = new ConfigPolicy(policyData); - }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { - newPolicy = new ClosedLoopPolicy(policyData); - }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { - if(policyData.getApiflag() == null){ - policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); - ObjectMapper jsonMapper = new ObjectMapper(); - String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); - jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); - jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); - policyData.setJsonBody(jsonBody); - } - newPolicy = new CreateClosedLoopPerformanceMetrics(policyData); - }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { - newPolicy = new MicroServiceConfigPolicy(policyData); - }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { - newPolicy = new OptimizationConfigPolicy(policyData); - } - }else if("Action".equalsIgnoreCase(policyType)) { - if(policyData.getApiflag() == null){ - List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); - List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); - List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); - List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); - - - if(!policyData.getRuleAlgorithmschoices().isEmpty()){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); - String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); - dynamicRuleAlgorithmLabels.add(label); - dynamicRuleAlgorithmField1.add(key); - dynamicRuleAlgorithmCombo.add(rule); - dynamicRuleAlgorithmField2.add(value); - } - } - } - - String actionDictValue = policyData.getActionAttributeValue(); - ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue)); - if(jsonData!=null){ - String actionBodyString = jsonData.getBody(); - String actionDictHeader = jsonData.getHeader(); - String actionDictType = jsonData.getType(); - String actionDictUrl = jsonData.getUrl(); - String actionDictMethod = jsonData.getMethod(); - policyData.setActionDictHeader(actionDictHeader); - policyData.setActionDictType(actionDictType); - policyData.setActionDictUrl(actionDictUrl); - policyData.setActionDictMethod(actionDictMethod); - if (actionBodyString != null) { - policyData.setActionBody(actionBodyString); - } - } - policyData.setActionAttribute(actionDictValue); - policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); - policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); - policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); - policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); - }else{ - // API request. - String comboDictValue = policyData.getActionAttribute(); - ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", comboDictValue)); - if(jsonData!=null){ - policyData.setActionBody(jsonData.getBody()); - policyData.setActionDictHeader(jsonData.getHeader()); - policyData.setActionDictType(jsonData.getType()); - policyData.setActionDictUrl(jsonData.getUrl()); - policyData.setActionDictMethod(jsonData.getMethod()); - } - } - newPolicy = new ActionPolicy(policyData, commonClassDao); - } else if ("Decision".equalsIgnoreCase(policyType)) { - if(policyData.getApiflag() == null){ - Map<String, String> settingsMap = new HashMap<>(); - Map<String, String> treatmentMap = new HashMap<>(); - List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); - List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); - List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); - List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); - List<Object> dynamicVariableList = new LinkedList<>(); - List<String> dataTypeList = new LinkedList<>(); - List<String> errorCodeList = new LinkedList<>(); - List<String> treatmentList = new LinkedList<>(); - - if(!policyData.getSettings().isEmpty()){ - for(Object settingsData : policyData.getSettings()){ - if(settingsData instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) settingsData).get("key").toString(); - String value = ((LinkedHashMap<?, ?>) settingsData).get("value").toString(); - settingsMap.put(key, value); - } - } - } - if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); - String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); - dynamicRuleAlgorithmLabels.add(label); - dynamicRuleAlgorithmField1.add(key); - dynamicRuleAlgorithmCombo.add(rule); - dynamicRuleAlgorithmField2.add(value); - } - } - } - if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)) - && policyData.getYamlparams()!=null){ - attributeMap.put("actor", policyData.getYamlparams().getActor()); - attributeMap.put("recipe", policyData.getYamlparams().getRecipe()); - attributeMap.put("clname", policyData.getYamlparams().getClname()); - attributeMap.put("limit", policyData.getYamlparams().getLimit()); - attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow()); - attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits()); - attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart()); - attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd()); - if(policyData.getYamlparams().getBlackList()!=null){ - String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ","); - attributeMap.put("blackList", blackList); - } - if(DecisionPolicy.GUARD_BL_YAML.equals(policyData.getRuleProvider()) && "Use File Upload".equals(policyData.getBlackListEntryType())){ - if(policyData.getBlackListEntries() != null && !policyData.getBlackListEntries().isEmpty()){ - String blackList = StringUtils.join(policyData.getBlackListEntries(), ","); - attributeMap.put("blackList", blackList); - } - if(policyData.getAppendBlackListEntries() != null && !policyData.getAppendBlackListEntries().isEmpty()){ - String blackList = StringUtils.join(policyData.getAppendBlackListEntries(), ","); - attributeMap.put("appendBlackList", blackList); - } - } - if(policyData.getYamlparams().getTargets()!=null){ - String targets = StringUtils.join(policyData.getYamlparams().getTargets(),","); - attributeMap.put("targets", targets); - } - } - if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){ - attributeMap.put("ServiceType", policyData.getRainyday().getServiceType()); - attributeMap.put("VNFType", policyData.getRainyday().getVnfType()); - attributeMap.put("BB_ID", policyData.getRainyday().getBbid()); - attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep()); - - if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){ - for (Object table : policyData.getRainyday().getTreatmentTableChoices()){ - if(table instanceof LinkedHashMap<?,?>){ - String errorcode = ((LinkedHashMap<?,?>) table).get("errorcode").toString(); - String treatment = ((LinkedHashMap<?,?>) table).get("treatment").toString(); - treatmentMap.put(errorcode, treatment); - } - } - } - } - - policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); - policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); - policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); - policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); - policyData.setDynamicVariableList(dynamicVariableList); - policyData.setDynamicSettingsMap(settingsMap); - policyData.setDynamicFieldConfigAttributes(attributeMap); - policyData.setDataTypeList(dataTypeList); - policyData.setRainydayMap(treatmentMap); - policyData.setErrorCodeList(errorCodeList); - policyData.setTreatmentList(treatmentList); - } - newPolicy = new DecisionPolicy(policyData, commonClassDao); - } - - if(newPolicy != null){ - newPolicy.prepareToSave(); - }else{ - body = "error"; - status = HttpStatus.INTERNAL_SERVER_ERROR; - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); - return new ResponseEntity<>(body, status); - } - - PolicyDBDaoTransaction policyDBDaoTransaction = null; - try{ - policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf()); - policyDBDaoTransaction = policyDBDao.getNewTransaction(); - policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); - successMap = newPolicy.savePolicies(); - if(successMap.containsKey("success")){ - policyDBDaoTransaction.commitTransaction(); - if(policyData.isEditPolicy()){ - commonClassDao.update(policyVersionDao); - }else{ - commonClassDao.save(policyVersionDao); - } - try{ - PolicyElasticSearchController search= new PolicyElasticSearchController(); - search.updateElk(policyData); - }catch(Exception e){ - LOGGER.error("Error Occured while saving policy to Elastic Database"+e); - } - body = "success"; - status = HttpStatus.OK; - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("policyName", policyData.getNewFileName()); - + private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); + + private String ruleID = ""; + private PolicyDBDao policyDBDao; + String CLName = null; + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + PolicyCreation.commonClassDao = commonClassDao; + } + + @Autowired + public PolicyCreation(CommonClassDao commonClassDao){ + PolicyCreation.commonClassDao = commonClassDao; + } + + public PolicyCreation(){} + + @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response){ + String body = null; + HttpStatus status = HttpStatus.BAD_REQUEST; + Map<String, String> successMap = new HashMap<>(); + Map<String, String> attributeMap = new HashMap<>(); + PolicyVersion policyVersionDao; + try { + + Policy newPolicy = null; + String policyConfigType = null; + String userId = policyData.getUserId(); + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + String policyType = policyData.getPolicyType(); + + String filePrefix = null; + if ("Config".equalsIgnoreCase(policyType)) { + policyConfigType = policyData.getConfigPolicyType(); + if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_FW_"; + }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_Fault_"; + }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_PM_"; + }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_MS_"; + }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_OOF_"; + }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_BRMS_Raw_"; + }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { + filePrefix = "Config_BRMS_Param_"; + }else { + filePrefix = "Config_"; + } + } else if ("Action".equalsIgnoreCase(policyType)) { + filePrefix = "Action_"; + } else if ("Decision".equalsIgnoreCase(policyType)) { + filePrefix = "Decision_"; + } + + int version = 0; + int highestVersion = 0; + String createdBy; + String modifiedBy; + String scopeCheck = policyData.getDomainDir().replace(".", File.separator); + PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); + if(policyEditorScope == null){ + UserInfo userInfo = new UserInfo(); + userInfo.setUserName("API"); + userInfo.setUserLoginId("API"); + PolicyEditorScopes editorScope = new PolicyEditorScopes(); + editorScope.setScopeName(scopeCheck); + editorScope.setUserCreatedBy(userInfo); + editorScope.setUserModifiedBy(userInfo); + commonClassDao.save(editorScope); + } + //get the highest version of policy from policy version table. + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); + PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName); + if(policyVersion == null){ + highestVersion = 0; + }else{ + highestVersion = policyVersion.getHigherVersion(); + } + + if(highestVersion != 0 && policyVersion != null){ + if(policyData.isEditPolicy()){ + version = highestVersion +1; + if(userId ==null){ + modifiedBy = "API"; + }else{ + modifiedBy = userId; + } + policyData.setUserId("API"); + createdBy = policyVersion.getCreatedBy(); + policyVersionDao = policyVersion; + policyVersionDao.setActiveVersion(version); + policyVersionDao.setHigherVersion(version); + policyVersionDao.setModifiedBy(modifiedBy); + policyVersionDao.setModifiedDate(new Date()); + }else{ + body = "policyExists"; + status = HttpStatus.CONFLICT; + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader("error", "policyExists"); + response.addHeader("policyName", policyData.getPolicyName()); + return new ResponseEntity<>(body, status); + } + }else{ + // if policy does not exist and the request is updatePolicy return error + if(policyData.isEditPolicy()){ + body = "policyNotAvailableForEdit"; + status = HttpStatus.NOT_FOUND; + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + response.addHeader("error", body); + response.addHeader("message", policyData.getPolicyName() + " does not exist on the PAP and cannot be updated."); + return new ResponseEntity<>(body, status); + } + version = 1; + if(userId == null){ + createdBy = "API"; + modifiedBy = "API"; + policyData.setUserId("API"); + }else{ + createdBy = userId; + modifiedBy = userId; + policyData.setUserId("API"); + } + policyVersionDao = new PolicyVersion(); + policyVersionDao.setPolicyName(dbCheckPolicyName); + policyVersionDao.setActiveVersion(version); + policyVersionDao.setHigherVersion(version); + policyVersionDao.setCreatedBy(createdBy); + policyVersionDao.setModifiedBy(modifiedBy); + } + + policyData.setPolicyID(newPolicyID()); + policyData.setRuleID(ruleID); + + String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml"; + policyData.setNewFileName(policyFileName); + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); + if(policyData.getApiflag() == null){ + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + if(policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); + attributeMap.put(key, value); + } + } + } + policyData.setDynamicFieldConfigAttributes(attributeMap); + } + + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + + // Calling Component class per policy type + if ("Config".equalsIgnoreCase(policyType)) { + if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { + newPolicy = new FirewallConfigPolicy(policyData); + }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { + policyData.setOnapName("DROOLS"); + policyData.setConfigName("BRMS_RAW_RULE"); + newPolicy = new CreateBrmsRawPolicy(policyData); + }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { + policyData.setOnapName("DROOLS"); + policyData.setConfigName("BRMS_PARAM_RULE"); + Map<String, String> drlRuleAndUIParams = new HashMap<>(); + if(policyData.getApiflag() == null){ + // If there is any dynamic field create the matches here + String key="templateName"; + String value= policyData.getRuleName(); + drlRuleAndUIParams.put(key, value); + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); + } + } + policyData.setBrmsParamBody(drlRuleAndUIParams); + }else{ + drlRuleAndUIParams=policyData.getBrmsParamBody(); + String modelName= drlRuleAndUIParams.get("templateName"); + PolicyLogger.info("Template name from API is: "+modelName); + + BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", modelName); + if(template == null){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + + modelName + " was not found in the dictionary."; + body = message; + status = HttpStatus.BAD_REQUEST; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + response.addHeader("modelName", modelName); + return new ResponseEntity<String>(body, status); + } + } + newPolicy = new CreateBrmsParamPolicy(policyData); + }else if ("Base".equalsIgnoreCase(policyConfigType)) { + newPolicy = new ConfigPolicy(policyData); + }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { + newPolicy = new ClosedLoopPolicy(policyData); + }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { + if(policyData.getApiflag() == null){ + policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); + ObjectMapper jsonMapper = new ObjectMapper(); + String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); + jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); + jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); + policyData.setJsonBody(jsonBody); + } + newPolicy = new CreateClosedLoopPerformanceMetrics(policyData); + }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { + newPolicy = new MicroServiceConfigPolicy(policyData); + }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + newPolicy = new OptimizationConfigPolicy(policyData); + } + }else if("Action".equalsIgnoreCase(policyType)) { + if(policyData.getApiflag() == null){ + List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); + List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); + + + if(!policyData.getRuleAlgorithmschoices().isEmpty()){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); + String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + + String actionDictValue = policyData.getActionAttributeValue(); + ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue)); + if(jsonData!=null){ + String actionBodyString = jsonData.getBody(); + String actionDictHeader = jsonData.getHeader(); + String actionDictType = jsonData.getType(); + String actionDictUrl = jsonData.getUrl(); + String actionDictMethod = jsonData.getMethod(); + policyData.setActionDictHeader(actionDictHeader); + policyData.setActionDictType(actionDictType); + policyData.setActionDictUrl(actionDictUrl); + policyData.setActionDictMethod(actionDictMethod); + if (actionBodyString != null) { + policyData.setActionBody(actionBodyString); + } + } + policyData.setActionAttribute(actionDictValue); + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + }else{ + // API request. + String comboDictValue = policyData.getActionAttribute(); + ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", comboDictValue)); + if(jsonData!=null){ + policyData.setActionBody(jsonData.getBody()); + policyData.setActionDictHeader(jsonData.getHeader()); + policyData.setActionDictType(jsonData.getType()); + policyData.setActionDictUrl(jsonData.getUrl()); + policyData.setActionDictMethod(jsonData.getMethod()); + } + } + newPolicy = new ActionPolicy(policyData, commonClassDao); + } else if ("Decision".equalsIgnoreCase(policyType)) { + if(policyData.getApiflag() == null){ + Map<String, String> settingsMap = new HashMap<>(); + Map<String, String> treatmentMap = new HashMap<>(); + List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); + List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); + List<Object> dynamicVariableList = new LinkedList<>(); + List<String> dataTypeList = new LinkedList<>(); + List<String> errorCodeList = new LinkedList<>(); + List<String> treatmentList = new LinkedList<>(); + + if(!policyData.getSettings().isEmpty()){ + for(Object settingsData : policyData.getSettings()){ + if(settingsData instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) settingsData).get("key").toString(); + String value = ((LinkedHashMap<?, ?>) settingsData).get("value").toString(); + settingsMap.put(key, value); + } + } + } + if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); + String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)) + && policyData.getYamlparams()!=null){ + attributeMap.put("actor", policyData.getYamlparams().getActor()); + attributeMap.put("recipe", policyData.getYamlparams().getRecipe()); + attributeMap.put("clname", policyData.getYamlparams().getClname()); + attributeMap.put("limit", policyData.getYamlparams().getLimit()); + attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow()); + attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits()); + attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart()); + attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd()); + if(policyData.getYamlparams().getBlackList()!=null){ + String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ","); + attributeMap.put("blackList", blackList); + } + if(DecisionPolicy.GUARD_BL_YAML.equals(policyData.getRuleProvider()) && "Use File Upload".equals(policyData.getBlackListEntryType())){ + if(policyData.getBlackListEntries() != null && !policyData.getBlackListEntries().isEmpty()){ + String blackList = StringUtils.join(policyData.getBlackListEntries(), ","); + attributeMap.put("blackList", blackList); + } + if(policyData.getAppendBlackListEntries() != null && !policyData.getAppendBlackListEntries().isEmpty()){ + String blackList = StringUtils.join(policyData.getAppendBlackListEntries(), ","); + attributeMap.put("appendBlackList", blackList); + } + } + if(policyData.getYamlparams().getTargets()!=null){ + String targets = StringUtils.join(policyData.getYamlparams().getTargets(),","); + attributeMap.put("targets", targets); + } + } + if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){ + attributeMap.put("ServiceType", policyData.getRainyday().getServiceType()); + attributeMap.put("VNFType", policyData.getRainyday().getVnfType()); + attributeMap.put("BB_ID", policyData.getRainyday().getBbid()); + attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep()); + + if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){ + for (Object table : policyData.getRainyday().getTreatmentTableChoices()){ + if(table instanceof LinkedHashMap<?,?>){ + String errorcode = ((LinkedHashMap<?,?>) table).get("errorcode").toString(); + String treatment = ((LinkedHashMap<?,?>) table).get("treatment").toString(); + treatmentMap.put(errorcode, treatment); + } + } + } + } + + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + policyData.setDynamicVariableList(dynamicVariableList); + policyData.setDynamicSettingsMap(settingsMap); + policyData.setDynamicFieldConfigAttributes(attributeMap); + policyData.setDataTypeList(dataTypeList); + policyData.setRainydayMap(treatmentMap); + policyData.setErrorCodeList(errorCodeList); + policyData.setTreatmentList(treatmentList); + } + newPolicy = new DecisionPolicy(policyData, commonClassDao); + } + + if(newPolicy != null){ + newPolicy.prepareToSave(); + }else{ + body = "error"; + status = HttpStatus.INTERNAL_SERVER_ERROR; + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "error"); + return new ResponseEntity<>(body, status); + } + + PolicyDBDaoTransaction policyDBDaoTransaction = null; + try{ + policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf()); + policyDBDaoTransaction = policyDBDao.getNewTransaction(); + policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); + successMap = newPolicy.savePolicies(); + if(successMap.containsKey("success")){ + policyDBDaoTransaction.commitTransaction(); + if(policyData.isEditPolicy()){ + commonClassDao.update(policyVersionDao); + }else{ + commonClassDao.save(policyVersionDao); + } + try{ + PolicyElasticSearchController search= new PolicyElasticSearchController(); + search.updateElk(policyData); + }catch(Exception e){ + LOGGER.error("Error Occured while saving policy to Elastic Database"+e); + } + body = "success"; + status = HttpStatus.OK; + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("policyName", policyData.getNewFileName()); + //get message from the SafetyCheckerResults if present String safetyCheckerResponse = policyData.getClWarning(); String existingCLName = policyData.getExistingCLName(); @@ -512,77 +512,77 @@ public class PolicyCreation extends AbstractPolicyCreation{ PolicyLogger.info("SafetyCheckerResponse was empty or null."); } - }else if (successMap.containsKey("invalidAttribute")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table."); - body = "invalidAttribute"; - status = HttpStatus.BAD_REQUEST; - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("invalidAttribute", policyData.getActionAttribute()); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - }else if (successMap.containsKey("fwdberror")) { - policyDBDaoTransaction.rollbackTransaction(); - body = "fwdberror"; - status = HttpStatus.BAD_REQUEST; - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + }else if (successMap.containsKey("invalidAttribute")) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table."); + body = "invalidAttribute"; + status = HttpStatus.BAD_REQUEST; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("invalidAttribute", policyData.getActionAttribute()); + response.addHeader("error", message); + response.addHeader("policyName", policyData.getPolicyName()); + }else if (successMap.containsKey("fwdberror")) { + policyDBDaoTransaction.rollbackTransaction(); + body = "fwdberror"; + status = HttpStatus.BAD_REQUEST; + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error when inserting Firewall ConfigBody data into the database."; - PolicyLogger.error(message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - } else if (successMap.get("error").equals("Validation Failed")) { + PolicyLogger.error(message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + response.addHeader("policyName", policyData.getPolicyName()); + } else if (successMap.get("error").equals("Validation Failed")) { policyDBDaoTransaction.rollbackTransaction(); String message = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Error Validating the Policy on the PAP."; + + "Error Validating the Policy on the PAP."; PolicyLogger.error(message); body = "Validation"; - status = HttpStatus.BAD_REQUEST; + status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", message); response.addHeader("policyName", policyData.getPolicyName()); }else { - policyDBDaoTransaction.rollbackTransaction(); - body = "error"; - status = HttpStatus.INTERNAL_SERVER_ERROR; - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); - } - }catch(Exception e){ - LOGGER.error("Exception Occured : ",e); - if(policyDBDaoTransaction != null){ - policyDBDaoTransaction.rollbackTransaction(); - } - } - } - catch (Exception e){ - LOGGER.error("Exception Occured : "+e.getMessage(),e); - body = "error"; - response.addHeader("error", e.getMessage()); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - return new ResponseEntity<>(body, status); - } - - @ExceptionHandler({ HttpMessageNotReadableException.class }) - public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { - LOGGER.error("Request not readable: {}", exception); - StringBuilder message = new StringBuilder(); - message.append(exception.getMessage()); - if (exception.getCause() != null) { - message.append(" Reason Caused: " - + exception.getCause().getMessage()); - } - return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); - } - - public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){ - PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); - if (entityItem != null) { - if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ - return entityItem; - } - } - return entityItem; - } + policyDBDaoTransaction.rollbackTransaction(); + body = "error"; + status = HttpStatus.INTERNAL_SERVER_ERROR; + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "error"); + } + }catch(Exception e){ + LOGGER.error("Exception Occured : ",e); + if(policyDBDaoTransaction != null){ + policyDBDaoTransaction.rollbackTransaction(); + } + } + } + catch (Exception e){ + LOGGER.error("Exception Occured : "+e.getMessage(),e); + body = "error"; + response.addHeader("error", e.getMessage()); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return new ResponseEntity<>(body, status); + } + + @ExceptionHandler({ HttpMessageNotReadableException.class }) + public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { + LOGGER.error("Request not readable: {}", exception); + StringBuilder message = new StringBuilder(); + message.append(exception.getMessage()); + if (exception.getCause() != null) { + message.append(" Reason Caused: " + + exception.getCause().getMessage()); + } + return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); + } + + public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){ + PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); + if (entityItem != null) { + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + return entityItem; + } + } + return entityItem; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java index cb03d44ec..e965356be 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java @@ -42,433 +42,433 @@ import org.springframework.web.servlet.ModelAndView; @Service("DictionaryService") public class DictionaryService { - /* - * Methods that call the controller method directly to Save and Update dictionary data - */ - public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { - - DictionaryController dictionary = new DictionaryController(); - ModelAndView result = dictionary.saveOnapDictionary(request, response); - return result.getViewName(); - } - - public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - DictionaryController dictionary = new DictionaryController(); - ModelAndView result = dictionary.saveAttributeDictionary(request, response); - return result.getViewName(); - } - - public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { - - ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - ModelAndView result = action.saveActionPolicyDictionary(request, response); - return result.getViewName(); - } - - public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { - - BRMSDictionaryController dictionary = new BRMSDictionaryController(); - ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); - return result.getViewName(); - } - - public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVSCLAction(request, response); - return result.getViewName(); - } - - public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVnfType(request, response); - return result.getViewName(); - } - - public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.savePEPOptions(request, response); - return result.getViewName(); - } - - public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVarbind(request, response); - return result.getViewName(); - } - - public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveServiceType(request, response); - return result.getViewName(); - } - - public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveSiteType(request, response); - return result.getViewName(); - } - - public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - ModelAndView result = dictionary.saveSettingsDictionary(request, response); - return result.getViewName(); - } - - public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - ModelAndView result = dictionary.saveRainyDayDictionary(request, response); - return result.getViewName(); - } - - public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); - return result.getViewName(); - } - - public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveActionListDictionary(request, response); - return result.getViewName(); - } - - public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveProtocolListDictionary(request, response); - return result.getViewName(); - } - - public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveZoneDictionary(request, response); - return result.getViewName(); - } - - public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); - return result.getViewName(); - } - - public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.savePrefixListDictionary(request, response); - return result.getViewName(); - } - - public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); - return result.getViewName(); - } - - public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); - return result.getViewName(); - } - - public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveServiceListDictionary(request, response); - return result.getViewName(); - } - - public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveTermListDictionary(request, response); - return result.getViewName(); - } - - - - - public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); - return result.getViewName(); - } - - public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); - return result.getViewName(); - } - - public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); - return result.getViewName(); - } - - public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); - return result.getViewName(); - } - - public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); - return result.getViewName(); - } - - public String saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); - ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response); - return result.getViewName(); - } - - public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSServiceDictionary(request, response); - return result.getViewName(); - } - - public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSResourceDictionary(request, response); - return result.getViewName(); - } - - public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSTypeDictionary(request, response); - return result.getViewName(); - } - - public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); - return result.getViewName(); - } - - public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); - return result.getViewName(); - } - - public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - - SafePolicyController dictionary = new SafePolicyController(); - ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); - return result.getViewName(); - } - - public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - SafePolicyController dictionary = new SafePolicyController(); - ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); - return result.getViewName(); - } - - - /* - * Methods that call the controller get methods directly to get dictionary data - */ - public void getOnapDictionary(HttpServletResponse response){ - DictionaryController dictionary = new DictionaryController(); - dictionary.getOnapNameDictionaryEntityData(response); - } - - public void getAttributeDictionary(HttpServletResponse response){ - DictionaryController dictionary = new DictionaryController(); - dictionary.getAttributeDictionaryEntityData(response); - } - - public void getActionPolicyDictionary(HttpServletResponse response){ - ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - action.getActionPolicyDictionaryEntityData(response); - } - - public void getBRMSParamDictionary(HttpServletResponse response){ - BRMSDictionaryController dictionary = new BRMSDictionaryController(); - dictionary.getBRMSParamDictionaryEntityData(response); - } - - public void getVSCLAction(HttpServletResponse response){ - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVSCLActionDictionaryEntityData(response); - } - - public void getVnfType(HttpServletResponse response){ - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVNFTypeDictionaryEntityData(response); - } - - public void getPEPOptions(HttpServletResponse response){ - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getPEPOptionsDictionaryEntityData(response); - } - - public void getVarbind(HttpServletResponse response){ - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVarbindDictionaryEntityData(response); - } - - public void getServiceType(HttpServletResponse response){ - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getClosedLoopServiceDictionaryEntityData(response); - } - - public void getSiteType(HttpServletResponse response){ - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getClosedLoopSiteDictionaryEntityData(response); - } - - public void getSettingsDictionary(HttpServletResponse response){ - DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - dictionary.getSettingsDictionaryEntityData(response); - } - - public void getRainyDayDictionary(HttpServletResponse response){ - DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - dictionary.getRainyDayDictionaryEntityData(response); - } - - public void getDescriptiveDictionary(HttpServletResponse response){ - DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - dictionary.getDescriptiveDictionaryEntityData(response); - } - - public void getActionListDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getActionListDictionaryEntityData(response); - } - - public void getProtocolListDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getProtocolListDictionaryEntityData(response); - } - - public void getZoneDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getZoneDictionaryEntityData(response); - } - - public void getSecurityZoneDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getSecurityZoneDictionaryEntityData(response); - } - - public void getPrefixListDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getPrefixListDictionaryEntityData(response); - } - - public void getAddressGroupDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getAddressGroupDictionaryEntityData(response); - } - - public void getServiceGroupDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getServiceGroupDictionaryEntityData(response); - } - - public void getServiceListDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getServiceListDictionaryEntityData(response); - } - - public void getTermListDictionary(HttpServletResponse response){ - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getTermListDictionaryEntityData(response); - } - - - public void getMicroServiceLocationDictionary(HttpServletResponse response){ - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceLocationDictionaryEntityData(response); - } - - public void getMicroServiceConfigNameDictionary(HttpServletResponse response){ - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceConfigNameDictionaryEntityData(response); - } - - public void getDCAEUUIDDictionary(HttpServletResponse response){ - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getDCAEUUIDDictionaryEntityData(response); - } - - public void getMicroServiceModelsDictionary(HttpServletResponse response){ - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceModelsDictionaryEntityData(response); - } - - public void getMicroServiceDictionary(HttpServletResponse response){ - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceModelsDictionaryEntityData(response); - } - - public void getOptimizationModelsDictionary(HttpServletResponse response){ - OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); - dictionary.getOptimizationModelsDictionaryEntityData(response); - } - - public void getPSServiceDictionary(HttpServletResponse response){ - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSServiceEntityData(response); - } - - public void getPSResourceDictionary(HttpServletResponse response){ - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSResourceEntityData(response); - } - - public void getPSTypeDictionary(HttpServletResponse response){ - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSTypeEntityData(response); - } - - public void getPSClosedLoopDictionary(HttpServletResponse response){ - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSClosedLoopEntityData(response); - } - - public void getPSGroupScopeDictionary(HttpServletResponse response){ - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getGroupPolicyScopeEntityData(response); - } - - public void getRiskTypeDictionary(HttpServletResponse response){ - SafePolicyController dictionary = new SafePolicyController(); - dictionary.getRiskTypeDictionaryEntityData(response); - } - - public void getSafePolicyWarningDictionary(HttpServletResponse response) { - SafePolicyController dictionary = new SafePolicyController(); - dictionary.getSafePolicyWarningeEntityData(response); - } + /* + * Methods that call the controller method directly to Save and Update dictionary data + */ + public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + + DictionaryController dictionary = new DictionaryController(); + ModelAndView result = dictionary.saveOnapDictionary(request, response); + return result.getViewName(); + } + + public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + DictionaryController dictionary = new DictionaryController(); + ModelAndView result = dictionary.saveAttributeDictionary(request, response); + return result.getViewName(); + } + + public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + + ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); + ModelAndView result = action.saveActionPolicyDictionary(request, response); + return result.getViewName(); + } + + public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + + BRMSDictionaryController dictionary = new BRMSDictionaryController(); + ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); + return result.getViewName(); + } + + public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + ModelAndView result = dictionary.saveVSCLAction(request, response); + return result.getViewName(); + } + + public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + ModelAndView result = dictionary.saveVnfType(request, response); + return result.getViewName(); + } + + public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + ModelAndView result = dictionary.savePEPOptions(request, response); + return result.getViewName(); + } + + public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + ModelAndView result = dictionary.saveVarbind(request, response); + return result.getViewName(); + } + + public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + ModelAndView result = dictionary.saveServiceType(request, response); + return result.getViewName(); + } + + public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + ModelAndView result = dictionary.saveSiteType(request, response); + return result.getViewName(); + } + + public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); + ModelAndView result = dictionary.saveSettingsDictionary(request, response); + return result.getViewName(); + } + + public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); + ModelAndView result = dictionary.saveRainyDayDictionary(request, response); + return result.getViewName(); + } + + public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); + ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); + return result.getViewName(); + } + + public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveActionListDictionary(request, response); + return result.getViewName(); + } + + public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveProtocolListDictionary(request, response); + return result.getViewName(); + } + + public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveZoneDictionary(request, response); + return result.getViewName(); + } + + public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); + return result.getViewName(); + } + + public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.savePrefixListDictionary(request, response); + return result.getViewName(); + } + + public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); + return result.getViewName(); + } + + public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); + return result.getViewName(); + } + + public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveServiceListDictionary(request, response); + return result.getViewName(); + } + + public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + ModelAndView result = dictionary.saveTermListDictionary(request, response); + return result.getViewName(); + } + + + + + public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); + return result.getViewName(); + } + + public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); + return result.getViewName(); + } + + public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); + return result.getViewName(); + } + + public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); + return result.getViewName(); + } + + public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); + return result.getViewName(); + } + + public String saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); + ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response); + return result.getViewName(); + } + + public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + ModelAndView result = dictionary.savePSServiceDictionary(request, response); + return result.getViewName(); + } + + public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + ModelAndView result = dictionary.savePSResourceDictionary(request, response); + return result.getViewName(); + } + + public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + ModelAndView result = dictionary.savePSTypeDictionary(request, response); + return result.getViewName(); + } + + public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); + return result.getViewName(); + } + + public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); + return result.getViewName(); + } + + public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + SafePolicyController dictionary = new SafePolicyController(); + ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); + return result.getViewName(); + } + + public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + SafePolicyController dictionary = new SafePolicyController(); + ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); + return result.getViewName(); + } + + + /* + * Methods that call the controller get methods directly to get dictionary data + */ + public void getOnapDictionary(HttpServletResponse response){ + DictionaryController dictionary = new DictionaryController(); + dictionary.getOnapNameDictionaryEntityData(response); + } + + public void getAttributeDictionary(HttpServletResponse response){ + DictionaryController dictionary = new DictionaryController(); + dictionary.getAttributeDictionaryEntityData(response); + } + + public void getActionPolicyDictionary(HttpServletResponse response){ + ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); + action.getActionPolicyDictionaryEntityData(response); + } + + public void getBRMSParamDictionary(HttpServletResponse response){ + BRMSDictionaryController dictionary = new BRMSDictionaryController(); + dictionary.getBRMSParamDictionaryEntityData(response); + } + + public void getVSCLAction(HttpServletResponse response){ + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + dictionary.getVSCLActionDictionaryEntityData(response); + } + + public void getVnfType(HttpServletResponse response){ + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + dictionary.getVNFTypeDictionaryEntityData(response); + } + + public void getPEPOptions(HttpServletResponse response){ + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + dictionary.getPEPOptionsDictionaryEntityData(response); + } + + public void getVarbind(HttpServletResponse response){ + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + dictionary.getVarbindDictionaryEntityData(response); + } + + public void getServiceType(HttpServletResponse response){ + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + dictionary.getClosedLoopServiceDictionaryEntityData(response); + } + + public void getSiteType(HttpServletResponse response){ + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + dictionary.getClosedLoopSiteDictionaryEntityData(response); + } + + public void getSettingsDictionary(HttpServletResponse response){ + DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); + dictionary.getSettingsDictionaryEntityData(response); + } + + public void getRainyDayDictionary(HttpServletResponse response){ + DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); + dictionary.getRainyDayDictionaryEntityData(response); + } + + public void getDescriptiveDictionary(HttpServletResponse response){ + DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); + dictionary.getDescriptiveDictionaryEntityData(response); + } + + public void getActionListDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getActionListDictionaryEntityData(response); + } + + public void getProtocolListDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getProtocolListDictionaryEntityData(response); + } + + public void getZoneDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getZoneDictionaryEntityData(response); + } + + public void getSecurityZoneDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getSecurityZoneDictionaryEntityData(response); + } + + public void getPrefixListDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getPrefixListDictionaryEntityData(response); + } + + public void getAddressGroupDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getAddressGroupDictionaryEntityData(response); + } + + public void getServiceGroupDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getServiceGroupDictionaryEntityData(response); + } + + public void getServiceListDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getServiceListDictionaryEntityData(response); + } + + public void getTermListDictionary(HttpServletResponse response){ + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + dictionary.getTermListDictionaryEntityData(response); + } + + + public void getMicroServiceLocationDictionary(HttpServletResponse response){ + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + dictionary.getMicroServiceLocationDictionaryEntityData(response); + } + + public void getMicroServiceConfigNameDictionary(HttpServletResponse response){ + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + dictionary.getMicroServiceConfigNameDictionaryEntityData(response); + } + + public void getDCAEUUIDDictionary(HttpServletResponse response){ + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + dictionary.getDCAEUUIDDictionaryEntityData(response); + } + + public void getMicroServiceModelsDictionary(HttpServletResponse response){ + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + dictionary.getMicroServiceModelsDictionaryEntityData(response); + } + + public void getMicroServiceDictionary(HttpServletResponse response){ + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + dictionary.getMicroServiceModelsDictionaryEntityData(response); + } + + public void getOptimizationModelsDictionary(HttpServletResponse response){ + OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); + dictionary.getOptimizationModelsDictionaryEntityData(response); + } + + public void getPSServiceDictionary(HttpServletResponse response){ + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + dictionary.getPSServiceEntityData(response); + } + + public void getPSResourceDictionary(HttpServletResponse response){ + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + dictionary.getPSResourceEntityData(response); + } + + public void getPSTypeDictionary(HttpServletResponse response){ + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + dictionary.getPSTypeEntityData(response); + } + + public void getPSClosedLoopDictionary(HttpServletResponse response){ + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + dictionary.getPSClosedLoopEntityData(response); + } + + public void getPSGroupScopeDictionary(HttpServletResponse response){ + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + dictionary.getGroupPolicyScopeEntityData(response); + } + + public void getRiskTypeDictionary(HttpServletResponse response){ + SafePolicyController dictionary = new SafePolicyController(); + dictionary.getRiskTypeDictionaryEntityData(response); + } + + public void getSafePolicyWarningDictionary(HttpServletResponse response) { + SafePolicyController dictionary = new SafePolicyController(); + dictionary.getSafePolicyWarningeEntityData(response); + } }
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java index 7382a77a1..5e4b4ee7d 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java @@ -41,187 +41,187 @@ import org.onap.policy.pap.xacml.rest.components.CreateNewMicroServiceModel; import org.onap.policy.pap.xacml.rest.components.CreateNewOptimizationModel; public class ImportService { - private static final Logger logger = FlexLogger.getLogger(ImportService.class); - private static String errorMessage = "Error in reading in file from API call"; - private static String errorMsg = "error"; - private static String operation = "operation"; - private static String importHeader = "import"; - private static String service = "service"; - private static String extractDir = "ExtractDir"; - private static String successMessage = "success"; - private static String invalidServiceName = "Invalid ServiceName"; - private static final String REGEX = "[0-9a-zA-Z._ ]*"; - private static final String MISSING = "missing"; - - public void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) { - String importServiceCreation = request.getParameter("importService"); - String fileName = request.getParameter("fileName"); - String version = request.getParameter("version"); - String serviceName = request.getParameter("serviceName"); - - if(serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, MISSING); - response.addHeader(operation, importHeader); - response.addHeader(service, invalidServiceName); - return; - } + private static final Logger logger = FlexLogger.getLogger(ImportService.class); + private static String errorMessage = "Error in reading in file from API call"; + private static String errorMsg = "error"; + private static String operation = "operation"; + private static String importHeader = "import"; + private static String service = "service"; + private static String extractDir = "ExtractDir"; + private static String successMessage = "success"; + private static String invalidServiceName = "Invalid ServiceName"; + private static final String REGEX = "[0-9a-zA-Z._ ]*"; + private static final String MISSING = "missing"; - String description = request.getParameter("description"); - Map<String, String> successMap = new HashMap<>(); - if(("BRMSPARAM").equals(importServiceCreation)){ - StringBuilder builder = new StringBuilder(); - int ch; - try { - while((ch = request.getInputStream().read()) != -1){ - builder.append((char)ch); - } - } catch (IOException e) { - logger.error(e); - PolicyLogger.error(errorMessage); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(errorMsg, MISSING); - response.addHeader(operation, importHeader); - response.addHeader(service, serviceName); - } - CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); - successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); - } - else if(("MICROSERVICE").equals(importServiceCreation)){ - CreateNewMicroServiceModel newMS = null; - String randomID = UUID.randomUUID().toString(); - String type = ".xmi"; - if ( fileName != null) { - File extracDir = new File(extractDir); - if (!extracDir.exists()){ - extracDir.mkdirs(); - } - if (fileName.contains(".xmi") || fileName.contains(".yml")){ - if(fileName.contains(".yml")){ - type = ".yml"; - } - // get the request content into a String - String xmi = null; - java.util.Scanner scanner; - try { - scanner = new java.util.Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - xmi = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - } catch (IOException e1) { - logger.error(e1); - PolicyLogger.error(errorMessage); - return; - } - PolicyLogger.info("Request from API to import new Service"); - try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { - writer.write(xmi); - } catch (IOException e) { - logger.error(e); - PolicyLogger.error(errorMessage); - return; - } - }else{ - InputStream inputStream = null; - try(FileOutputStream outputStream = new FileOutputStream(extractDir + File.separator + randomID+".zip")) { - inputStream = request.getInputStream(); - byte[] buffer = new byte[4096]; - int bytesRead = -1 ; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead) ; - } - } catch (IOException e) { - PolicyLogger.error("Error in reading in Zip File from API call"+e); - return; - }finally{ - try { - if(inputStream != null){ - inputStream.close(); - } - } catch (IOException e) { - PolicyLogger.error("Exception Occured while closing the input/output stream"+e); - } - } - } - - newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); - - successMap = newMS.addValuesToNewModel(type); - - if (successMap.containsKey(successMessage)) { - successMap.clear(); - successMap = newMS.saveImportService(); - } - } - } else if(("OPTIMIZATION").equals(importServiceCreation)){ - CreateNewOptimizationModel newOOF = null; - String randomID = UUID.randomUUID().toString(); - if ( fileName != null) { - File extracDir = new File(extractDir); - if (!extracDir.exists()){ - extracDir.mkdirs(); - } - - String type = ".yml"; - - // get the request content into a String - String yml = null; - try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());){ - scanner.useDelimiter("\\A"); - yml = scanner.hasNext() ? scanner.next() : ""; - } catch (IOException e1) { - logger.error(e1); - PolicyLogger.error(errorMessage); - return; - } - PolicyLogger.info("Request from API to import new Optimization Service Model"); - try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { - writer.write(yml); - } catch (IOException e) { - logger.error(e); - PolicyLogger.error(errorMessage); - return; - } - - newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID); - successMap = newOOF.addValuesToNewModel(); - if (successMap.containsKey(successMessage)) { - successMap.clear(); - successMap = newOOF.saveImportService(); - } - } - } - - // return a response to the PAP - if (successMap.containsKey(successMessage)) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", successMessage); - response.addHeader(operation, importHeader); - response.addHeader(service, serviceName); - } else if (successMap.containsKey("DBError")) { - if (successMap.get("DBError").contains("EXISTS")){ - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader(service, serviceName); - response.addHeader(errorMsg, "modelExistsDB"); - }else{ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(errorMsg, "importDB"); - } - response.addHeader(operation, importHeader); - response.addHeader(service, serviceName); - }else if (successMap.get(errorMsg).contains("MISSING")){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(errorMsg, MISSING); - response.addHeader(operation, importHeader); - response.addHeader(service, serviceName); - }else if (successMap.get(errorMsg).contains("VALIDATION")){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader(errorMsg, "validation"); - response.addHeader(operation, importHeader); - response.addHeader(service, serviceName); - } - } + public void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) { + String importServiceCreation = request.getParameter("importService"); + String fileName = request.getParameter("fileName"); + String version = request.getParameter("version"); + String serviceName = request.getParameter("serviceName"); + + if(serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(errorMsg, MISSING); + response.addHeader(operation, importHeader); + response.addHeader(service, invalidServiceName); + return; + } + + String description = request.getParameter("description"); + Map<String, String> successMap = new HashMap<>(); + if(("BRMSPARAM").equals(importServiceCreation)){ + StringBuilder builder = new StringBuilder(); + int ch; + try { + while((ch = request.getInputStream().read()) != -1){ + builder.append((char)ch); + } + } catch (IOException e) { + logger.error(e); + PolicyLogger.error(errorMessage); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader(errorMsg, MISSING); + response.addHeader(operation, importHeader); + response.addHeader(service, serviceName); + } + CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); + successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); + } + else if(("MICROSERVICE").equals(importServiceCreation)){ + CreateNewMicroServiceModel newMS = null; + String randomID = UUID.randomUUID().toString(); + String type = ".xmi"; + if ( fileName != null) { + File extracDir = new File(extractDir); + if (!extracDir.exists()){ + extracDir.mkdirs(); + } + if (fileName.contains(".xmi") || fileName.contains(".yml")){ + if(fileName.contains(".yml")){ + type = ".yml"; + } + // get the request content into a String + String xmi = null; + java.util.Scanner scanner; + try { + scanner = new java.util.Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + xmi = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + } catch (IOException e1) { + logger.error(e1); + PolicyLogger.error(errorMessage); + return; + } + PolicyLogger.info("Request from API to import new Service"); + try (Writer writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { + writer.write(xmi); + } catch (IOException e) { + logger.error(e); + PolicyLogger.error(errorMessage); + return; + } + }else{ + InputStream inputStream = null; + try(FileOutputStream outputStream = new FileOutputStream(extractDir + File.separator + randomID+".zip")) { + inputStream = request.getInputStream(); + byte[] buffer = new byte[4096]; + int bytesRead = -1 ; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead) ; + } + } catch (IOException e) { + PolicyLogger.error("Error in reading in Zip File from API call"+e); + return; + }finally{ + try { + if(inputStream != null){ + inputStream.close(); + } + } catch (IOException e) { + PolicyLogger.error("Exception Occured while closing the input/output stream"+e); + } + } + } + + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); + + successMap = newMS.addValuesToNewModel(type); + + if (successMap.containsKey(successMessage)) { + successMap.clear(); + successMap = newMS.saveImportService(); + } + } + } else if(("OPTIMIZATION").equals(importServiceCreation)){ + CreateNewOptimizationModel newOOF = null; + String randomID = UUID.randomUUID().toString(); + if ( fileName != null) { + File extracDir = new File(extractDir); + if (!extracDir.exists()){ + extracDir.mkdirs(); + } + + String type = ".yml"; + + // get the request content into a String + String yml = null; + try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());){ + scanner.useDelimiter("\\A"); + yml = scanner.hasNext() ? scanner.next() : ""; + } catch (IOException e1) { + logger.error(e1); + PolicyLogger.error(errorMessage); + return; + } + PolicyLogger.info("Request from API to import new Optimization Service Model"); + try (Writer writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { + writer.write(yml); + } catch (IOException e) { + logger.error(e); + PolicyLogger.error(errorMessage); + return; + } + + newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID); + successMap = newOOF.addValuesToNewModel(); + if (successMap.containsKey(successMessage)) { + successMap.clear(); + successMap = newOOF.saveImportService(); + } + } + } + + // return a response to the PAP + if (successMap.containsKey(successMessage)) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", successMessage); + response.addHeader(operation, importHeader); + response.addHeader(service, serviceName); + } else if (successMap.containsKey("DBError")) { + if (successMap.get("DBError").contains("EXISTS")){ + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader(service, serviceName); + response.addHeader(errorMsg, "modelExistsDB"); + }else{ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader(errorMsg, "importDB"); + } + response.addHeader(operation, importHeader); + response.addHeader(service, serviceName); + }else if (successMap.get(errorMsg).contains("MISSING")){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader(errorMsg, MISSING); + response.addHeader(operation, importHeader); + response.addHeader(service, serviceName); + }else if (successMap.get(errorMsg).contains("VALIDATION")){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader(errorMsg, "validation"); + response.addHeader(operation, importHeader); + response.addHeader(service, serviceName); + } + } }
\ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java index 3fff9f266..864201cfe 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java @@ -35,64 +35,64 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup; import com.att.research.xacml.api.pap.PDPPolicy; public class MetricService { - private static String errorMsg = "error"; - /* - * This is a private constructor - * */ - private MetricService(){ - - } - public static void doGetPolicyMetrics(HttpServletResponse response) { - Set<OnapPDPGroup> groups = new HashSet<>(); - try { - //get the count of policies on the PDP - if(XACMLPapServlet.getPAPEngine()!=null){ - groups = XACMLPapServlet.getPAPEngine().getOnapPDPGroups(); - } - int pdpCount = 0; - for (OnapPDPGroup group : groups) { - Set<PDPPolicy> policies = group.getPolicies(); - pdpCount += policies.size(); - } - //get the count of policies on the PAP - EntityManager em = null; - if(XACMLPapServlet.getEmf()!=null){ - em = XACMLPapServlet.getEmf().createEntityManager(); - } - if (em==null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, "Error creating entity manager with persistence unit"); - return; - } - int papCount = ((Number) em.createNamedQuery("PolicyVersion.findAllCount").getSingleResult()).intValue(); - em.close(); - int totalCount = pdpCount + papCount; - //create json string for API response - JSONObject json = new JSONObject(); - json.put("papCount", papCount); - json.put("pdpCount", pdpCount); - json.put("totalCount", totalCount); - if (pdpCount>0 && papCount>0 && totalCount>0) { - PolicyLogger.info("Metrics have been found on the Policy Engine for the number of policies on the PAP and PDP."); - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getMetrics"); - response.addHeader("metrics", json.toString() ); - return; - }else{ - String message = "The policy count on the PAP and PDP is 0. Please check the database and file system to correct this error."; - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, message); - return; - } - } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Querying the Database."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, message); - return; - } - } + private static String errorMsg = "error"; + /* + * This is a private constructor + * */ + private MetricService(){ + + } + public static void doGetPolicyMetrics(HttpServletResponse response) { + Set<OnapPDPGroup> groups = new HashSet<>(); + try { + //get the count of policies on the PDP + if(XACMLPapServlet.getPAPEngine()!=null){ + groups = XACMLPapServlet.getPAPEngine().getOnapPDPGroups(); + } + int pdpCount = 0; + for (OnapPDPGroup group : groups) { + Set<PDPPolicy> policies = group.getPolicies(); + pdpCount += policies.size(); + } + //get the count of policies on the PAP + EntityManager em = null; + if(XACMLPapServlet.getEmf()!=null){ + em = XACMLPapServlet.getEmf().createEntityManager(); + } + if (em==null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(errorMsg, "Error creating entity manager with persistence unit"); + return; + } + int papCount = ((Number) em.createNamedQuery("PolicyVersion.findAllCount").getSingleResult()).intValue(); + em.close(); + int totalCount = pdpCount + papCount; + //create json string for API response + JSONObject json = new JSONObject(); + json.put("papCount", papCount); + json.put("pdpCount", pdpCount); + json.put("totalCount", totalCount); + if (pdpCount>0 && papCount>0 && totalCount>0) { + PolicyLogger.info("Metrics have been found on the Policy Engine for the number of policies on the PAP and PDP."); + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getMetrics"); + response.addHeader("metrics", json.toString() ); + return; + }else{ + String message = "The policy count on the PAP and PDP is 0. Please check the database and file system to correct this error."; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(errorMsg, message); + return; + } + } catch (Exception e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Querying the Database."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(errorMsg, message); + return; + } + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java index 0c98a44a3..f411e7d98 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java @@ -30,69 +30,69 @@ import com.google.common.base.Joiner; @Component public abstract class AbstractPolicyCreation { - - public static String getDomain() { - return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); - } - - public String newPolicyID() { - return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null: "urn"), - getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); - } - - public String convertDate(String dateTTL) { - String formateDate = null; - if(dateTTL.contains("/")){ - formateDate = dateTTL.replace("/", "-"); - }else { - formateDate = dateTTL; - } - return formateDate; - } - - - public void updatePolicyCreationToDatabase(){ - // Add it into our tree + public static String getDomain() { + return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + } + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null: "urn"), + getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + public String convertDate(String dateTTL) { + String formateDate = null; + if(dateTTL.contains("/")){ + formateDate = dateTTL.replace("/", "-"); + }else { + formateDate = dateTTL; + } + return formateDate; + } + + + + public void updatePolicyCreationToDatabase(){ + // Add it into our tree /* Path finalPolicyPath = null; - finalPolicyPath = Paths.get(successMap.get("success")); - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - controller.updateElk(finalPolicyPath.toString()); - File file = finalPolicyPath.toFile(); - if(file != null){ - String policyName = file.toString(); - String removePath = policyName.substring(policyName.indexOf("repository")+11); - String removeXml = removePath.replace(".xml", ""); - String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); - List<Object> policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", removeExtension); - if (policyVersionList.size() > 0) { - for(int i = 0; i < policyVersionList.size(); i++) { - PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); - if(entityItem.getPolicyName().equals(removeExtension)){ - version = entityItem.getHigherVersion() +1; - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setModifiedBy(userId); - commonClassDao.update(entityItem); - if(policyData.isEditPolicy){ - PolicyNotificationMail email = new PolicyNotificationMail(); - String mode = "EditPolicy"; - String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; - email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); - } - } - } - }else{ - PolicyVersion entityItem = new PolicyVersion(); - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setPolicyName(removeExtension); - entityItem.setCreatedBy(userId); - entityItem.setModifiedBy(userId); - commonClassDao.save(entityItem); - } - }*/ - } + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<Object> policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", removeExtension); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + commonClassDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + commonClassDao.save(entityItem); + } + }*/ + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java index 5610577a9..f85255785 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java @@ -48,166 +48,166 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Service public class DictionaryUtils { - private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class); - - private static String apiflag = "apiflag"; - private static String operation = "operation"; - private static String duplicateResponseString = "Duplicate"; - private static String utf8 = "UTF-8"; - private static String applicationJsonContentType = "application / json"; - - private static CommonClassDao commonClassDao; - - private static DictionaryUtils dictionaryUtils; - - public static synchronized DictionaryUtils getDictionaryUtils() { - return dictionaryUtils != null ? dictionaryUtils : new DictionaryUtils(); - } - - public static synchronized void setDictionaryUtils(DictionaryUtils dictionaryUtils) { - DictionaryUtils.dictionaryUtils = dictionaryUtils; - } - - @Autowired - public DictionaryUtils(CommonClassDao commonClassDao){ - DictionaryUtils.commonClassDao = commonClassDao; - } - - public DictionaryUtils(){ - super(); - } - - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - } - - public boolean isRequestFromAPI(HttpServletRequest request){ - return request.getParameter(apiflag)!=null && "api".equalsIgnoreCase(request.getParameter(apiflag)); - } - - public String appendKey(List<Object> objects, String key1, String appendValue){ - StringBuilder userValue = new StringBuilder(); - int counter = 0; - for(Object attribute : objects){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get(key1).toString(); - if(counter>0){ - userValue.append(appendValue); - } - userValue.append(key); - counter ++; - } - } - return userValue.toString(); - } - - public String appendKeyValue(List<Object> objects, String append1, String append2){ - StringBuilder header = new StringBuilder(); - int counter = 0; - for(Object attribute : objects){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); - if(counter>0){ - header.append(append1); - } - header.append(key).append(append2).append(value); - counter ++; - } - } - return header.toString(); - } - - public Datatype getDataType(String datatype){ - Datatype a = new Datatype(); - if("string".equalsIgnoreCase(datatype)){ - a.setId(26); - }else if("integer".equalsIgnoreCase(datatype)){ - a.setId(12); - }else if("boolean".equalsIgnoreCase(datatype)){ - a.setId(18); - }else if("double".equalsIgnoreCase(datatype)){ - a.setId(25); - }else if("user".equalsIgnoreCase(datatype)){ - a.setId(29); - } - return a; - } - - public Category getCategory(){ - return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0); - } - - public ModelAndView getResultForApi(String inResponseString){ - String responseString = inResponseString; - if(responseString!=null && !duplicateResponseString.equals(responseString)){ - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } - - public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException{ - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{"+key+":" + responseString + "}"); - out.write(j.toString()); - } - - public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException{ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - - @SuppressWarnings("rawtypes") - public void getDataByEntity(HttpServletResponse response, String key, String value, Class className){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put(key, mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @SuppressWarnings("rawtypes") - public void getData(HttpServletResponse response, String key, Class className){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put(key, mapper.writeValueAsString(commonClassDao.getData(className))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); + private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class); + + private static String apiflag = "apiflag"; + private static String operation = "operation"; + private static String duplicateResponseString = "Duplicate"; + private static String utf8 = "UTF-8"; + private static String applicationJsonContentType = "application / json"; + + private static CommonClassDao commonClassDao; + + private static DictionaryUtils dictionaryUtils; + + public static synchronized DictionaryUtils getDictionaryUtils() { + return dictionaryUtils != null ? dictionaryUtils : new DictionaryUtils(); + } + + public static synchronized void setDictionaryUtils(DictionaryUtils dictionaryUtils) { + DictionaryUtils.dictionaryUtils = dictionaryUtils; + } + + @Autowired + public DictionaryUtils(CommonClassDao commonClassDao){ + DictionaryUtils.commonClassDao = commonClassDao; + } + + public DictionaryUtils(){ + super(); + } + + public UserInfo getUserInfo(String loginId){ + return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + } + + public boolean isRequestFromAPI(HttpServletRequest request){ + return request.getParameter(apiflag)!=null && "api".equalsIgnoreCase(request.getParameter(apiflag)); + } + + public String appendKey(List<Object> objects, String key1, String appendValue){ + StringBuilder userValue = new StringBuilder(); + int counter = 0; + for(Object attribute : objects){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get(key1).toString(); + if(counter>0){ + userValue.append(appendValue); + } + userValue.append(key); + counter ++; + } + } + return userValue.toString(); + } + + public String appendKeyValue(List<Object> objects, String append1, String append2){ + StringBuilder header = new StringBuilder(); + int counter = 0; + for(Object attribute : objects){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); + if(counter>0){ + header.append(append1); + } + header.append(key).append(append2).append(value); + counter ++; + } + } + return header.toString(); + } + + public Datatype getDataType(String datatype){ + Datatype a = new Datatype(); + if("string".equalsIgnoreCase(datatype)){ + a.setId(26); + }else if("integer".equalsIgnoreCase(datatype)){ + a.setId(12); + }else if("boolean".equalsIgnoreCase(datatype)){ + a.setId(18); + }else if("double".equalsIgnoreCase(datatype)){ + a.setId(25); + }else if("user".equalsIgnoreCase(datatype)){ + a.setId(29); + } + return a; + } + + public Category getCategory(){ + return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0); + } + + public ModelAndView getResultForApi(String inResponseString){ + String responseString = inResponseString; + if(responseString!=null && !duplicateResponseString.equals(responseString)){ + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } + + public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException{ + response.setCharacterEncoding(utf8); + response.setContentType(applicationJsonContentType); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{"+key+":" + responseString + "}"); + out.write(j.toString()); + } + + public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding(utf8); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + + @SuppressWarnings("rawtypes") + public void getDataByEntity(HttpServletResponse response, String key, String value, Class className){ + try{ + Map<String, Object> model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put(key, mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @SuppressWarnings("rawtypes") + public void getData(HttpServletResponse response, String key, Class className){ + try{ + Map<String, Object> model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put(key, mapper.writeValueAsString(commonClassDao.getData(className))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); response.addHeader("successMapKey", "success"); response.addHeader(operation, "getDictionary"); - response.getWriter().write(j.toString()); - }catch(Exception e){ + response.getWriter().write(j.toString()); + }catch(Exception e){ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", "dictionaryDBQuery"); - } - } - - @SuppressWarnings("unchecked") - public void removeData(HttpServletRequest request, HttpServletResponse response, String key, @SuppressWarnings("rawtypes") Class className) throws IOException{ - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - commonClassDao.delete((Object)mapper.readValue(root.get("data").toString(), className)); - String responseString = mapper.writeValueAsString(commonClassDao.getData(className)); - setResponseData(response, key, responseString); - }catch(Exception e){ - setErrorResponseData(response, e); - } - } - + } + } + + @SuppressWarnings("unchecked") + public void removeData(HttpServletRequest request, HttpServletResponse response, String key, @SuppressWarnings("rawtypes") Class className) throws IOException{ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + commonClassDao.delete((Object)mapper.readValue(root.get("data").toString(), className)); + String responseString = mapper.writeValueAsString(commonClassDao.getData(className)); + setResponseData(response, key, responseString); + }catch(Exception e){ + setErrorResponseData(response, e); + } + } + } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java index 22c44a8ab..b9880d8ac 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java @@ -31,88 +31,88 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; public class JPAUtils { - private static final Logger LOGGER = FlexLogger.getLogger(JPAUtils.class); - - private static EntityManagerFactory emf; - private static JPAUtils currentInstance = null; - - - /** - * Get an instance of a JPAUtils. It creates one if it does not exist. - * Only one instance is allowed to be created per server. - * @param emf The EntityFactoryManager to be used for database connections - * @return The new instance of JPAUtils or throw exception if the given emf is null. - * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this. - */ - public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf){ - LOGGER.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called"); - if(currentInstance == null){ - if(emf != null){ - currentInstance = new JPAUtils(emf); - return currentInstance; - } - throw new IllegalStateException("The EntityManagerFactory is Null"); - } - return currentInstance; - } - - private JPAUtils(EntityManagerFactory emf){ - LOGGER.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called"); - JPAUtils.emf = emf; - } - - /** - * Returns the lockdown value, in case of exception it is assumed that lockdown functionality - * is not supported and returns false. - * - * - * @throws ReadOnlyException - * @throws ConversionException - */ - public boolean dbLockdownIgnoreErrors() { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - boolean lockdown = false; - try { - lockdown = dbLockdown(); - } catch (Exception e) { - LOGGER.warn("Cannot access DB lockdown value", e); - } - return lockdown; - } - - /** - * Returns the lockdown value from the database. - * - * @throws ReadOnlyException - * @throws ConversionException - */ - public boolean dbLockdown() - throws IllegalAccessException { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - EntityManager em = emf.createEntityManager(); - Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll"); - - GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult(); - - if (globalRoleSettings == null) { - // this should not happen - String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); - if (LOGGER.isErrorEnabled()) - LOGGER.error(msg); - throw new IllegalAccessException(msg); - } - - if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) { - String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); - if (LOGGER.isErrorEnabled()) - LOGGER.error(msg); - throw new IllegalAccessException(msg); - } - - return globalRoleSettings.isLockdown(); - } + private static final Logger LOGGER = FlexLogger.getLogger(JPAUtils.class); + + private static EntityManagerFactory emf; + private static JPAUtils currentInstance = null; + + + /** + * Get an instance of a JPAUtils. It creates one if it does not exist. + * Only one instance is allowed to be created per server. + * @param emf The EntityFactoryManager to be used for database connections + * @return The new instance of JPAUtils or throw exception if the given emf is null. + * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this. + */ + public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf){ + LOGGER.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called"); + if(currentInstance == null){ + if(emf != null){ + currentInstance = new JPAUtils(emf); + return currentInstance; + } + throw new IllegalStateException("The EntityManagerFactory is Null"); + } + return currentInstance; + } + + private JPAUtils(EntityManagerFactory emf){ + LOGGER.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called"); + JPAUtils.emf = emf; + } + + /** + * Returns the lockdown value, in case of exception it is assumed that lockdown functionality + * is not supported and returns false. + * + * + * @throws ReadOnlyException + * @throws ConversionException + */ + public boolean dbLockdownIgnoreErrors() { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + boolean lockdown = false; + try { + lockdown = dbLockdown(); + } catch (Exception e) { + LOGGER.warn("Cannot access DB lockdown value", e); + } + return lockdown; + } + + /** + * Returns the lockdown value from the database. + * + * @throws ReadOnlyException + * @throws ConversionException + */ + public boolean dbLockdown() + throws IllegalAccessException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + EntityManager em = emf.createEntityManager(); + Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll"); + + GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult(); + + if (globalRoleSettings == null) { + // this should not happen + String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); + if (LOGGER.isErrorEnabled()) + LOGGER.error(msg); + throw new IllegalAccessException(msg); + } + + if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) { + String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); + if (LOGGER.isErrorEnabled()) + LOGGER.error(msg); + throw new IllegalAccessException(msg); + } + + return globalRoleSettings.isLockdown(); + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java index ab3b126ea..6ea0c79ee 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java @@ -22,46 +22,46 @@ package org.onap.policy.pap.xacml.rest.util; public class JsonMessage { - private String data; - private String data2; - private String data3; - public JsonMessage(String data) { - super(); - this.data = data; - } - public JsonMessage(String data,String data2) { - super(); - this.data = data; - this.data2 = data2; - } + private String data; + private String data2; + private String data3; + public JsonMessage(String data) { + super(); + this.data = data; + } + public JsonMessage(String data,String data2) { + super(); + this.data = data; + this.data2 = data2; + } + + public JsonMessage(String data,String data2,String data3) { + super(); + this.data = data; + this.data2 = data2; + this.data3 = data3; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + public String getData2() { + return data2; + } + public void setData2(String data2) { + this.data2 = data2; + } + public String getData3() { + return data3; + } + public void setData3(String data3) { + this.data3 = data3; + } - public JsonMessage(String data,String data2,String data3) { - super(); - this.data = data; - this.data2 = data2; - this.data3 = data3; - } - - public String getData() { - return data; - } - public void setData(String data) { - this.data = data; - } - public String getData2() { - return data2; - } - public void setData2(String data2) { - this.data2 = data2; - } - public String getData3() { - return data3; - } - public void setData3(String data3) { - this.data3 = data3; - } - - } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java index 352505ec5..0ac6c7009 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java @@ -31,34 +31,34 @@ import org.onap.policy.utils.CryptoUtils; import com.att.research.xacml.util.XACMLProperties; public class AuthenticationService { - private String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - private String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); - - public boolean authenticate(String authCredentials) { + private String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + private String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); - if (null == authCredentials) - return false; - // header value format will be "Basic encodedstring" for Basic authentication. - final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); - String usernameAndPassword = null; - try { - byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); - usernameAndPassword = new String(decodedBytes, "UTF-8"); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception decoding username and password"); - return false; - } - try { - final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); - final String username = tokenizer.nextToken(); - final String password = tokenizer.nextToken(); + public boolean authenticate(String authCredentials) { + + if (null == authCredentials) + return false; + // header value format will be "Basic encodedstring" for Basic authentication. + final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); + String usernameAndPassword = null; + try { + byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception decoding username and password"); + return false; + } + try { + final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + final String username = tokenizer.nextToken(); + final String password = tokenizer.nextToken(); + + boolean authenticationStatus = papID.equals(username) && papPass.equals(password); + return authenticationStatus; + } catch (Exception e){ + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception authenticating user"); + return false; + } + } - boolean authenticationStatus = papID.equals(username) && papPass.equals(password); - return authenticationStatus; - } catch (Exception e){ - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception authenticating user"); - return false; - } - } - } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java index 335b94f51..28207f29d 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java @@ -47,137 +47,137 @@ import com.att.research.xacml.api.pap.PAPException; public class CheckPDP { - private static Path pdpPath = null; - private static Properties pdpProp = null; - private static Long oldModified = null; - private static Long newModified = null; - private static HashMap<String, String> pdpMap = null; - private static final Logger logger = FlexLogger.getLogger(CheckPDP.class); + private static Path pdpPath = null; + private static Properties pdpProp = null; + private static Long oldModified = null; + private static Long newModified = null; + private static HashMap<String, String> pdpMap = null; + private static final Logger logger = FlexLogger.getLogger(CheckPDP.class); - public static boolean validateID(String id) { - // ReadFile - try { - readFile(); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception reading file"); - return false; - } - // Check ID - if (pdpMap.containsKey(id)) { - return true; - } - return false; - } + public static boolean validateID(String id) { + // ReadFile + try { + readFile(); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception reading file"); + return false; + } + // Check ID + if (pdpMap.containsKey(id)) { + return true; + } + return false; + } - private static void readFile() throws PAPException { - String pdpFile = XACMLPapServlet.getPDPFile(); - if (pdpFile == null) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); - } - if (pdpPath == null) { - pdpPath = Paths.get(pdpFile); - if (Files.notExists(pdpPath)) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); - } - if (pdpPath.toString().endsWith(".properties")) { - readProps(); - } else { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "Not a .properties file"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); - } - } - // Check if File is updated recently - else { - newModified = pdpPath.toFile().lastModified(); - if (newModified != oldModified) { - // File has been updated. - readProps(); - } - } - } + private static void readFile() throws PAPException { + String pdpFile = XACMLPapServlet.getPDPFile(); + if (pdpFile == null) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); + } + if (pdpPath == null) { + pdpPath = Paths.get(pdpFile); + if (Files.notExists(pdpPath)) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); + } + if (pdpPath.toString().endsWith(".properties")) { + readProps(); + } else { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "Not a .properties file"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); + } + } + // Check if File is updated recently + else { + newModified = pdpPath.toFile().lastModified(); + if (newModified != oldModified) { + // File has been updated. + readProps(); + } + } + } - @SuppressWarnings({ "rawtypes", "unchecked" }) - private static void readProps() throws PAPException { - InputStream in; - pdpProp = new Properties(); - try { - in = new FileInputStream(pdpPath.toFile()); - oldModified = pdpPath.toFile().lastModified(); - pdpProp.load(in); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Cannot load the Properties file"); - throw new PAPException("Cannot Load the Properties file", e); - } - // Read the Properties and Load the PDPs and encoding. - pdpMap = new HashMap<>(); - // Check the Keys for PDP_URLs - Collection<Object> unsorted = pdpProp.keySet(); - List<String> sorted = new ArrayList(unsorted); - Collections.sort(sorted); - for (String propKey : sorted) { - if (propKey.startsWith("PDP_URL")) { - String check_val = pdpProp.getProperty(propKey); - if (check_val == null) { - throw new PAPException("Properties file doesn't have the PDP_URL parameter"); - } - if (check_val.contains(";")) { - List<String> pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*"))); - int pdpCount = 0; - while (pdpCount < pdp_default.size()) { - String pdpVal = pdp_default.get(pdpCount); - readPDPParam(pdpVal); - pdpCount++; - } - } else { - readPDPParam(check_val); - } - } - } - if (pdpMap == null || pdpMap.isEmpty()) { - logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); - } - } + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static void readProps() throws PAPException { + InputStream in; + pdpProp = new Properties(); + try { + in = new FileInputStream(pdpPath.toFile()); + oldModified = pdpPath.toFile().lastModified(); + pdpProp.load(in); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Cannot load the Properties file"); + throw new PAPException("Cannot Load the Properties file", e); + } + // Read the Properties and Load the PDPs and encoding. + pdpMap = new HashMap<>(); + // Check the Keys for PDP_URLs + Collection<Object> unsorted = pdpProp.keySet(); + List<String> sorted = new ArrayList(unsorted); + Collections.sort(sorted); + for (String propKey : sorted) { + if (propKey.startsWith("PDP_URL")) { + String check_val = pdpProp.getProperty(propKey); + if (check_val == null) { + throw new PAPException("Properties file doesn't have the PDP_URL parameter"); + } + if (check_val.contains(";")) { + List<String> pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*"))); + int pdpCount = 0; + while (pdpCount < pdp_default.size()) { + String pdpVal = pdp_default.get(pdpCount); + readPDPParam(pdpVal); + pdpCount++; + } + } else { + readPDPParam(check_val); + } + } + } + if (pdpMap == null || pdpMap.isEmpty()) { + logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); + } + } - private static void readPDPParam(String pdpVal) throws PAPException{ - if(pdpVal.contains(",")){ - List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); - if(pdpValues.size()==3){ - // 1:2 will be UserID:Password - String userID = pdpValues.get(1); - String pass = pdpValues.get(2); - Base64.Encoder encoder = Base64.getEncoder(); - // 0 - PDPURL - pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); - }else{ - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request"); - throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); - } - }else{ - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); - throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); - } - } - - public static String getEncoding(String pdpID){ - try { - readFile(); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exeption reading Properties file"); - } - String encoding = null; - if(pdpMap!=null && (!pdpMap.isEmpty())){ - try{ - encoding = pdpMap.get(pdpID); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding"); - } - return encoding; - }else{ - return null; - } - } + private static void readPDPParam(String pdpVal) throws PAPException{ + if(pdpVal.contains(",")){ + List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + if(pdpValues.size()==3){ + // 1:2 will be UserID:Password + String userID = pdpValues.get(1); + String pass = pdpValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + // 0 - PDPURL + pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); + }else{ + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request"); + throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); + } + }else{ + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); + throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); + } + } + + public static String getEncoding(String pdpID){ + try { + readFile(); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exeption reading Properties file"); + } + String encoding = null; + if(pdpMap!=null && (!pdpMap.isEmpty())){ + try{ + encoding = pdpMap.get(pdpID); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding"); + } + return encoding; + }else{ + return null; + } + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java index c4b97f592..94cd9c798 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java @@ -41,69 +41,69 @@ import org.apache.commons.logging.LogFactory; @WebFilter("/*") public class PAPAuthenticationFilter implements Filter { - private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); - public static final String AUTHENTICATION_HEADER = "Authorization"; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filter) throws IOException, ServletException { - - - if (request instanceof HttpServletRequest) { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - - String authCredentials = null; - String url = httpServletRequest.getRequestURI(); - - logger.info("Request URI: " + url); - - //getting authentication credentials - authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); - - // Check Authentication credentials - AuthenticationService authenticationService = new AuthenticationService(); - boolean authenticationStatus = authenticationService.authenticate(authCredentials); - - if (authenticationStatus) { - //indicates the request comes from Traditional Admin Console or PolicyEngineAPI - if ("/pap/".equals(url)){ - logger.info("Request comes from Traditional Admin Console or PolicyEngineAPI"); - //forward request to the XACMLPAPServlet if authenticated - request.getRequestDispatcher("/pap/pap/").forward(request, response); - }else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse){ - //indicates the request comes from the ONAP Portal onap-sdk-app - HttpServletResponse alteredResponse = ((HttpServletResponse)response); - addCorsHeader(alteredResponse); - logger.info("Request comes from Onap Portal"); - //Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path - filter.doFilter(request, response); - } - } else { - if (response instanceof HttpServletResponse) { - HttpServletResponse httpServletResponse = (HttpServletResponse) response; - httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - } - - } - } - - //method to add CorsHeaders for onap portal rest call - private void addCorsHeader(HttpServletResponse response) { - logger.info("Adding Cors Response Headers!!!"); - response.addHeader("Access-Control-Allow-Origin", "*"); + private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); + public static final String AUTHENTICATION_HEADER = "Authorization"; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filter) throws IOException, ServletException { + + + if (request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + + String authCredentials = null; + String url = httpServletRequest.getRequestURI(); + + logger.info("Request URI: " + url); + + //getting authentication credentials + authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); + + // Check Authentication credentials + AuthenticationService authenticationService = new AuthenticationService(); + boolean authenticationStatus = authenticationService.authenticate(authCredentials); + + if (authenticationStatus) { + //indicates the request comes from Traditional Admin Console or PolicyEngineAPI + if ("/pap/".equals(url)){ + logger.info("Request comes from Traditional Admin Console or PolicyEngineAPI"); + //forward request to the XACMLPAPServlet if authenticated + request.getRequestDispatcher("/pap/pap/").forward(request, response); + }else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse){ + //indicates the request comes from the ONAP Portal onap-sdk-app + HttpServletResponse alteredResponse = ((HttpServletResponse)response); + addCorsHeader(alteredResponse); + logger.info("Request comes from Onap Portal"); + //Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path + filter.doFilter(request, response); + } + } else { + if (response instanceof HttpServletResponse) { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } + + } + } + + //method to add CorsHeaders for onap portal rest call + private void addCorsHeader(HttpServletResponse response) { + logger.info("Adding Cors Response Headers!!!"); + response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD"); response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); response.addHeader("Access-Control-Max-Age", "1728000"); - } + } - @Override - public void destroy() { - //Empty - } + @Override + public void destroy() { + //Empty + } - @Override - public void init(FilterConfig arg0) throws ServletException { - //Empty - } + @Override + public void init(FilterConfig arg0) throws ServletException { + //Empty + } } |