diff options
Diffstat (limited to 'ONAP-PAP-REST/src')
5 files changed, 543 insertions, 527 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java index 6c80f9c04..614ba85df 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java index eed73f629..6c66898e3 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index d6718ab81..abb425131 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +58,7 @@ public class CreateNewMicroServiceModel { private HashMap<String,MSAttributeObject > classMap = new HashMap<>(); - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) { super(); @@ -80,31 +81,8 @@ public class CreateNewMicroServiceModel { File directory = new File("ExtractDir" + File.separator + randomID); List<File> fileList = listModelFiles(directory.toString()); //get all the files from a director - for (File file : fileList){ - if (file.isFile()){ - int i = file.getName().lastIndexOf('.'); - String type = file.getName().substring(i+1); - - if(type != null && "yml".equalsIgnoreCase(type)){ - - processYmlModel(file.toString(), modelName); - - }else{ - - tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); - classMap.putAll(tempMap); - } - } - } - cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip"; - try { - FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID)); - FileUtils.deleteDirectory(new File(randomID)); - File deleteFile = new File(cleanUpFile); - FileUtils.forceDelete(deleteFile); - } catch (IOException e) { - logger.error("Failed to unzip model file " + randomID, e); - } + processFiles(modelName, fileList); + doCleanUpFiles(randomID); }else { if(importFile.contains(".yml")){ @@ -122,6 +100,39 @@ public class CreateNewMicroServiceModel { } } + private void processFiles(String modelName, List<File> fileList) { + Map<String, MSAttributeObject> tempMap; + for (File file : fileList){ + if (file.isFile()){ + int i = file.getName().lastIndexOf('.'); + String type = file.getName().substring(i+1); + + if("yml".equalsIgnoreCase(type)){ + + processYmlModel(file.toString(), modelName); + + }else{ + + tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); + classMap.putAll(tempMap); + } + } + } + } + + private void doCleanUpFiles(String randomID) { + String cleanUpFile; + cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip"; + try { + FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID)); + FileUtils.deleteDirectory(new File(randomID)); + File deleteFile = new File(cleanUpFile); + FileUtils.forceDelete(deleteFile); + } catch (IOException e) { + logger.error("Failed to unzip model file " + randomID, e); + } + } + private void processYmlModel(String fileName, String modelName){ try { @@ -145,7 +156,7 @@ public class CreateNewMicroServiceModel { returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if(utils.getListConstraints()!=""){ + if(!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())){ LinkedHashMap<String, String> enumList =new LinkedHashMap<>(); String[] listArray=utils.getListConstraints().split("#"); for(String str:listArray){ diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java index 3b3e81ee2..1be27ae71 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,334 +52,326 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; public abstract class Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(Policy.class); - - - /** - * Common Fields - */ - public static final String GET_INT_TYPE = "Integer"; - public static final String GET_STRING_TYPE = "String"; - - public static final String ONAPID = "ONAPName"; - public static final String CONFIGID = "ConfigName"; - public static final String CLOSEDLOOPID = "ServiceType"; - - public static final String CONFIG_POLICY = "Config"; - public static final String ACTION_POLICY = "Action"; - public static final String DECISION_POLICY = "Decision"; - - protected String policyName = null; - - protected boolean isValidForm = true; - - private Path finalPolicyPath = null; - - private boolean preparedToSave = false; - - private boolean policyExists = false; - - public Path getFinalPolicyPath() { - return finalPolicyPath; - } - - public void setFinalPolicyPath(Path finalPolicyPath) { - this.finalPolicyPath = finalPolicyPath; - } - - // Constants Used in XML Creation - public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; - public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; - public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; - public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; - public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; - public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; - public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; - public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; - public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; - public static final String FUNCTION_BOOLEAN_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:boolean-one-and-only"; - public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; - public static final String FUNCTION_STRING_REGEX_MATCH = "org.onap.function.regex-match"; - public static final String FUNCTION_STRING_REGEXP_MATCH = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"; - public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; - public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; - public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; - public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; - public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI"; - public static final String RULE_VARIABLE = "var:"; - public static final String EMPTY_STRING = ""; - - protected static String CONFIG_HOME = null; - protected static String ACTION_HOME = null; - protected static String CONFIG_URL = null; - - protected Map<String, String> performer = new HashMap<>(); - - private static String actionHome = null; - private static String configHome = null; - - public PolicyRestAdapter policyAdapter = null; - String ruleID = ""; - - public Policy() { - CONFIG_HOME = getConfigHome(); - ACTION_HOME = getActionHome(); - CONFIG_URL = "$URL"; - performer.put("PDP", "PDPAction"); - performer.put("PEP", "PEPAction"); - } - - //Each policy type seems to either use policyData or data field policy adapter when - //getting the xml to save the policy. Instead of keep this hardcoded in the save method, - //this method makes it usable outside. - /** - * Return the data field of the PolicyAdapter that will be used when saving this policy - * with the savePolicies method. - * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData() - */ - public abstract Object getCorrectPolicyDataObject(); - public abstract Map<String, String> savePolicies() throws PAPException; - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - public abstract boolean prepareToSave() throws PAPException; - - - // create match for onap and config name - protected MatchType createMatch(String key, String value) { - MatchType match = new MatchType(); - - AttributeValueType attributeValue = new AttributeValueType(); - attributeValue.setDataType(STRING_DATATYPE); - attributeValue.getContent().add(value); - match.setAttributeValue(attributeValue); - AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); - URI uri = null; - try { - uri = new URI(key); - } catch (URISyntaxException e) { - LOGGER.error("Exception Occured"+e); - } - attributeDesignator.setCategory(CATEGORY_ACCESS_SUBJECT); - attributeDesignator.setDataType(STRING_DATATYPE); - attributeDesignator.setAttributeId(new IdentifierImpl(uri).stringValue()); - match.setAttributeDesignator(attributeDesignator); - match.setMatchId(FUNCTION_STRING_REGEX_MATCH); - return match; - } - - // Creating the match for dynamically added components. - protected MatchType createDynamicMatch(String key, String value) { - MatchType dynamicMatch = new MatchType(); - AttributeValueType dynamicAttributeValue = new AttributeValueType(); - String dataType = null; - dataType = STRING_DATATYPE; - dynamicAttributeValue.setDataType(dataType); - dynamicAttributeValue.getContent().add(value); - dynamicMatch.setAttributeValue(dynamicAttributeValue); - - AttributeDesignatorType dynamicAttributeDesignator = new AttributeDesignatorType(); - - URI dynamicURI = null; - try { - dynamicURI = new URI(key); - } catch (URISyntaxException e) { - LOGGER.error("Exception Occured"+e);// log msg - } - dynamicAttributeDesignator.setCategory(CATEGORY_RESOURCE); - dynamicAttributeDesignator.setDataType(dataType); - dynamicAttributeDesignator.setAttributeId(new IdentifierImpl(dynamicURI).stringValue()); - dynamicMatch.setAttributeDesignator(dynamicAttributeDesignator); - dynamicMatch.setMatchId(FUNCTION_STRING_REGEX_MATCH); - - return dynamicMatch; - } - - // the Policy Name as Unique One throws error - @SuppressWarnings("static-access") - protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) { - policyType = FilenameUtils.removeExtension(policyType); - polcyFileName = FilenameUtils.removeExtension(polcyFileName); - Path newFile = null; - String policyDir = EMPTY_STRING; - String absolutePath = parent.toString(); - if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf('\\') + 1, absolutePath.length()); - if (policyDir == null || policyDir.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf('/') + 1, absolutePath.length()); - } - } - - String fileName = "default"; - if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { - fileName = policyType + "_" + String.format(polcyFileName) + "." + version + ".xml"; - } - - newFile = Paths.get(parent.toString(), fileName); - if (newFile.toFile().exists()) { - return newFile; - } - return null; - } - - protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, String policyFileName, Integer version) { - policyType = FilenameUtils.removeExtension(policyType); - policyConfigType = FilenameUtils.removeExtension(policyConfigType); - policyFileName = FilenameUtils.removeExtension(policyFileName); - Path newFile = null; - String policyDir = EMPTY_STRING; - String absolutePath = parentPath.toString(); - if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf('\\') + 1, absolutePath.length()); - if (policyDir == null || policyDir.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf('/') + 1, absolutePath.length()); - } - } - - String fileName = "default"; - if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { - if("ClosedLoop_PM".equals(policyConfigType)){ - fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml"; - }else if("ClosedLoop_Fault".equals(policyConfigType)){ - fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; - }else if("Micro Service".equals(policyConfigType)){ - fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; - }else if("Optimization".equals(policyConfigType)) { - fileName = policyType + "_" + "OOF" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; - } - } - - newFile = Paths.get(parentPath.toString(), fileName); - - if (newFile.toFile().exists()) { - return newFile; - } - return null; - } - - - //create policy once all the validations are completed - protected Map<String, String> createPolicy(final Path policyPath, final Object policyData) { - Map<String, String> success = new HashMap<>(); - // - // Is the root a PolicySet or Policy? - // - - if (policyData instanceof PolicyType) { - // - // Write it out - // - //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP - //and this transaction is intercepted up stream. - InputStream inputStream = null; - try { - inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData); - PolicyDef policyDef = DOMPolicyDef.load(inputStream); - if (policyDef == null) { - success.put("validation", "PolicyDef Validation Failed"); - }else{ - success.put("success", "success"); - } - } catch (Exception e) { - LOGGER.error("PolicyDef Validation failed"+e); - success.put("error", "Validation Failed"); - }finally{ - try { - if(inputStream != null) - inputStream.close(); - } catch (IOException e) { - LOGGER.error("Exception Occured while closing the input stream"+e); - } - } - } else { - PolicyLogger.error("Unknown data type sent back."); - return success; - } - return success; - } - - public static String getConfigHome(){ - try { - loadWebapps(); - } catch (Exception e) { - LOGGER.debug(e); - return null; - } - return configHome; - } - - public static String getActionHome(){ - try { - loadWebapps(); - } catch (Exception e) { - LOGGER.debug(e); - return null; - } - return actionHome; - } - - 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; - Path webappsPathAction; - if(webappsPath.toString().contains("\\")){ - webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"\\Action"); - }else{ - webappsPathConfig = Paths.get(webappsPath.toString()+"/Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"/Action"); - } - if(!webappsPathConfig.toFile().exists()){ - try { - Files.createDirectories(webappsPathConfig); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); - } - } - if(!webappsPathAction.toFile().exists()){ - try { - Files.createDirectories(webappsPathAction); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); - } - } - actionHome = webappsPathAction.toString(); - configHome = webappsPathConfig.toString(); - } - } - - public boolean validateConfigForm() { - return true; - } - - /** - * @return the preparedToSave - */ - public boolean isPreparedToSave() { - return preparedToSave; - } - - /** - * @param preparedToSave the preparedToSave to set - */ - protected void setPreparedToSave(boolean preparedToSave) { - this.preparedToSave = preparedToSave; - } - - public boolean isPolicyExists() { - return policyExists; - } - - public void setPolicyExists(boolean policyExists) { - this.policyExists = policyExists; - } + + private static final Logger LOGGER = FlexLogger.getLogger(Policy.class); + + + /** + * Common Fields + */ + public static final String GET_INT_TYPE = "Integer"; + public static final String GET_STRING_TYPE = "String"; + + public static final String ONAPID = "ONAPName"; + public static final String CONFIGID = "ConfigName"; + public static final String CLOSEDLOOPID = "ServiceType"; + + public static final String CONFIG_POLICY = "Config"; + public static final String ACTION_POLICY = "Action"; + public static final String DECISION_POLICY = "Decision"; + + protected String policyName = null; + + protected boolean isValidForm = true; + + private Path finalPolicyPath = null; + + private boolean preparedToSave = false; + + private boolean policyExists = false; + + public Path getFinalPolicyPath() { + return finalPolicyPath; + } + + public void setFinalPolicyPath(Path finalPolicyPath) { + this.finalPolicyPath = finalPolicyPath; + } + + // Constants Used in XML Creation + public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; + public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; + public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; + public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; + public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; + public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; + public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; + public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; + public static final String FUNCTION_BOOLEAN_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:boolean-one-and-only"; + public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; + public static final String FUNCTION_STRING_REGEX_MATCH = "org.onap.function.regex-match"; + public static final String FUNCTION_STRING_REGEXP_MATCH = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"; + public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; + public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; + public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; + public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; + public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI"; + public static final String RULE_VARIABLE = "var:"; + public static final String EMPTY_STRING = ""; + + protected static String CONFIG_HOME = null; + protected static String ACTION_HOME = null; + protected static String CONFIG_URL = null; + + protected Map<String, String> performer = new HashMap<>(); + + private static String actionHome = null; + private static String configHome = null; + + public PolicyRestAdapter policyAdapter = null; + String ruleID = ""; + + public Policy() { + CONFIG_HOME = getConfigHome(); + ACTION_HOME = getActionHome(); + CONFIG_URL = "$URL"; + performer.put("PDP", "PDPAction"); + performer.put("PEP", "PEPAction"); + } + + //Each policy type seems to either use policyData or data field policy adapter when + //getting the xml to save the policy. Instead of keep this hardcoded in the save method, + //this method makes it usable outside. + /** + * Return the data field of the PolicyAdapter that will be used when saving this policy + * with the savePolicies method. + * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData() + */ + public abstract Object getCorrectPolicyDataObject(); + public abstract Map<String, String> savePolicies() throws PAPException; + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + public abstract boolean prepareToSave() throws PAPException; + + + // create match for onap and config name + protected MatchType createMatch(String key, String value) { + MatchType match = new MatchType(); + + AttributeValueType attributeValue = new AttributeValueType(); + attributeValue.setDataType(STRING_DATATYPE); + attributeValue.getContent().add(value); + match.setAttributeValue(attributeValue); + AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); + URI uri = null; + try { + uri = new URI(key); + } catch (URISyntaxException e) { + LOGGER.error("Exception Occured"+e); + } + attributeDesignator.setCategory(CATEGORY_ACCESS_SUBJECT); + attributeDesignator.setDataType(STRING_DATATYPE); + attributeDesignator.setAttributeId(new IdentifierImpl(uri).stringValue()); + match.setAttributeDesignator(attributeDesignator); + match.setMatchId(FUNCTION_STRING_REGEX_MATCH); + return match; + } + + // Creating the match for dynamically added components. + protected MatchType createDynamicMatch(String key, String value) { + MatchType dynamicMatch = new MatchType(); + AttributeValueType dynamicAttributeValue = new AttributeValueType(); + String dataType = null; + dataType = STRING_DATATYPE; + dynamicAttributeValue.setDataType(dataType); + dynamicAttributeValue.getContent().add(value); + dynamicMatch.setAttributeValue(dynamicAttributeValue); + + AttributeDesignatorType dynamicAttributeDesignator = new AttributeDesignatorType(); + + URI dynamicURI = null; + try { + dynamicURI = new URI(key); + } catch (URISyntaxException e) { + LOGGER.error("Exception Occured"+e);// log msg + } + dynamicAttributeDesignator.setCategory(CATEGORY_RESOURCE); + dynamicAttributeDesignator.setDataType(dataType); + dynamicAttributeDesignator.setAttributeId(new IdentifierImpl(dynamicURI).stringValue()); + dynamicMatch.setAttributeDesignator(dynamicAttributeDesignator); + dynamicMatch.setMatchId(FUNCTION_STRING_REGEX_MATCH); + + return dynamicMatch; + } + + // the Policy Name as Unique One throws error + @SuppressWarnings("static-access") + protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) { + policyType = FilenameUtils.removeExtension(policyType); + polcyFileName = FilenameUtils.removeExtension(polcyFileName); + Path newFile = null; + String policyDir = EMPTY_STRING; + String absolutePath = parent.toString(); + if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf('\\') + 1, absolutePath.length()); + if (policyDir == null || policyDir.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf('/') + 1, absolutePath.length()); + } + } + + String fileName = "default"; + if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { + fileName = policyType + "_" + String.format(polcyFileName) + "." + version + ".xml"; + } + + newFile = Paths.get(parent.toString(), fileName); + if (newFile.toFile().exists()) { + return newFile; + } + return null; + } + + protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, String policyFileName, Integer version) { + policyType = FilenameUtils.removeExtension(policyType); + policyConfigType = FilenameUtils.removeExtension(policyConfigType); + policyFileName = FilenameUtils.removeExtension(policyFileName); + Path newFile = null; + String policyDir = EMPTY_STRING; + String absolutePath = parentPath.toString(); + if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf('\\') + 1, absolutePath.length()); + if (policyDir.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf('/') + 1, absolutePath.length()); + } + } + + String fileName = "default"; + if (!policyDir.equals(EMPTY_STRING)) { + if("ClosedLoop_PM".equals(policyConfigType)){ + fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml"; + }else if("ClosedLoop_Fault".equals(policyConfigType)){ + fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; + }else if("Micro Service".equals(policyConfigType)){ + fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; + }else if("Optimization".equals(policyConfigType)) { + fileName = policyType + "_" + "OOF" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; + } + } + + newFile = Paths.get(parentPath.toString(), fileName); + + if (newFile.toFile().exists()) { + return newFile; + } + return null; + } + + + //create policy once all the validations are completed + protected Map<String, String> createPolicy(final Path policyPath, final Object policyData) { + Map<String, String> success = new HashMap<>(); + // + // Is the root a PolicySet or Policy? + // + + if (policyData instanceof PolicyType) { + // + // Write it out + // + //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP + //and this transaction is intercepted up stream. + + try(InputStream inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData)) { + PolicyDef policyDef = DOMPolicyDef.load(inputStream); + if (policyDef == null) { + success.put("validation", "PolicyDef Validation Failed"); + }else{ + success.put("success", "success"); + } + } catch (Exception e) { + LOGGER.error("PolicyDef Validation failed"+e); + success.put("error", "Validation Failed"); + } + } else { + PolicyLogger.error("Unknown data type sent back."); + return success; + } + return success; + } + + public static String getConfigHome(){ + try { + loadWebapps(); + } catch (Exception e) { + LOGGER.debug(e); + return null; + } + return configHome; + } + + public static String getActionHome(){ + try { + loadWebapps(); + } catch (Exception e) { + LOGGER.debug(e); + return null; + } + return actionHome; + } + + 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; + Path webappsPathAction; + if(webappsPath.toString().contains("\\")){ + webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config"); + webappsPathAction = Paths.get(webappsPath.toString()+"\\Action"); + }else{ + webappsPathConfig = Paths.get(webappsPath.toString()+"/Config"); + webappsPathAction = Paths.get(webappsPath.toString()+"/Action"); + } + if(!webappsPathConfig.toFile().exists()){ + try { + Files.createDirectories(webappsPathConfig); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); + } + } + if(!webappsPathAction.toFile().exists()){ + try { + Files.createDirectories(webappsPathAction); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); + } + } + actionHome = webappsPathAction.toString(); + configHome = webappsPathConfig.toString(); + } + } + + public boolean validateConfigForm() { + return true; + } + + /** + * @return the preparedToSave + */ + public boolean isPreparedToSave() { + return preparedToSave; + } + + /** + * @param preparedToSave the preparedToSave to set + */ + protected void setPreparedToSave(boolean preparedToSave) { + this.preparedToSave = preparedToSave; + } + + public boolean isPolicyExists() { + return policyExists; + } + + public void setPolicyExists(boolean policyExists) { + this.policyExists = policyExists; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java index 2374ac4ec..1b786ed6a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java @@ -3,13 +3,14 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -86,14 +87,13 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.onap.policy.xacml.util.XACMLPolicyWriter; import org.w3c.dom.Document; import org.xml.sax.InputSource; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDP; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; - public class PolicyDBDao { private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); private List<?> otherServers; @@ -101,31 +101,30 @@ public class PolicyDBDao { private static PolicyDBDao currentInstance = null; private PAPPolicyEngine papEngine; - public static final String JSON_CONFIG = "JSON"; - public static final String XML_CONFIG = "XML"; - public static final String PROPERTIES_CONFIG = "PROPERTIES"; - public static final String OTHER_CONFIG = "OTHER"; - public static final String AUDIT_USER = "audit"; + private static final String JSON_CONFIG = "JSON"; + private static final String XML_CONFIG = "XML"; + private static final String PROPERTIES_CONFIG = "PROPERTIES"; + private static final String OTHER_CONFIG = "OTHER"; //Declared to static variables which were repeating multiple times across the PolicyDBDao public static final String config = "Config"; public static final String action = "Action"; - public static final String groupIdVar = "groupId"; - public static final String deletedVar = "deleted"; - public static final String groupEntitySelectQuery = "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"; - public static final String pdpEntitySelectQuery = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; - public static final String groupCannotBeFound = "The group could not be found with id "; - public static final String foundInDBNotDeleted = " were found in the database that are not deleted"; - public static final String moreThanOnePDP = "Somehow, more than one pdp with the same id "; - public static final String deletedStatusFound = " and deleted status were found in the database"; - public static final String duplicateGroupId = "Somehow, more than one group with the same id "; - public static final String pdpIdVariable = "pdpId"; - public static final String queryFailedToCheckExisting = "Query failed trying to check for existing group"; - public static final String queryFailedToGetGroup = "Query failed trying to get group "; + private static final String groupIdVar = "groupId"; + private static final String deletedVar = "deleted"; + private static final String groupEntitySelectQuery = "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"; + private static final String pdpEntitySelectQuery = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; + private static final String groupCannotBeFound = "The group could not be found with id "; + private static final String foundInDBNotDeleted = " were found in the database that are not deleted"; + private static final String moreThanOnePDP = "Somehow, more than one pdp with the same id "; + private static final String deletedStatusFound = " and deleted status were found in the database"; + private static final String duplicateGroupId = "Somehow, more than one group with the same id "; + private static final String pdpIdVariable = "pdpId"; + private static final String queryFailedToCheckExisting = "Query failed trying to check for existing group"; + private static final String queryFailedToGetGroup = "Query failed trying to get group "; public static final String scope = "scope"; - public static final String policyDBDaoVar = "PolicyDBDao"; - public static final String duplicatePolicyId = "Somehow, more than one policy with the id "; - public static final String foundInDB = " were found in the database"; + private static final String policyDBDaoVar = "PolicyDBDao"; + private static final String duplicatePolicyId = "Somehow, more than one policy with the id "; + private static final String foundInDB = " were found in the database"; private static boolean isJunit = false; @@ -425,30 +424,6 @@ public class PolicyDBDao { return true; } - public void notifyOthers(long entityId,String entityType){ - notifyOthers(entityId,entityType,null); - } - - public void notifyOthers(long entityId, String entityType, String newGroupId){ - logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called"); - LinkedList<Thread> notifyThreads = new LinkedList<>(); - - //we're going to run notifications in parallel threads to speed things up - for(Object obj : otherServers){ - Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId)); - newNotifyThread.start(); - notifyThreads.add(newNotifyThread); - } - //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes - for(Thread t : notifyThreads){ - try { - t.join(); - } catch (Exception e) { - logger.warn("Could not join a notifcation thread" + e); - } - } - } - private class NotifyOtherThread implements Runnable { public NotifyOtherThread(Object obj, long entityId, String entityType, String newGroupId){ this.obj = obj; @@ -481,19 +456,18 @@ public class PolicyDBDao { URL url; String papUrl; try { - String[] papUrlUserPass = getPapUrlUserPass(); - if(papUrlUserPass == null ){ - papUrl = "undefined"; - } else { - papUrl = papUrlUserPass[0]; - } + String[] papUrlUserPass = getPapUrlUserPass(); + if(papUrlUserPass == null ){ + papUrl = "undefined"; + } else { + papUrl = papUrlUserPass[0]; + } logger.debug("We are going to try to notify "+o); //is this our own url? String ourUrl = o; try{ ourUrl = splitPapUrlUserPass((String)o)[0]; }catch(Exception e){ - ourUrl = o; logger.debug(e); } if(o == null){ @@ -617,57 +591,57 @@ public class PolicyDBDao { int pauseBetweenRetries = 1000; switch(entityType){ - case POLICY_NOTIFICATION: - for(int i=0; i<retries;i++){ - try{ - handleIncomingPolicyChange(entityId); - break; - } catch(Exception e){ - logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught exception on handleIncomingPolicyChange("+url+", "+entityId+", "+extraData+")"); - } - try{ - Thread.sleep(pauseBetweenRetries); - }catch(InterruptedException ie){ - Thread.currentThread().interrupt(); - break; - } - } - break; - case PDP_NOTIFICATION: - for(int i=0; i<retries;i++){ - try{ - handleIncomingPdpChange(entityId, transaction); - break; - } catch(Exception e){ - logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught exception on handleIncomingPdpChange("+url+", "+entityId+", "+transaction+")"); - } - try{ - Thread.sleep(pauseBetweenRetries); - }catch(InterruptedException ie){ - Thread.currentThread().interrupt(); - break; + case POLICY_NOTIFICATION: + for(int i=0; i<retries;i++){ + try{ + handleIncomingPolicyChange(entityId); + break; + } catch(Exception e){ + logger.debug(e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught exception on handleIncomingPolicyChange("+url+", "+entityId+", "+extraData+")"); + } + try{ + Thread.sleep(pauseBetweenRetries); + }catch(InterruptedException ie){ + Thread.currentThread().interrupt(); + break; + } } - } - break; - case GROUP_NOTIFICATION: - for(int i=0; i<retries;i++){ - try{ - handleIncomingGroupChange(entityId, extraData, transaction); - break; - }catch(Exception e){ - logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught exception on handleIncomingGroupChange("+url+", "+entityId+", "+extraData+", "+transaction+", "+xacmlPapServlet+")"); + break; + case PDP_NOTIFICATION: + for(int i=0; i<retries;i++){ + try{ + handleIncomingPdpChange(entityId, transaction); + break; + } catch(Exception e){ + logger.debug(e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught exception on handleIncomingPdpChange("+url+", "+entityId+", "+transaction+")"); + } + try{ + Thread.sleep(pauseBetweenRetries); + }catch(InterruptedException ie){ + Thread.currentThread().interrupt(); + break; + } } - try{ - Thread.sleep(pauseBetweenRetries); - }catch(InterruptedException ie){ - Thread.currentThread().interrupt(); - break; + break; + case GROUP_NOTIFICATION: + for(int i=0; i<retries;i++){ + try{ + handleIncomingGroupChange(entityId, extraData, transaction); + break; + }catch(Exception e){ + logger.debug(e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught exception on handleIncomingGroupChange("+url+", "+entityId+", "+extraData+", "+transaction+", "+xacmlPapServlet+")"); + } + try{ + Thread.sleep(pauseBetweenRetries); + }catch(InterruptedException ie){ + Thread.currentThread().interrupt(); + break; + } } - } - break; + break; } //no changes should be being made in this function, we still need to close transaction.rollbackTransaction(); @@ -909,7 +883,7 @@ public class PolicyDBDao { throw new PolicyDBException(); } } catch(Exception e){ - nameAndVersion[0] = originalPolicyName; + nameAndVersion[0] = originalPolicyName; logger.debug(e); } try{ @@ -923,7 +897,7 @@ public class PolicyDBDao { } return nameAndVersion; } - + private void handleIncomingPdpChange(String pdpId, PolicyDBDaoTransaction transaction) throws PAPException{ //get pdp long pdpIdLong = -1; @@ -1321,7 +1295,7 @@ public class PolicyDBDao { private String[] getNameScopeAndVersionFromPdpPolicy(String fileName){ String[] splitByDots = fileName.split("\\."); if(splitByDots.length < 3){ - return null; + return null; } String policyName = splitByDots[splitByDots.length-3]; String version = splitByDots[splitByDots.length-2]; @@ -1367,7 +1341,7 @@ public class PolicyDBDao { * @param strings One or more Strings (or nulls) to check if they are null or empty * @return true if one or more of the given strings are empty or null */ - private static boolean isNullOrEmpty(String... strings){ + public static boolean isNullOrEmpty(String... strings){ for(String s : strings){ if(s == null || "".equals(s)){ return true; @@ -1939,22 +1913,14 @@ public class PolicyDBDao { @Override public void createPolicy(Policy policy, String username){ - InputStream policyXmlStream = null; + try{ logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy("+policy+","+username+") called"); String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP //and this transaction is intercepted up stream. - String policyDataString; - try { - policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType)policy.getCorrectPolicyDataObject()); - policyDataString = IOUtils.toString(policyXmlStream); - } catch (IOException e) { - policyDataString = "could not read"; - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught IOException on IOUtils.toString("+policyXmlStream+")"); - throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter."); - } - IOUtils.closeQuietly(policyXmlStream); + + String policyDataString = getPolicyDataString((PolicyType)policy.getCorrectPolicyDataObject()); if(isJunit){ //Using parentPath object to set policy data. policyDataString = policy.policyAdapter.getParentPath(); @@ -1971,19 +1937,7 @@ public class PolicyDBDao { prefix = configPath.substring(configPath.indexOf(policyScope+".")+policyScope.concat(".").length(), configPath.lastIndexOf(policy.policyAdapter.getPolicyName())); if(isNullOrEmpty(policy.policyAdapter.getConfigBodyData())){ - String configData = ""; - try{ - String newConfigPath = configPath; - try{ - newConfigPath = processConfigPath(newConfigPath); - }catch(Exception e2){ - logger.error("Could not process config path: "+newConfigPath,e2); - } - configData = readConfigFile(newConfigPath); - }catch(Exception e){ - logger.error("Could not read config body data for "+configPath,e); - } - policy.policyAdapter.setConfigBodyData(configData); + policy.policyAdapter.setConfigBodyData(getConfigData(configPath)); } } else if (action.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { prefix = "Action_"; @@ -2017,16 +1971,39 @@ public class PolicyDBDao { } } } - createPolicy(policy.policyAdapter, username, policyScope,finalName,policyDataString); - }finally{ - if(policyXmlStream != null){ - try { - policyXmlStream.close(); - } catch (IOException e) { - logger.error("Exception Occured while closing input stream"+e); - } - } + } catch (Exception e) { + logger.error("Could not create policy for "+policy,e); + throw e; + } + } + + private String getConfigData(String configPath) { + String configData = ""; + try{ + configData = getConfigPath(configPath); + }catch(Exception e){ + logger.error("Could not read config body data for "+configPath,e); + } + return configData; + } + + private String getConfigPath(String configPath) { + try{ + String newConfigPath = processConfigPath(configPath); + return readConfigFile(newConfigPath); + } catch(IllegalArgumentException e2){ + logger.error("Could not process config path: "+configPath,e2); + } + return ""; + } + + private String getPolicyDataString(PolicyType policyType) { + try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyType)) { + return IOUtils.toString(policyXmlStream, StandardCharsets.UTF_8); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Caught IOException on IOUtils.toString(policyXmlStream)"); + throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.", e); } } @@ -2140,37 +2117,7 @@ public class PolicyDBDao { //should be fast since getPolicies uses a HashSet in StdPDPGroup if(!newPolicySet.contains(pol.getId())){ String[] scopeAndName = getNameScopeAndVersionFromPdpPolicy(pol.getId()); - PolicyEntity policyToDelete = null; - try{ - if(scopeAndName!=null){ - policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]); - if ("XACMLPapServlet.doDelete".equals(username)) { - Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDB.getPolicies().iterator(); - String policyName = getPolicyNameAndVersionFromPolicyFileName(policyToDelete.getPolicyName())[0]; - - logger.info("PolicyDBDao: delete policy from GroupEntity"); - try{ - while(dbPolicyIt.hasNext()){ - PolicyEntity dbpolicy = dbPolicyIt.next(); - if(policyToDelete.getScope().equals(dbpolicy.getScope()) && - getPolicyNameAndVersionFromPolicyFileName(dbpolicy.getPolicyName())[0].equals(policyName)) { - dbPolicyIt.remove(); - - logger.info("PolicyDBDao: deleting policy from the existing group:\n " - + "policyName is " + policyToDelete.getScope()+"."+policyToDelete.getPolicyName() + "\n" - + "group is " + groupToUpdateInDB.getGroupId()); - } - } - }catch(Exception e){ - logger.debug(e); - PolicyLogger.error("Could not delete policy with name: "+ policyToDelete.getScope()+"."+policyToDelete.getPolicyName()+"\n ID: "+ policyToDelete.getPolicyId()); - } - } - } - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Could not get policy to remove: "+pol.getId()); - throw new PersistenceException("Could not get policy to remove: "+pol.getId()); - } + deletePolicyInScope(username, groupToUpdateInDB, pol, scopeAndName); } } } @@ -2201,6 +2148,45 @@ public class PolicyDBDao { } } + private void deletePolicyInScope(String username, GroupEntity groupToUpdateInDB, PDPPolicy pol, String[] scopeAndName) { + PolicyEntity policyToDelete; + if (scopeAndName == null) { + return; + } + try{ + policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]); + if ("XACMLPapServlet.doDelete".equals(username)) { + Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDB.getPolicies().iterator(); + String policyName = getPolicyNameAndVersionFromPolicyFileName(policyToDelete.getPolicyName())[0]; + + logger.info("PolicyDBDao: delete policy from GroupEntity"); + deletePolicyFromGroupEntity(groupToUpdateInDB, policyToDelete, dbPolicyIt, policyName); + } + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Could not get policy to remove: "+pol.getId()); + throw new PersistenceException("Could not get policy to remove: "+pol.getId()); + } + } + + private void deletePolicyFromGroupEntity(GroupEntity groupToUpdateInDB, PolicyEntity policyToDelete, Iterator<PolicyEntity> dbPolicyIt, String policyName) { + try{ + while(dbPolicyIt.hasNext()){ + PolicyEntity dbpolicy = dbPolicyIt.next(); + if(policyToDelete.getScope().equals(dbpolicy.getScope()) && + getPolicyNameAndVersionFromPolicyFileName(dbpolicy.getPolicyName())[0].equals(policyName)) { + dbPolicyIt.remove(); + + logger.info("PolicyDBDao: deleting policy from the existing group:\n " + + "policyName is " + policyToDelete.getScope()+"."+policyToDelete.getPolicyName() + "\n" + + "group is " + groupToUpdateInDB.getGroupId()); + } + } + }catch(Exception e){ + logger.debug(e); + PolicyLogger.error("Could not delete policy with name: "+ policyToDelete.getScope()+"."+policyToDelete.getPolicyName()+"\n ID: "+ policyToDelete.getPolicyId()); + } + } + @Override public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) { logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup("+pdpID+", "+groupID+", "+pdpName+", "+pdpDescription+", "+pdpJmxPort+", "+username+") called"); @@ -2635,6 +2621,30 @@ public class PolicyDBDao { this.pdpId = pdp.getPdpKey(); } } + + private void notifyOthers(long entityId,String entityType){ + notifyOthers(entityId,entityType,null); + } + + private void notifyOthers(long entityId, String entityType, String newGroupId){ + logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called"); + LinkedList<Thread> notifyThreads = new LinkedList<>(); + + //we're going to run notifications in parallel threads to speed things up + for(Object obj : otherServers){ + Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId)); + newNotifyThread.start(); + notifyThreads.add(newNotifyThread); + } + //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes + for(Thread t : notifyThreads){ + try { + t.join(); + } catch (Exception e) { + logger.warn("Could not join a notifcation thread" + e); + } + } + } } private PolicyDBDao(){ @@ -2654,4 +2664,4 @@ public class PolicyDBDao { } } -} +}
\ No newline at end of file |