diff options
Diffstat (limited to 'ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components')
20 files changed, 1421 insertions, 1272 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java index 780ed86c7..c4076b2ad 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -32,6 +33,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; @@ -47,6 +49,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -82,7 +85,6 @@ public class ActionPolicy extends Policy { List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>(); - private CommonClassDao commonClassDao; private static boolean isAttribute = false; @@ -360,7 +362,6 @@ public class ActionPolicy extends Policy { return obligations; } - // if compound setting the inner apply here protected ApplyType getInnerActionApply(String value1Label) { ApplyType actionApply = new ApplyType(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java index 8ca4dfa01..233add1ad 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; + import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -32,16 +35,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -56,6 +49,13 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class ClosedLoopPolicy extends Policy { private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class); @@ -68,7 +68,7 @@ public class ClosedLoopPolicy extends Policy { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { if (policyName.endsWith(".xml")) { @@ -76,7 +76,7 @@ public class ClosedLoopPolicy extends Policy { } try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) { String body = jsonBody; - //Remove the trapMaxAge in Verification Signature + // Remove the trapMaxAge in Verification Signature body = body.replace(",\"trapMaxAge\":null", ""); this.policyAdapter.setJsonBody(body); out.println(body); @@ -85,7 +85,7 @@ public class ClosedLoopPolicy extends Policy { } } - //Utility to read json data from the existing file to a string + // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); @@ -93,7 +93,7 @@ public class ClosedLoopPolicy extends Policy { } - //create the configuration file based on the policy name on adding the extension as .json + // create the configuration file based on the policy name on adding the extension as .json private String getConfigFile(String filename) { filename = FilenameUtils.removeExtension(filename); if (filename.endsWith(".xml")) { @@ -124,13 +124,13 @@ public class ClosedLoopPolicy extends Policy { return successMap; } - //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 + // 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 @Override public boolean prepareToSave() throws PAPException { if (isPreparedToSave()) { - //we have already done this + // we have already done this return true; } @@ -176,17 +176,13 @@ public class ClosedLoopPolicy extends Policy { // Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -340,7 +336,7 @@ public class ClosedLoopPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment5); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("RiskType"); assignment6.setCategory(CATEGORY_RESOURCE); @@ -389,7 +385,6 @@ public class ClosedLoopPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment9); - advices.getAdviceExpression().add(advice); return advices; } @@ -399,5 +394,4 @@ public class ClosedLoopPolicy extends Policy { return policyAdapter.getPolicyData(); } - } 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 d6b09086a..1cab7166a 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * Modified Copyright (C) 2019 Bell Canada. * ================================================================================ @@ -22,6 +22,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -33,17 +36,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.utils.PolicyUtils; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -58,6 +50,14 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.utils.PolicyUtils; + public class ConfigPolicy extends Policy { /** @@ -93,7 +93,6 @@ public class ConfigPolicy extends Policy { } } - // Here we are adding the extension for the configurations file based on the // config type selection for saving. private String getConfigFile(String filename) { @@ -103,8 +102,7 @@ public class ConfigPolicy extends Policy { if (id == null) { return filename; } - switch (id.toUpperCase()) - { + switch (id.toUpperCase()) { case JSON_CONFIG: return filename + ".json"; case XML_CONFIG: @@ -127,7 +125,6 @@ public class ConfigPolicy extends Policy { return filename; } - // Validations for Config form /* * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object... @@ -181,7 +178,7 @@ public class ConfigPolicy extends Policy { } if (!isPreparedToSave()) { - //Prep and configure the policy for saving + // Prep and configure the policy for saving prepareToSave(); } @@ -192,8 +189,8 @@ public class ConfigPolicy extends Policy { return successMap; } - //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 + // 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 @Override public boolean prepareToSave() throws PAPException { @@ -441,7 +438,7 @@ public class ConfigPolicy extends Policy { } } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java index 9809ad498..2151a1988 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import java.util.HashMap; @@ -26,7 +27,7 @@ import java.util.Map; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.PolicyUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -34,26 +35,28 @@ import org.springframework.stereotype.Service; @Service public class CreateBRMSRuleTemplate { - private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); + private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); private static CommonClassDao commonClassDao; @Autowired - public CreateBRMSRuleTemplate(CommonClassDao commonClassDao){ + public CreateBRMSRuleTemplate(CommonClassDao commonClassDao) { CreateBRMSRuleTemplate.commonClassDao = commonClassDao; } - public CreateBRMSRuleTemplate() {} + public CreateBRMSRuleTemplate() { + } public Map<String, String> addRule(String rule, String ruleName, String description, String userID) { - Map<String,String> responseMap = new HashMap<>(); - if(rule!=null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class); - if(duplicateData!=null && !duplicateData.isEmpty()){ + Map<String, String> responseMap = new HashMap<>(); + if (rule != null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")) { + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BrmsParamTemplate.class); + if (duplicateData != null && !duplicateData.isEmpty()) { LOGGER.error("Import new service failed. Service already exists"); responseMap.put("DBError", "EXISTS"); return responseMap; - }else{ - BRMSParamTemplate brmsParamTemplate = new BRMSParamTemplate(); + } else { + BrmsParamTemplate brmsParamTemplate = new BrmsParamTemplate(); brmsParamTemplate.setDescription(description); brmsParamTemplate.setRuleName(ruleName); brmsParamTemplate.setRule(rule); @@ -63,7 +66,7 @@ public class CreateBRMSRuleTemplate { LOGGER.info("Template created with " + ruleName + " by " + userID); } responseMap.put("success", "success"); - }else{ + } else { LOGGER.debug("Error during validating the rule for creating record for BRMS Param Template"); responseMap.put("error", "VALIDATION"); } @@ -73,8 +76,8 @@ public class CreateBRMSRuleTemplate { public static boolean validateRuleParams(String rule) { CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy(); Map<String, String> paramValues = policy.findType(rule); - for(String key : paramValues.keySet()) { - if(!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))){ + for (String key : paramValues.keySet()) { + if (!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))) { return false; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java index 6a0c92650..ffb902bc4 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -38,22 +41,7 @@ import java.util.Map.Entry; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; - import javax.script.SimpleBindings; - -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.BRMSParamTemplate; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -67,6 +55,15 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.BrmsParamTemplate; public class CreateBrmsParamPolicy extends Policy { @@ -91,19 +88,18 @@ public class CreateBrmsParamPolicy extends Policy { copyMap.put("policyVersion", policyAdapter.getHighestVersion().toString()); copyMap.put("unique", ("p" + policyName + UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", "")); - //Finding all the keys in the Map data-structure. + // Finding all the keys in the Map data-structure. Iterator<String> iterator = copyMap.keySet().iterator(); Pattern p; Matcher m; while (iterator.hasNext()) { - //Converting the first character of the key into a lower case. + // Converting the first character of the key into a lower case. String input = iterator.next(); - String output = Character.toLowerCase(input.charAt(0)) + - (input.length() > 1 ? input.substring(1) : ""); - //Searching for a pattern in the String using the key. + String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : ""); + // Searching for a pattern in the String using the key. p = Pattern.compile("\\$\\{" + output + "\\}"); m = p.matcher(ruleContents); - //Replacing the value with the inputs provided by the user in the editor. + // Replacing the value with the inputs provided by the user in the editor. String finalInput = copyMap.get(input); if (finalInput.contains("$")) { finalInput = finalInput.replace("$", "\\$"); @@ -113,7 +109,6 @@ public class CreateBrmsParamPolicy extends Policy { return ruleContents; } - // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); @@ -133,11 +128,10 @@ public class CreateBrmsParamPolicy extends Policy { out.close(); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", - "Exception saving configuration file"); + "Exception saving configuration file"); } } - // Here we are adding the extension for the configurations file based on the // config type selection for saving. private String getConfigFile(String filename) { @@ -151,6 +145,7 @@ public class CreateBrmsParamPolicy extends Policy { } // Validations for Config form + @Override public boolean validateConfigForm() { // Validating mandatory Fields. @@ -187,12 +182,12 @@ public class CreateBrmsParamPolicy extends Policy { private String getValueFromDictionary(String templateName) { String ruleTemplate = null; CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - String queryString = "from BRMSParamTemplate where param_template_name= :templateName"; + String queryString = "from BrmsParamTemplate where param_template_name= :templateName"; SimpleBindings params = new SimpleBindings(); params.put("templateName", templateName); List<Object> result = dbConnection.getDataByQuery(queryString, params); if (!result.isEmpty()) { - BRMSParamTemplate template = (BRMSParamTemplate) result.get(0); + BrmsParamTemplate template = (BrmsParamTemplate) result.get(0); ruleTemplate = template.getRule(); } return ruleTemplate; @@ -222,8 +217,7 @@ public class CreateBrmsParamPolicy extends Policy { if (line.contains("*/")) { try { comment = false; - line = line.split("\\/\\*")[0] - + line.split("\\*\\/")[1].replace("*/", ""); + line = line.split("\\/\\*")[0] + line.split("\\*\\/")[1].replace("*/", ""); } catch (Exception e) { LOGGER.debug(e); line = line.split("\\/\\*")[0]; @@ -255,8 +249,8 @@ public class CreateBrmsParamPolicy extends Policy { break; } } - String param = params.toString().replace("declare Params", "").replace("end", "") - .replaceAll("\\s+", ""); + String param = + params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""); String[] components = param.split(":"); String caption = ""; for (int i = 0; i < components.length; i++) { @@ -274,7 +268,7 @@ public class CreateBrmsParamPolicy extends Policy { LOGGER.debug(e); nextComponent = components[i]; } - //If the type is of type String then we add the UI Item and type to the map. + // If the type is of type String then we add the UI Item and type to the map. if (nextComponent.startsWith("String")) { type = "String"; mapFieldType.put(caption, type); @@ -287,7 +281,7 @@ public class CreateBrmsParamPolicy extends Policy { } } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy", - "Exception parsing file in findType"); + "Exception parsing file in findType"); } } return mapFieldType; @@ -330,10 +324,8 @@ public class CreateBrmsParamPolicy extends Policy { StringBuilder body = new StringBuilder(); try { - body.append( - "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " + - "purpose. \n\t " + - "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); + body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " + + "purpose. \n\t " + "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); body.append("<%$Values="); for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) { String uiKey = entry.getKey(); @@ -344,8 +336,8 @@ public class CreateBrmsParamPolicy extends Policy { body.append("$%> \n*/ \n"); body.append(valueFromDictionary + "\n"); } catch (Exception e) { - PolicyLogger - .error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", + "Exception saving policy"); } saveConfigurations(policyName, body.toString()); @@ -366,12 +358,10 @@ public class CreateBrmsParamPolicy extends Policy { String fileName = policyAdapter.getNewFileName(); String name = fileName.substring(fileName.lastIndexOf("\\") + 1); if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1 - ); + name = fileName.substring(fileName.lastIndexOf("/") + 1); } allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); // Match for ONAPName @@ -415,12 +405,11 @@ public class CreateBrmsParamPolicy extends Policy { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", - "Exception creating ACCESS URI"); + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); accessMatch.setAttributeDesignator(accessAttributeDesignator); accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -438,7 +427,7 @@ public class CreateBrmsParamPolicy extends Policy { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", - "Exception creating Config URI"); + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -459,24 +448,21 @@ public class CreateBrmsParamPolicy extends Policy { rule.setTarget(targetInRule); rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(configPolicy); } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); } setPreparedToSave(true); return true; } // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { + @VisibleForTesting + protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - //Policy Config ID Assignment + // Policy Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("BRMSPARAMID"); @@ -489,8 +475,7 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue = new AttributeValueType(); configNameAttributeValue.setDataType(STRING_DATATYPE); configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. @@ -505,8 +490,7 @@ public class CreateBrmsParamPolicy extends Policy { String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); attributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue)); + assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); // Policy Name Assignment @@ -518,15 +502,12 @@ public class CreateBrmsParamPolicy extends Policy { attributeValue3.setDataType(STRING_DATATYPE); fileName = FilenameUtils.removeExtension(fileName); fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1 - ); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1); if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1 - ); + name = fileName.substring(fileName.lastIndexOf("/") + 1); } attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); // Version Number Assignment @@ -537,8 +518,7 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue4 = new AttributeValueType(); configNameAttributeValue4.setDataType(STRING_DATATYPE); configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); // Onap Name Assignment @@ -549,12 +529,10 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue5 = new AttributeValueType(); configNameAttributeValue5.setDataType(STRING_DATATYPE); configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -564,16 +542,15 @@ public class CreateBrmsParamPolicy extends Policy { configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - // Adding Controller Information. + // Adding Controller Information. if (policyAdapter.getBrmsController() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:" + policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()) - .getController())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("controller:" + policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); } - // Adding Dependencies. + // Adding Dependencies. if (policyAdapter.getBrmsDependency() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); ArrayList<String> dependencies = new ArrayList<>(); @@ -582,18 +559,18 @@ public class CreateBrmsParamPolicy extends Policy { dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); key.append(dependencyName + ","); } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); } - // Dynamic Field Config Attributes. + // Dynamic Field Config Attributes. Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); for (Entry<String, String> map : dynamicFieldConfigAttributes.entrySet()) { advice.getAttributeAssignmentExpression() - .add(createResponseAttributes("key:" + map.getKey(), map.getValue())); + .add(createResponseAttributes("key:" + map.getKey(), map.getValue())); } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java index efa28b2bb..bb46fd6a9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; import java.io.File; import java.io.IOException; @@ -34,15 +36,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -57,6 +50,11 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.rest.adapter.PolicyRestAdapter; public class CreateBrmsRawPolicy extends Policy { @@ -76,8 +74,7 @@ public class CreateBrmsRawPolicy extends Policy { protected void saveConfigurations(String policyName, String jsonBody) { if (policyName.endsWith(".xml")) { - policyName = policyName.substring(0, - policyName.lastIndexOf(".xml")); + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); } try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) { out.println(jsonBody); @@ -195,7 +192,6 @@ public class CreateBrmsRawPolicy extends Policy { } allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); // Match for ONAPName @@ -243,8 +239,7 @@ public class CreateBrmsRawPolicy extends Policy { } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); accessMatch.setAttributeDesignator(accessAttributeDesignator); accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -267,8 +262,7 @@ public class CreateBrmsRawPolicy extends Policy { configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl( - configURI).stringValue()); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); configMatch.setAttributeDesignator(configAttributeDesignator); configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -284,22 +278,18 @@ public class CreateBrmsRawPolicy extends Policy { rule.setTarget(targetInRule); rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(configPolicy); } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); } setPreparedToSave(true); return true; } // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { // Policy Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); @@ -314,8 +304,7 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue = new AttributeValueType(); configNameAttributeValue.setDataType(STRING_DATATYPE); configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. @@ -330,8 +319,7 @@ public class CreateBrmsRawPolicy extends Policy { String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(AttributeValue)); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); // Policy Name Assignment @@ -350,8 +338,7 @@ public class CreateBrmsRawPolicy extends Policy { } System.out.println(name); attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); // Version Number Assignment @@ -362,8 +349,7 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue4 = new AttributeValueType(); configNameAttributeValue4.setDataType(STRING_DATATYPE); configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); // Onap Name Assignment @@ -374,12 +360,10 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue5 = new AttributeValueType(); configNameAttributeValue5.setDataType(STRING_DATATYPE); configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -390,16 +374,15 @@ public class CreateBrmsRawPolicy extends Policy { assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - // Adding Controller Information. + // Adding Controller Information. if (policyAdapter.getBrmsController() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:" + policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()) - .getController())); + advice.getAttributeAssignmentExpression().add(createResponseAttributes( + "controller:" + policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); } - // Adding Dependencies. + // Adding Dependencies. if (policyAdapter.getBrmsDependency() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); ArrayList<String> dependencies = new ArrayList<>(); @@ -408,11 +391,11 @@ public class CreateBrmsRawPolicy extends Policy { dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); key.append(dependencyName).append(","); } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); } - // Dynamic Field Config Attributes. + // Dynamic Field Config Attributes. Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); for (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) { String keyField = entry.getKey(); @@ -420,7 +403,7 @@ public class CreateBrmsRawPolicy extends Policy { .add(createResponseAttributes("key:" + keyField, entry.getValue())); } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java index e74cc3359..a980e70d8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; import java.io.File; import java.io.PrintWriter; @@ -30,16 +32,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -54,40 +46,47 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class CreateClosedLoopPerformanceMetrics extends Policy { - private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); + private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); public CreateClosedLoopPerformanceMetrics() { super(); } - public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){ + public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, final String jsonBody) { - if(policyName.endsWith(".xml")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); - } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json")){ + if (policyName.endsWith(".xml")) { + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); + } + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "." + policyName + ".json")) { out.println(jsonBody); policyAdapter.setJsonBody(jsonBody); policyAdapter.setConfigBodyData(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } } - //getting the policy name and setting to configuration on adding .json + // getting the policy name and setting to configuration on adding .json private String getConfigFile(String filename) { filename = FilenameUtils.removeExtension(filename); if (filename.endsWith(".xml")) { filename = filename.substring(0, filename.length() - 4); } - filename = filename +".json"; + filename = filename + ".json"; return filename; } @@ -95,13 +94,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -109,18 +108,18 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //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 + // 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 @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -148,7 +147,6 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -167,17 +165,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); // Match for ServiceType allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType())); @@ -210,7 +204,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -229,7 +224,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -286,7 +282,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { AttributeValueType AttributeValue = new AttributeValueType(); AttributeValue.setDataType(URI_DATATYPE); - String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName); + String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); AttributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); @@ -344,7 +340,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { advice.getAttributeAssignmentExpression().add(assignment6); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("RiskType"); assignment7.setCategory(CATEGORY_RESOURCE); 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 103928cbc..e18628dff 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 @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -36,6 +38,7 @@ import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -46,17 +49,16 @@ import org.onap.policy.pap.xacml.rest.XACMLPapServlet; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; -import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; +import org.onap.policy.rest.util.MsModelUtils.ModelType; public class CreateNewMicroServiceModel { private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class); private MicroServiceModels newModel = null; - private HashMap<String, MSAttributeObject> classMap = new HashMap<>(); - + private HashMap<String, MsAttributeObject> classMap = new HashMap<>(); - private 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(); @@ -82,7 +84,7 @@ public class CreateNewMicroServiceModel { this.newModel.setUserCreatedBy(userInfo); String cleanUpFile = null; - Map<String, MSAttributeObject> tempMap = new HashMap<>(); + Map<String, MsAttributeObject> tempMap = new HashMap<>(); // Need to delete the file if (importFile.contains(".zip")) { extractFolder(randomID + ".zip"); @@ -98,7 +100,7 @@ public class CreateNewMicroServiceModel { cleanUpFile = "ExtractDir" + File.separator + randomID + ".yml"; } else { - tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID + ".xmi", MODEL_TYPE.XMI); + tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID + ".xmi", ModelType.XMI); classMap.putAll(tempMap); cleanUpFile = "ExtractDir" + File.separator + randomID + ".xmi"; } @@ -109,7 +111,7 @@ public class CreateNewMicroServiceModel { } private void processFiles(String modelName, List<File> fileList) { - Map<String, MSAttributeObject> tempMap; + Map<String, MsAttributeObject> tempMap; for (File file : fileList) { if (file.isFile()) { int indx = file.getName().lastIndexOf('.'); @@ -121,7 +123,7 @@ public class CreateNewMicroServiceModel { } else { - tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); + tempMap = utils.processEpackage(file.getAbsolutePath(), ModelType.XMI); classMap.putAll(tempMap); } } @@ -145,10 +147,9 @@ public class CreateNewMicroServiceModel { try { - utils.parseTosca(fileName); - MSAttributeObject msAttributes = new MSAttributeObject(); + MsAttributeObject msAttributes = new MsAttributeObject(); msAttributes.setClassName(modelName); LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>(); @@ -164,7 +165,7 @@ public class CreateNewMicroServiceModel { returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if (!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())) { + if (!PolicyDbDao.isNullOrEmpty(utils.getListConstraints())) { LinkedHashMap<String, String> enumList = new LinkedHashMap<>(); String[] listArray = utils.getListConstraints().split("#"); for (String str : listArray) { @@ -255,7 +256,7 @@ public class CreateNewMicroServiceModel { public Map<String, String> addValuesToNewModel(String type) { Map<String, String> successMap = new HashMap<>(); - MSAttributeObject mainClass = null; + MsAttributeObject mainClass = null; List<String> dependency = null; String subAttribute = null; @@ -269,13 +270,12 @@ public class CreateNewMicroServiceModel { } mainClass = classMap.get(this.newModel.getModelName()); - if (".yml".equalsIgnoreCase(type)) { newModel.setDependency("[]"); if (mainClass.getSubClass() != null) { String value = new Gson().toJson(mainClass.getSubClass()); - newModel.setSub_attributes(value); + newModel.setSubAttributes(value); } if (mainClass.getAttribute() != null) { @@ -289,7 +289,7 @@ public class CreateNewMicroServiceModel { String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); int equalsIndex = refAttributes.indexOf("="); String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1); - this.newModel.setRef_attributes(refAttributesAfterFirstEquals); + this.newModel.setRefAttributes(refAttributesAfterFirstEquals); } if (mainClass.getEnumType() != null) { @@ -317,7 +317,7 @@ public class CreateNewMicroServiceModel { dependency = utils.getFullDependencyList(dependency, classMap); if (!dependency.isEmpty()) { for (String element : dependency) { - MSAttributeObject temp = new MSAttributeObject(); + MsAttributeObject temp = new MsAttributeObject(); if (classMap.containsKey(element)) { temp = classMap.get(element); mainClass.addAllRefAttribute(temp.getRefAttribute()); @@ -328,14 +328,14 @@ public class CreateNewMicroServiceModel { } subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); - this.newModel.setSub_attributes(subAttribute); + this.newModel.setSubAttributes(subAttribute); if (mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()) { this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); } if (mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()) { this.newModel - .setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); + .setRefAttributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); } if (mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()) { @@ -368,8 +368,8 @@ public class CreateNewMicroServiceModel { model.setDependency(this.newModel.getDependency()); model.setDescription(this.newModel.getDescription()); model.setEnumValues(this.newModel.getEnumValues()); - model.setRef_attributes(this.newModel.getRef_attributes()); - model.setSub_attributes(this.newModel.getSub_attributes()); + model.setRefAttributes(this.newModel.getRefAttributes()); + model.setSubAttributes(this.newModel.getSubAttributes()); model.setDataOrderInfo(this.newModel.getDataOrderInfo()); model.setDecisionModel(this.newModel.isDecisionModel()); model.setRuleFormation(this.newModel.getRuleFormation()); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java index 87c9f9108..8c63a2766 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -43,28 +45,26 @@ import org.onap.policy.pap.xacml.rest.XACMLPapServlet; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; -import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; - -import com.google.gson.Gson; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; +import org.onap.policy.rest.util.MsModelUtils.ModelType; public class CreateNewOptimizationModel { private static final Logger logger = FlexLogger.getLogger(CreateNewOptimizationModel.class); private OptimizationModels newModel = null; - private HashMap<String,MSAttributeObject > classMap = new HashMap<>(); + private HashMap<String, MsAttributeObject> classMap = new HashMap<>(); private static final String EXTRACTDIR = "ExtractDir"; private static final String SUCCESS = "success"; - - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); public CreateNewOptimizationModel() { super(); } - public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, String randomID) { + public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, + String randomID) { this.newModel = new OptimizationModels(); this.newModel.setVersion(version); @@ -75,15 +75,15 @@ public class CreateNewOptimizationModel { this.newModel.setUserCreatedBy(userInfo); String cleanUpFile = null; - Map<String, MSAttributeObject> tempMap = new HashMap<>(); - //Need to delete the file - if (importFile.contains(".zip")){ + Map<String, MsAttributeObject> tempMap = new HashMap<>(); + // Need to delete the file + if (importFile.contains(".zip")) { extractFolder(randomID + ".zip"); 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()){ + // get all the files from a director + for (File file : fileList) { + if (file.isFile()) { processYmlModel(file.toString(), modelName); } } @@ -96,32 +96,32 @@ public class CreateNewOptimizationModel { } catch (IOException e) { logger.error("Failed to unzip model file " + randomID, e); } - }else { - if(importFile.contains(".yml")){ + } else { + if (importFile.contains(".yml")) { - processYmlModel(EXTRACTDIR + File.separator + randomID+".yml", modelName); - cleanUpFile = EXTRACTDIR + File.separator + randomID+".yml"; + processYmlModel(EXTRACTDIR + File.separator + randomID + ".yml", modelName); + cleanUpFile = EXTRACTDIR + File.separator + randomID + ".yml"; - }else{ - tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID+".xmi", MODEL_TYPE.XMI); + } else { + tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID + ".xmi", ModelType.XMI); classMap.putAll(tempMap); - cleanUpFile = EXTRACTDIR + File.separator + randomID+".xmi"; + cleanUpFile = EXTRACTDIR + File.separator + randomID + ".xmi"; } File deleteFile = new File(cleanUpFile); deleteFile.delete(); } } - private void processYmlModel(String fileName, String modelName){ + private void processYmlModel(String fileName, String modelName) { try { utils.parseTosca(fileName); - MSAttributeObject msAttributes= new MSAttributeObject(); + MsAttributeObject msAttributes = new MsAttributeObject(); msAttributes.setClassName(modelName); - LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>(); + LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>(); returnAttributeList.put(modelName, utils.getAttributeString()); msAttributes.setAttribute(returnAttributeList); @@ -129,24 +129,24 @@ public class CreateNewOptimizationModel { msAttributes.setMatchingSet(utils.getMatchableValues()); - LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>(); + LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>(); returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if(!"".equals(utils.getListConstraints())){ - LinkedHashMap<String, String> enumList =new LinkedHashMap<>(); - String[] listArray=utils.getListConstraints().split("#"); - for(String str:listArray){ - String[] strArr= str.split("="); - if(strArr.length>1){ + if (!"".equals(utils.getListConstraints())) { + LinkedHashMap<String, String> enumList = new LinkedHashMap<>(); + String[] listArray = utils.getListConstraints().split("#"); + for (String str : listArray) { + String[] strArr = str.split("="); + if (strArr.length > 1) { enumList.put(strArr[0], strArr[1]); } } msAttributes.setEnumType(enumList); } - classMap=new LinkedHashMap<>(); + classMap = new LinkedHashMap<>(); classMap.put(modelName, msAttributes); } catch (Exception e) { @@ -174,13 +174,13 @@ public class CreateNewOptimizationModel { int buffer = 2048; File file = new File(zipFile); - try(ZipFile zip = new ZipFile(EXTRACTDIR + File.separator +file);){ - String newPath = zipFile.substring(0, zipFile.length() - 4); + try (ZipFile zip = new ZipFile(EXTRACTDIR + File.separator + file);) { + String newPath = zipFile.substring(0, zipFile.length() - 4); new File(newPath).mkdir(); Enumeration zipFileEntries = zip.entries(); // Process each entry - while (zipFileEntries.hasMoreElements()){ + while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); @@ -189,13 +189,13 @@ public class CreateNewOptimizationModel { destinationParent.mkdirs(); - if (!entry.isDirectory()){ + if (!entry.isDirectory()) { int currentByte; byte[] data = new byte[buffer]; - try(FileOutputStream fos = new FileOutputStream(destFile); + try (FileOutputStream fos = new FileOutputStream(destFile); BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); - BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { + BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { while ((currentByte = is.read(data, 0, buffer)) != -1) { dest.write(data, 0, currentByte); @@ -204,7 +204,7 @@ public class CreateNewOptimizationModel { } } - if (currentEntry.endsWith(".zip")){ + if (currentEntry.endsWith(".zip")) { extractFolder(destFile.getAbsolutePath()); } } @@ -216,40 +216,42 @@ public class CreateNewOptimizationModel { public Map<String, String> addValuesToNewModel() { Map<String, String> successMap = new HashMap<>(); - MSAttributeObject mainClass; + MsAttributeObject mainClass; - if (!classMap.containsKey(this.newModel.getModelName())){ - logger.error("Model Provided does not contain the service name provided in request. Unable to import new model"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request"); + if (!classMap.containsKey(this.newModel.getModelName())) { + logger.error( + "Model Provided does not contain the service name provided in request. Unable to import new model"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", + "Unable to pull out required values, file missing service name provided in request"); successMap.put("error", "MISSING"); return successMap; } mainClass = classMap.get(this.newModel.getModelName()); newModel.setDependency("[]"); - if(mainClass.getSubClass() != null){ - String value = new Gson().toJson(mainClass.getSubClass()); - newModel.setSubattributes(value); + if (mainClass.getSubClass() != null) { + String value = new Gson().toJson(mainClass.getSubClass()); + newModel.setSubattributes(value); } - if(mainClass.getAttribute() != null){ - String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndexForAttributes= attributes.indexOf('='); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + if (mainClass.getAttribute() != null) { + String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes = attributes.indexOf('='); + String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1); this.newModel.setAttributes(atttributesAfterFirstEquals); } - if(mainClass.getRefAttribute() != null){ - String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf('='); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + if (mainClass.getRefAttribute() != null) { + String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex = refAttributes.indexOf('='); + String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1); this.newModel.setRefattributes(refAttributesAfterFirstEquals); } - if(mainClass.getEnumType() != null){ + if (mainClass.getEnumType() != null) { this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); } - if(mainClass.getMatchingSet() != null){ + if (mainClass.getMatchingSet() != null) { this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); } @@ -258,14 +260,15 @@ public class CreateNewOptimizationModel { } - public Map<String, String> saveImportService(){ + public Map<String, String> saveImportService() { String modelName = this.newModel.getModelName(); String importedBy = "API"; String version = this.newModel.getVersion(); Map<String, String> successMap = new HashMap<>(); CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+version); - if(result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + version); + if (result.isEmpty()) { OptimizationModels model = new OptimizationModels(); model.setModelName(modelName); model.setVersion(version); @@ -283,7 +286,7 @@ public class CreateNewOptimizationModel { model.setUserCreatedBy(userInfo); dbConnection.save(model); successMap.put(SUCCESS, SUCCESS); - }else{ + } else { successMap.put("DBError", "EXISTS"); logger.error("Import new service failed. Service already exists"); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java index da5c6aea1..ed1d551b4 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.XACML3; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.std.IdentifierImpl; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -40,6 +41,25 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + import org.apache.commons.lang3.StringEscapeUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -63,25 +83,6 @@ import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine; import org.onap.policy.xacml.util.XACMLPolicyScanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; - @Component public class DecisionPolicy extends Policy { @@ -103,7 +104,6 @@ public class DecisionPolicy extends Policy { private static final String POLICY_NAME = "PolicyName"; private static final String DESCRIPTION = "description"; - List<String> dynamicLabelRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>(); @@ -154,16 +154,15 @@ public class DecisionPolicy extends Policy { private void readRawPolicyData() { Object policy; if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) { - policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils - .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); + policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream( + StringEscapeUtils.unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); } else { policy = XACMLPolicyScanner.readPolicy( new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8))); } String policyRawDesc; if (policy instanceof PolicySetType) { - policyRawDesc = - ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; + policyRawDesc = ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; ((PolicySetType) policy).setDescription(policyRawDesc); } else { policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; @@ -204,13 +203,13 @@ public class DecisionPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || - policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) || - policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){ + if (policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) + || policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)) { Map<String, String> yamlParams = new HashMap<>(); - String blackListEntryType = policyAdapter.getBlackListEntryType() != null - ? policyAdapter.getBlackListEntryType() : "Use Manual Entry"; + String blackListEntryType = + policyAdapter.getBlackListEntryType() != null ? policyAdapter.getBlackListEntryType() + : "Use Manual Entry"; String description = policyAdapter.getPolicyDescription() != null ? policyAdapter.getPolicyDescription() : "YAML Guard Policy"; yamlParams.put(DESCRIPTION, description + "@blEntry@" + blackListEntryType + "@blEntry@"); @@ -428,8 +427,7 @@ public class DecisionPolicy extends Policy { yamlSpecs.put("guardActiveStart", constraints.getActive_time_range().get("start")); yamlSpecs.put("guardActiveEnd", constraints.getActive_time_range().get("end")); String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs, - constraints.getBlacklist(), - guard.getMatch_parameters().getTargets()); + constraints.getBlacklist(), guard.getMatch_parameters().getTargets()); // Convert the Policy into Stream input to Policy Adapter. Object policy = XACMLPolicyScanner @@ -713,7 +711,8 @@ public class DecisionPolicy extends Policy { if (!attributeId.startsWith("S_")) { ApplyType innerDecisionApply = generateApplyTypeDataType(functionKey); AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey); - AttributeValueType decisionConditionAttributeValue = generateAttributeValueTypeDataType(functionKey); + AttributeValueType decisionConditionAttributeValue = + generateAttributeValueTypeDataType(functionKey); if (attributeId != null) { attributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -793,7 +792,6 @@ public class DecisionPolicy extends Policy { dataTypeList.add(dataType); } - private String getDataType(String key) { DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key); @@ -826,8 +824,7 @@ public class DecisionPolicy extends Policy { private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) { AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": attributeDesignator.setDataType(INTEGER_DATATYPE); break; @@ -839,8 +836,7 @@ public class DecisionPolicy extends Policy { private ApplyType generateApplyTypeDataType(String functionKey) { ApplyType applyType = new ApplyType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": applyType.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); break; @@ -852,8 +848,7 @@ public class DecisionPolicy extends Policy { private AttributeValueType generateAttributeValueTypeDataType(String functionKey) { AttributeValueType applyType = new AttributeValueType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": applyType.setDataType(INTEGER_DATATYPE); break; @@ -864,8 +859,10 @@ public class DecisionPolicy extends Policy { } private void applyTwoTextFieldRuleAttribute(ApplyType decisionApply, String value1, String functionKey) { - decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); - decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); + decisionApply.getExpression() + .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); + decisionApply.getExpression() + .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); } private ApplyType generateApplyTypeDataType(String value1, String functionKey) { @@ -874,10 +871,8 @@ public class DecisionPolicy extends Policy { attributeDesignator.setCategory(CATEGORY_RESOURCE); // Here set actual field values - attributeDesignator - .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); - innerApply.getExpression() - .add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); + attributeDesignator.setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); + innerApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); return innerApply; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java index eca473f41..e153ea834 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java @@ -26,6 +26,7 @@ import com.att.research.xacml.std.IdentifierImpl; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonpatch.diff.JsonDiff; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -41,11 +42,27 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.script.SimpleBindings; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.FilenameUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -66,19 +83,6 @@ import org.onap.policy.rest.jpa.TermList; import org.onap.policy.rest.jpa.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @Component public class FirewallConfigPolicy extends Policy { @@ -114,11 +118,11 @@ public class FirewallConfigPolicy extends Policy { LOGGER.debug("Configuration is succesfully saved"); } } catch (IOException e) { - LOGGER.error("Save of configuration to file" +fileName+ "failed",e); + LOGGER.error("Save of configuration to file" + fileName + "failed", e); } } - //Utility to read json data from the existing file to a string + // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); @@ -127,11 +131,11 @@ public class FirewallConfigPolicy extends Policy { @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ + if (!isPreparedToSave()) { prepareToSave(); } @@ -139,9 +143,10 @@ public class FirewallConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); Boolean dbIsUpdated = false; - if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){ + if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())) { if (policyAdapter.isEditPolicy()) { - dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); + dbIsUpdated = + updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); } else { try { dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody()); @@ -153,14 +158,14 @@ public class FirewallConfigPolicy extends Policy { dbIsUpdated = true; } - if(dbIsUpdated) { - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + if (dbIsUpdated) { + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); } else { PolicyLogger.error("Failed to Update the Database Dictionary Tables."); - //remove the new json file + // remove the new json file String jsonBody = policyAdapter.getPrevJsonBody(); - if (jsonBody!=null){ + if (jsonBody != null) { saveConfigurations(policyName, jsonBody); } else { saveConfigurations(policyName, ""); @@ -171,13 +176,13 @@ public class FirewallConfigPolicy extends Policy { return successMap; } - //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 + // 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 @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -196,13 +201,13 @@ public class FirewallConfigPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - //String oldPolicyName = policyName.replace(".xml", ""); + // String oldPolicyName = policyName.replace(".xml", ""); String scope = policyName.substring(0, policyName.indexOf('.')); - String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", ""); + String dbPolicyName = policyName.substring(policyName.indexOf('.') + 1).replace(".xml", ""); - int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1)); - dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1); - if(oldversion > 1){ + int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.') + 1)); + dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.') + 1); + if (oldversion > 1) { oldversion = oldversion - 1; dbPolicyName = dbPolicyName + oldversion + ".xml"; } @@ -277,7 +282,8 @@ public class FirewallConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -298,7 +304,8 @@ public class FirewallConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -332,7 +339,7 @@ public class FirewallConfigPolicy extends Policy { // Data required for Advice part is setting here. private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - //Firewall Config ID Assignment + // Firewall Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("firewallConfigID"); @@ -349,7 +356,7 @@ public class FirewallConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. - //URL ID Assignment + // URL ID Assignment AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); assignment2.setAttributeId("URLID"); assignment2.setCategory(CATEGORY_RESOURCE); @@ -365,7 +372,7 @@ public class FirewallConfigPolicy extends Policy { assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); - //Policy Name Assignment + // Policy Name Assignment AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); assignment3.setAttributeId("PolicyName"); assignment3.setCategory(CATEGORY_RESOURCE); @@ -382,7 +389,7 @@ public class FirewallConfigPolicy extends Policy { assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); - //Version Number Assignment + // Version Number Assignment AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); assignment4.setAttributeId("VersionNumber"); assignment4.setCategory(CATEGORY_RESOURCE); @@ -393,7 +400,7 @@ public class FirewallConfigPolicy extends Policy { assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); - //Onap Name Assignment + // Onap Name Assignment AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); assignment5.setAttributeId("matching:" + ONAPID); assignment5.setCategory(CATEGORY_RESOURCE); @@ -403,7 +410,7 @@ public class FirewallConfigPolicy extends Policy { assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -414,7 +421,7 @@ public class FirewallConfigPolicy extends Policy { assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("RiskType"); assignment7.setCategory(CATEGORY_RESOURCE); @@ -466,19 +473,18 @@ public class FirewallConfigPolicy extends Policy { return advices; } - - private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException { + private Boolean insertFirewallDicionaryData(String jsonBody) throws SQLException { CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject json = null; if (jsonBody != null) { - //Read jsonBody to JsonObject + // Read jsonBody to JsonObject json = stringToJson(jsonBody); JsonArray firewallRules = null; JsonArray serviceGroup = null; JsonArray addressGroup = null; - //insert data into tables + // insert data into tables try { firewallRules = json.getJsonArray("firewallRuleList"); serviceGroup = json.getJsonArray("serviceGroups"); @@ -487,28 +493,28 @@ public class FirewallConfigPolicy extends Policy { * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ if (firewallRules != null) { - for(int i = 0;i<firewallRules.size();i++) { + for (int i = 0; i < firewallRules.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(i); - //get values from JSON fields of firewallRulesList Array + // get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString(); String action = ruleListobj.get("action").toString(); String description = ruleListobj.get("description").toString(); List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { TermList termEntry = (TermList) result.get(0); dbConnection.delete(termEntry); } - //getting fromZone Array field from the firewallRulesList + // getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) { + for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); if (fromZoneString != null) { @@ -517,12 +523,12 @@ public class FirewallConfigPolicy extends Policy { fromZoneString = value; } } - String fromZoneInsert = "'"+fromZoneString+"'"; + String fromZoneInsert = "'" + fromZoneString + "'"; - //getting toZone Array field from the firewallRulesList + // getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; - for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) { + for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); if (toZoneString != null) { @@ -531,19 +537,19 @@ public class FirewallConfigPolicy extends Policy { toZoneString = value; } } - String toZoneInsert = "'"+toZoneString+"'"; + String toZoneInsert = "'" + toZoneString + "'"; - //getting sourceList Array fields from the firewallRulesList + // getting sourceList Array fields from the firewallRulesList JsonArray srcListArray = ruleListobj.getJsonArray("sourceList"); String srcListString = null; - for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) { + for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = srcListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = srcListObj.get("value").toString(); @@ -552,19 +558,19 @@ public class FirewallConfigPolicy extends Policy { srcListString = getLeftOrRight(srcListString, value); } - String srcListInsert = "'"+srcListString+"'"; + String srcListInsert = "'" + srcListString + "'"; - //getting destinationList Array fields from the firewallRulesList + // getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; - for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) { + for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destListObj.get("value").toString(); @@ -572,19 +578,20 @@ public class FirewallConfigPolicy extends Policy { destListString = getLeftOrRight(destListString, value); } - String destListInsert = "'"+destListString+"'"; + String destListInsert = "'" + destListString + "'"; - //getting destServices Array fields from the firewallRulesList + // getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; - for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { + for (int destPortListIndex = 0; destPortListIndex < destServicesArray + .size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destServicesObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destServicesObj.get("value").toString(); @@ -592,7 +599,7 @@ public class FirewallConfigPolicy extends Policy { destPortListString = getLeftOrRight(destPortListString, value); } - String destPortListInsert = "'"+destPortListString+"'"; + String destPortListInsert = "'" + destPortListString + "'"; /* * Create Queries to INSERT data into database tables and execute @@ -603,16 +610,16 @@ public class FirewallConfigPolicy extends Policy { TermList termEntry = new TermList(); termEntry.setTermName(ruleName); - termEntry.setSrcIPList(srcListInsert); - termEntry.setDestIPList(destListInsert); + termEntry.setSrcIpList(srcListInsert); + termEntry.setDestIpList(destListInsert); termEntry.setProtocolList("null"); termEntry.setPortList("null"); termEntry.setSrcPortList("null"); termEntry.setDestPortList(destPortListInsert); termEntry.setAction(action); termEntry.setDescription(description); - termEntry.setFromZones(fromZoneInsert); - termEntry.setToZones(toZoneInsert); + termEntry.setFromZone(fromZoneInsert); + termEntry.setToZone(toZoneInsert); termEntry.setUserCreatedBy(userInfo); dbConnection.save(termEntry); @@ -624,35 +631,35 @@ public class FirewallConfigPolicy extends Policy { * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables */ if (serviceGroup != null) { - for(int i = 0; i < serviceGroup.size() ; i++) { + for (int i = 0; i < serviceGroup.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(i); String serviceListName = svcGroupListobj.get("name").toString(); String description = null; - if (svcGroupListobj.containsKey("description")){ + if (svcGroupListobj.containsKey("description")) { description = svcGroupListobj.get("description").toString(); } - //getting members Array from the serviceGroup + // getting members Array from the serviceGroup JsonArray membersArray = svcGroupListobj.getJsonArray("members"); - //String type = svcGroupListobj.get("type").toString(); + // String type = svcGroupListobj.get("type").toString(); Boolean isServiceGroup = false; - if (membersArray!=null){ + if (membersArray != null) { String membersType = membersArray.getJsonObject(0).get("type").toString(); if (membersType.contains("REFERENCE")) { isServiceGroup = true; } } - //Insert values into GROUPSERVICELIST table if name begins with Group + // Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray); - } else { //Insert JSON data serviceList table, protollist table, and portlist table + } else { // Insert JSON data serviceList table, protollist table, and portlist table String type = svcGroupListobj.get("type").toString(); String transportProtocol = svcGroupListobj.get("transportProtocol").toString(); String ports = svcGroupListobj.get("ports").toString(); @@ -660,7 +667,8 @@ public class FirewallConfigPolicy extends Policy { /* * Create Queries to INSERT data into database table and execute */ - saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports); + saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, + ports); saveProtocolListToDb(dbConnection, transportProtocol); @@ -673,19 +681,19 @@ public class FirewallConfigPolicy extends Policy { * Inserting addressGroup data into the ADDRESSGROUP table */ if (addressGroup != null) { - for(int i = 0; i < addressGroup.size(); i++) { + for (int i = 0; i < addressGroup.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(i); - //create JSON array for members + // create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString(); String description = null; - if (addressGroupObj.containsKey("description")){ + if (addressGroupObj.containsKey("description")) { description = addressGroupObj.get("description").toString(); } @@ -693,13 +701,11 @@ public class FirewallConfigPolicy extends Policy { String type = null; for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); - //String value = membersObj.get("value").toString(); type = membersObj.get("type").toString().replace("\"", ""); - String value = null; prefixIP = getName(prefixIP, membersObj, type); } - String prefixList = "'"+prefixIP+"'"; + String prefixList = "'" + prefixIP + "'"; Boolean isAddressGroup = type.contains("REFERENCE"); @@ -711,8 +717,9 @@ public class FirewallConfigPolicy extends Policy { } } removeDuplicateValuesFromLookup(dbConnection); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", + "Exception getting Json values"); return false; } return true; @@ -731,33 +738,34 @@ public class FirewallConfigPolicy extends Policy { + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;"; dbConnection.updateQuery(protoDelete); - //PortList Table + // PortList Table String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; dbConnection.updateQuery(portListDelete); - //PrefixList Table + // PrefixList Table String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; dbConnection.updateQuery(prefixListDelete); - //GroupServiceList + // GroupServiceList String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " + "groupservicelist.serviceList = g1.serviceList; "; dbConnection.updateQuery(groupServiceDelete); } - private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) { + private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, + JsonArray membersArray) { String name = null; - for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) { + for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); String type = membersObj.get("type").toString().replace("\"", ""); name = getName(name, membersObj, type); } - String nameInsert = "'"+name+"'"; + String nameInsert = "'" + name + "'"; GroupServiceList groupServiceEntry = new GroupServiceList(); groupServiceEntry.setGroupName(serviceListName); groupServiceEntry.setServiceList(nameInsert); @@ -766,9 +774,9 @@ public class FirewallConfigPolicy extends Policy { private String getName(String name, JsonObject membersObj, String type) { String value; - if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ + if (type.equals("REFERENCE") || type.equals("GROUP") || type.equals("SERVICE")) { value = membersObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = membersObj.get("value").toString(); @@ -791,7 +799,6 @@ public class FirewallConfigPolicy extends Policy { return name; } - private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) { CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject oldJson = null; @@ -802,7 +809,7 @@ public class FirewallConfigPolicy extends Policy { oldJson = stringToJson(prevJsonBody); newJson = stringToJson(jsonBody); - //if no changes to the json then return true + // if no changes to the json then return true if (oldJson != null && oldJson.equals(newJson)) { return true; } @@ -815,12 +822,12 @@ public class FirewallConfigPolicy extends Policy { serviceGroup = newJson.getJsonArray("serviceGroups"); addressGroup = newJson.getJsonArray("addressGroups"); - //insert data into tables + // insert data into tables try { JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody); - for (int i = 0; i<jsonDiff.size(); i++) { - //String path = jsonDiff.get(i).asText(); + for (int i = 0; i < jsonDiff.size(); i++) { + // String path = jsonDiff.get(i).asText(); String jsonpatch = jsonDiff.get(i).toString(); JsonObject patchObj = stringToJson(jsonpatch); @@ -831,29 +838,29 @@ public class FirewallConfigPolicy extends Policy { /* * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ - for(int ri = 0; ri < firewallRules.size(); ri++) { + for (int ri = 0; ri < firewallRules.size(); ri++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(ri); - //get values from JSON fields of firewallRulesList Array + // get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\''); String action = ruleListobj.get("action").toString().replace('"', '\''); String description = ruleListobj.get("description").toString().replace('"', '\''); List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { TermList termEntry = (TermList) result.get(0); dbConnection.delete(termEntry); } - //getting fromZone Array field from the firewallRulesList + // getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) { + for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); @@ -865,13 +872,12 @@ public class FirewallConfigPolicy extends Policy { } } - String fromZoneInsert = "'"+fromZoneString+"'"; + String fromZoneInsert = "'" + fromZoneString + "'"; - //getting toZone Array field from the firewallRulesList + // getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; - for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); @@ -884,18 +890,18 @@ public class FirewallConfigPolicy extends Policy { } } - String toZoneInsert = "'"+toZoneString+"'"; - //getting sourceList Array fields from the firewallRulesList + String toZoneInsert = "'" + toZoneString + "'"; + // getting sourceList Array fields from the firewallRulesList JsonArray srcListArray = ruleListobj.getJsonArray("sourceList"); String srcListString = null; - for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) { + for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = srcListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = srcListObj.get("value").toString(); @@ -904,19 +910,19 @@ public class FirewallConfigPolicy extends Policy { srcListString = getLeftOrRight(srcListString, value); } - String srcListInsert = "'"+srcListString+"'"; + String srcListInsert = "'" + srcListString + "'"; - //getting destinationList Array fields from the firewallRulesList + // getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; - for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) { + for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destListObj.get("value").toString(); @@ -924,19 +930,20 @@ public class FirewallConfigPolicy extends Policy { destListString = getLeftOrRight(destListString, value); } - String destListInsert = "'"+destListString+"'"; + String destListInsert = "'" + destListString + "'"; - //getting destServices Array fields from the firewallRulesList + // getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; - for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { + for (int destPortListIndex = 0; destPortListIndex < destServicesArray + .size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destServicesObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destServicesObj.get("value").toString(); @@ -944,7 +951,7 @@ public class FirewallConfigPolicy extends Policy { destPortListString = getLeftOrRight(destPortListString, value); } - String destPortListInsert = "'"+destPortListString+"'"; + String destPortListInsert = "'" + destPortListString + "'"; /* * Create Queries to INSERT data into database tables and execute @@ -955,21 +962,22 @@ public class FirewallConfigPolicy extends Policy { TermList termEntry = new TermList(); termEntry.setTermName(ruleName); - termEntry.setSrcIPList(srcListInsert); - termEntry.setDestIPList(destListInsert); + termEntry.setSrcIpList(srcListInsert); + termEntry.setDestIpList(destListInsert); termEntry.setProtocolList("null"); termEntry.setPortList("null"); termEntry.setSrcPortList("null"); termEntry.setDestPortList(destPortListInsert); termEntry.setAction(action); termEntry.setDescription(description); - termEntry.setFromZones(fromZoneInsert); - termEntry.setToZones(toZoneInsert); + termEntry.setFromZone(fromZoneInsert); + termEntry.setToZone(toZoneInsert); termEntry.setUserCreatedBy(userInfo); dbConnection.save(termEntry); - List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action); - if(actionResult == null || actionResult.isEmpty()){ + List<Object> actionResult = + dbConnection.getDataById(ActionList.class, "actionName", action); + if (actionResult == null || actionResult.isEmpty()) { saveActionListToDb(dbConnection, action); } } @@ -977,61 +985,66 @@ public class FirewallConfigPolicy extends Policy { if (path.contains("serviceGroups")) { /* - * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables + * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList + * tables */ - for(int si = 0; si < serviceGroup.size(); si++) { + for (int si = 0; si < serviceGroup.size(); si++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(si); String groupName = svcGroupListobj.get("name").toString().replace('"', '\''); String description = null; - if (svcGroupListobj.containsKey("description")){ + if (svcGroupListobj.containsKey("description")) { description = svcGroupListobj.get("description").toString().replace('"', '\''); } JsonArray membersArray = svcGroupListobj.getJsonArray("members"); Boolean isServiceGroup = false; - if (membersArray!=null){ + if (membersArray != null) { String membersType = membersArray.getJsonObject(0).get("type").toString(); if (membersType.contains("REFERENCE")) { isServiceGroup = true; } } - //Insert values into GROUPSERVICELIST table if name begins with Group + // Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { - List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(GroupServiceList.class, "name", groupName); + if (result != null && !result.isEmpty()) { GroupServiceList groupEntry = (GroupServiceList) result.get(0); dbConnection.delete(groupEntry); } saveGroupServiceListTableToDb(dbConnection, groupName, membersArray); - } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table + } else { // Insert JSON data serviceGroup table, protocollist table, and portlist table String type = svcGroupListobj.get("type").toString().replace('"', '\''); - String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); + String transportProtocol = + svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); String ports = svcGroupListobj.get("ports").toString().replace('"', '\''); List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { ServiceList serviceEntry = (ServiceList) result.get(0); dbConnection.delete(serviceEntry); } - saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports); + saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, + ports); - List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); - if(protocolResult == null || protocolResult.isEmpty()){ + List<Object> protocolResult = + dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); + if (protocolResult == null || protocolResult.isEmpty()) { saveProtocolListToDb(dbConnection, transportProtocol); } List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports); - if(portResult == null || portResult.isEmpty()){ + if (portResult == null || portResult.isEmpty()) { savePortListToDb(dbConnection, ports); } } @@ -1042,46 +1055,47 @@ public class FirewallConfigPolicy extends Policy { /* * Inserting addressGroup data into the ADDRESSGROUP table */ - for(int ai=0; ai < addressGroup.size() ; ai++) { + for (int ai = 0; ai < addressGroup.size(); ai++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(ai); - //create JSON array for members + // create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\''); String description = null; - if (addressGroupObj.containsKey("description")){ + if (addressGroupObj.containsKey("description")) { description = addressGroupObj.get("description").toString().replace('"', '\''); } String prefixIP = null; String type = null; - for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) { + for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); type = membersObj.get("type").toString().replace("\"", ""); - String value = null; prefixIP = getName(prefixIP, membersObj, type); } - String prefixList = "'"+prefixIP+"'"; + String prefixList = "'" + prefixIP + "'"; Boolean isAddressGroup = type.contains("REFERENCE"); if (isAddressGroup) { - List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); + if (result != null && !result.isEmpty()) { AddressGroup addressGroupEntry = (AddressGroup) result.get(0); dbConnection.delete(addressGroupEntry); } saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList); } else { - List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); + if (result != null && !result.isEmpty()) { PrefixList prefixListEntry = (PrefixList) result.get(0); dbConnection.delete(prefixListEntry); } @@ -1091,8 +1105,9 @@ public class FirewallConfigPolicy extends Policy { } } removeDuplicateValuesFromLookup(dbConnection); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", + "Exception executing Firewall queries"); return false; } return true; @@ -1123,18 +1138,20 @@ public class FirewallConfigPolicy extends Policy { dbConnection.save(protocolEntry); } - private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) { + private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, + String transportProtocol, String ports) { ServiceList serviceListEntry = new ServiceList(); serviceListEntry.setServiceName(groupName); serviceListEntry.setServiceDescription(description); serviceListEntry.setServiceType(type); - serviceListEntry.setServiceTransProtocol(transportProtocol); + serviceListEntry.setServiceTransportProtocol(transportProtocol); serviceListEntry.setServiceAppProtocol("null"); serviceListEntry.setServicePorts(ports); dbConnection.save(serviceListEntry); } - private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) { + private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, + String prefixList) { PrefixList newPrefixList = new PrefixList(); newPrefixList.setPrefixListName(addressGroupName); newPrefixList.setDescription(description); @@ -1142,7 +1159,8 @@ public class FirewallConfigPolicy extends Policy { dbConnection.save(newPrefixList); } - private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) { + private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, + String prefixList) { AddressGroup newAddressGroup = new AddressGroup(); newAddressGroup.setGroupName(addressGroupName); newAddressGroup.setDescription(description); @@ -1151,7 +1169,7 @@ public class FirewallConfigPolicy extends Policy { } private JsonObject stringToJson(String jsonString) { - //Read jsonBody to JsonObject + // Read jsonBody to JsonObject StringReader in = new StringReader(jsonString); JsonReader jsonReader = Json.createReader(in); JsonObject json = jsonReader.readObject(); @@ -1167,7 +1185,7 @@ public class FirewallConfigPolicy extends Policy { oldJason = JsonLoader.fromString(oldJson); updatedJason = JsonLoader.fromString(json); } catch (IOException e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } return JsonDiff.asJson(oldJason, updatedJason); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java index fc08b643e..72e6f488a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; @@ -34,7 +36,9 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.List; + import javax.persistence.PersistenceException; + import org.apache.commons.io.FilenameUtils; import org.hibernate.Query; import org.hibernate.Session; @@ -44,8 +48,8 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.XacmlRestProperties; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; import org.onap.policy.rest.jpa.PolicyEntity; @@ -70,7 +74,6 @@ public class HandleIncomingNotifications { public static final String OTHER_CONFIG = "OTHER"; public static final String AUDIT_USER = "audit"; - private static SessionFactory sessionfactory; @Autowired @@ -82,15 +85,24 @@ public class HandleIncomingNotifications { // Default Constructor } + /** + * Handle the incoming HTTP notification. + * + * @param url the URL + * @param entityId the entity id + * @param entityType the entity type + * @param extraData extra data + * @param xacmlPapServlet the servlet to use + */ public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData, XACMLPapServlet xacmlPapServlet) { logger.info("DBDao url: " + url + " has reported an update on " + entityType + " entity " + entityId); - PolicyDBDaoTransaction transaction = PolicyDBDao.getPolicyDBDaoInstance().getNewTransaction(); + PolicyDbDaoTransaction transaction = PolicyDbDao.getPolicyDbDaoInstance().getNewTransaction(); // although its named retries, this is the total number of tries int retries; try { retries = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES)); + .parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES)); } catch (Exception e) { logger.error("xacml.rest.pap.incomingnotification.tries property not set, using a default of 3." + e); retries = 3; @@ -101,6 +113,7 @@ public class HandleIncomingNotifications { retries = 1; } int pauseBetweenRetries = 1000; + switch (entityType) { case POLICY_NOTIFICATION: @@ -110,7 +123,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingPolicyChange(" + url + ", " + entityId + ", " + extraData + ")"); } @@ -129,7 +142,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingPdpChange(" + url + ", " + entityId + ", " + transaction + ")"); } @@ -148,7 +161,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingGroupChange(" + url + ", " + entityId + ", " + extraData + ", " + transaction + ", " + xacmlPapServlet + ")"); } @@ -160,14 +173,25 @@ public class HandleIncomingNotifications { } } break; + + default: } // no changes should be being made in this function, we still need to // close transaction.rollbackTransaction(); } - private void handleIncomingGroupChange(String groupId, String extraData, PolicyDBDaoTransaction transaction) - throws PAPException, PolicyDBException { + /** + * Handle an incoming group change. + * + * @param groupId the group ID + * @param extraData extra data + * @param transaction the transaction + * @throws PAPException on PAP exceptions + * @throws PolicyDbException on Policy DB exceptions + */ + private void handleIncomingGroupChange(String groupId, String extraData, PolicyDbDaoTransaction transaction) + throws PAPException, PolicyDbException { GroupEntity groupRecord = null; long groupIdLong = -1; try { @@ -178,7 +202,7 @@ public class HandleIncomingNotifications { try { groupRecord = transaction.getGroup(groupIdLong); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp group record with transaction.getGroup(" + groupIdLong + ");"); throw new PAPException("Could not get local group " + groupIdLong); } @@ -189,7 +213,7 @@ public class HandleIncomingNotifications { // does group folder exist OnapPDPGroup localGroup = null; try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); } catch (Exception e) { logger.warn("Caught PAPException trying to get local pdp group with papEngine.getGroup(" + groupId + ");", e); @@ -197,7 +221,7 @@ public class HandleIncomingNotifications { if (localGroup == null && extraData != null) { // here we can try to load an old group id from the extraData try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData); } catch (Exception e) { logger.warn( "Caught PAPException trying to get local pdp group with papEngine.getGroup(" + extraData + ");", @@ -208,17 +232,17 @@ public class HandleIncomingNotifications { OnapPDPGroup newLocalGroup = null; if (extraData != null) { try { - newLocalGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData); + newLocalGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get new pdp group with papEngine.getGroup(" + extraData + ");"); } } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get remove pdp group with papEngine.removeGroup(" + localGroup + ", " + newLocalGroup + ");"); throw new PAPException("Could not remove group " + groupId); @@ -226,18 +250,21 @@ public class HandleIncomingNotifications { } else if (localGroup == null) { // creating a new group try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newGroup(groupRecord.getgroupName(), + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newGroup(groupRecord.getGroupName(), groupRecord.getDescription()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to create pdp group with " + + "papEngine.newGroup(groupRecord.getGroupName(), groupRecord.getDescription());"); throw new PAPException("Could not create group " + groupRecord); } try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get pdp group we just created with papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs or policies in the new group may not have been added"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get pdp group we just created with " + + "papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs " + + "or policies in the new group may not have been added"); return; } // add possible pdps to group @@ -245,11 +272,12 @@ public class HandleIncomingNotifications { for (Object pdpO : pdpsInGroup) { PdpEntity pdp = (PdpEntity) pdpO; try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup, + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), " + + "localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); throw new PAPException("Could not create pdp " + pdp); } } @@ -269,36 +297,36 @@ public class HandleIncomingNotifications { // set default if it should be if (!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().setDefaultGroup(localGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().setDefaultGroup(localGroup); return; } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to set default group with papEngine.SetDefaultGroup(" + localGroupClone + ");"); throw new PAPException("Could not set default group to " + localGroupClone); } } boolean needToUpdate = false; - if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord, transaction)) { + if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord)) { needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) - || !PolicyDBDao.stringEquals(localGroupClone.getName(), groupRecord.getgroupName())) { + if (!PolicyDbDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) + || !PolicyDbDao.stringEquals(localGroupClone.getName(), groupRecord.getGroupName())) { // changing ids // we do not want to change the id, the papEngine will do this // for us, it needs to know the old id - localGroupClone.setName(groupRecord.getgroupName()); + localGroupClone.setName(groupRecord.getGroupName()); needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) { + if (!PolicyDbDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) { localGroupClone.setDescription(groupRecord.getDescription()); needToUpdate = true; } if (needToUpdate) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updateGroup(localGroupClone); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updateGroup(localGroupClone); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to update group with papEngine.updateGroup(" + localGroupClone + ");"); throw new PAPException("Could not update group " + localGroupClone); @@ -310,7 +338,7 @@ public class HandleIncomingNotifications { // this will also handle removes, since incoming pdpGroup has no policies // internally, we are just going to add them all in from the db private boolean updateGroupPoliciesInFileSystem(OnapPDPGroup pdpGroup, OnapPDPGroup oldPdpGroup, - GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException, PolicyDBException { + GroupEntity groupRecord) throws PAPException, PolicyDbException { if (!(pdpGroup instanceof StdPDPGroup)) { throw new PAPException("group is not a StdPDPGroup"); } @@ -325,7 +353,7 @@ public class HandleIncomingNotifications { } for (PolicyEntity policy : groupRecord.getPolicies()) { String pdpPolicyName = - PolicyDBDao.getPolicyDBDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope()); + PolicyDbDao.getPolicyDbDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope()); if (group.getPolicy(pdpPolicyName) == null) { didUpdate = true; if (currentPolicySet.containsKey(pdpPolicyName)) { @@ -335,7 +363,7 @@ public class HandleIncomingNotifications { "PolicyDBDao: Adding the new policy to the PDP group after notification: " + pdpPolicyName); InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); group.copyPolicyToFile(pdpPolicyName, policyStream); - ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDBDao.getPolicyDBDaoInstance() + ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDbDao.getPolicyDbDaoInstance() .removeExtensionAndVersionFromPolicyName(pdpPolicyName)); try { policyStream.close(); @@ -354,7 +382,7 @@ public class HandleIncomingNotifications { return didUpdate; } - private void handleIncomingPdpChange(String pdpId, PolicyDBDaoTransaction transaction) throws PAPException { + private void handleIncomingPdpChange(String pdpId, PolicyDbDaoTransaction transaction) throws PAPException { // get pdp long pdpIdLong = -1; try { @@ -366,7 +394,7 @@ public class HandleIncomingNotifications { try { pdpRecord = transaction.getPdp(pdpIdLong); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp record with transaction.getPdp(" + pdpIdLong + ");"); throw new PAPException("Could not get local pdp " + pdpIdLong); } @@ -375,15 +403,15 @@ public class HandleIncomingNotifications { } OnapPDP localPdp = null; try { - localPdp = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId()); + localPdp = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId()); } catch (PAPException e) { logger.warn("Caught PAPException trying to get local pdp with papEngine.getPDP(" + pdpId + ");", e); } if (localPdp != null && pdpRecord.isDeleted()) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removePDP(localPdp); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removePDP(localPdp); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get remove pdp with papEngine.removePDP(" + localPdp + ");"); throw new PAPException("Could not remove pdp " + pdpId); } @@ -393,17 +421,18 @@ public class HandleIncomingNotifications { OnapPDPGroup localGroup = null; try { localGroup = - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId()); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get local group to add pdp to with " + + "papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); throw new PAPException("Could not get local group"); } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup, + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup, pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to create pdp with papEngine.newPDP(" + pdpRecord.getPdpId() + ", " + localGroup + ", " + pdpRecord.getPdpName() + ", " + pdpRecord.getDescription() + ", " + pdpRecord.getJmxPort() + ");"); @@ -411,41 +440,41 @@ public class HandleIncomingNotifications { } } else { boolean needToUpdate = false; - if (!PolicyDBDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId()) - || !PolicyDBDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) { + if (!PolicyDbDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId()) + || !PolicyDbDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) { // again, we don't want to change the id, the papEngine will do // this localPdp.setName(pdpRecord.getPdpName()); needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) { + if (!PolicyDbDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) { localPdp.setDescription(pdpRecord.getDescription()); needToUpdate = true; } String localPdpGroupId = null; try { - localPdpGroupId = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDPGroup(localPdp).getId(); + localPdpGroupId = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getPDPGroup(localPdp).getId(); } catch (PAPException e) { // could be null or something, just warn at this point - logger.warn( - "Caught PAPException trying to get id of local group that pdp is in with localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();", - e); + logger.warn("Caught PAPException trying to get id of local group that pdp is in with " + + "localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();", e); } - if (!PolicyDBDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) { + if (!PolicyDbDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) { OnapPDPGroup newPdpGroup = null; try { - newPdpGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine() + newPdpGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine() .getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e) { // ok, now we have an issue. Time to stop things - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get id of local group to move pdp to with " + + "papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); throw new PAPException("Could not get local group"); } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);"); throw new PAPException("Could not move pdp " + localPdp); } @@ -456,9 +485,9 @@ public class HandleIncomingNotifications { } if (needToUpdate) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updatePDP(localPdp); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updatePDP(localPdp); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to update pdp with papEngine.updatePdp(" + localPdp + ");"); throw new PAPException("Could not update pdp " + localPdp); } @@ -490,22 +519,22 @@ public class HandleIncomingNotifications { if (policy.getConfigurationData() != null) { subFile = - getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDBDao.CONFIG); + getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDbDao.CONFIG); } else if (policy.getActionBodyEntity() != null) { - subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDBDao.ACTION); + subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDbDao.ACTION); } if (subFile != null) { Files.deleteIfExists(subFile); } if (policy.getConfigurationData() != null) { - writePolicySubFile(policy, PolicyDBDao.CONFIG); + writePolicySubFile(policy, PolicyDbDao.CONFIG); } else if (policy.getActionBodyEntity() != null) { writePolicySubFile(policy, action); } } } catch (IOException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, "Error occurred while performing [" + action + "] of Policy File: " + policyName); } finally { session.close(); @@ -518,8 +547,8 @@ public class HandleIncomingNotifications { String type = null; String subTypeName = null; String subTypeBody = null; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policyType)) { - type = PolicyDBDao.CONFIG; + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policyType)) { + type = PolicyDbDao.CONFIG; subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName()); subTypeBody = policy.getConfigurationData().getConfigBody(); @@ -539,12 +568,12 @@ public class HandleIncomingNotifications { subTypeName = subTypeName + ".txt"; } } - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policyType)) { - type = PolicyDBDao.ACTION; + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policyType)) { + type = PolicyDbDao.ACTION; subTypeName = policy.getActionBodyEntity().getActionBodyName(); subTypeBody = policy.getActionBodyEntity().getActionBody(); } - Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), type); + Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type); if (subTypeBody == null) { subTypeBody = ""; @@ -558,11 +587,10 @@ public class HandleIncomingNotifications { try (FileWriter fileWriter = new FileWriter(file, false)) { // false to overwrite fileWriter.write(subTypeBody); - fileWriter.close(); success = true; } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Exception occured while creating Configuration File for Policy : " + policy.getPolicyName()); } return success; @@ -571,7 +599,7 @@ public class HandleIncomingNotifications { Path getPolicySubFile(String inputFileName, String subFileType) { String filename = inputFileName; logger.info("getPolicySubFile(" + filename + ", " + subFileType + ")"); - Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), subFileType); + Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), subFileType); File file = null; filename = FilenameUtils.removeExtension(filename); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java index 26c7ed834..5a7a2088f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * 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. @@ -20,6 +20,11 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -32,23 +37,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.MicroServiceModels; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -61,7 +49,16 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.MicroServiceModels; public class MicroServiceConfigPolicy extends Policy { @@ -70,7 +67,7 @@ public class MicroServiceConfigPolicy extends Policy { private static Map<String, String> mapAttribute = new HashMap<>(); private static Map<String, String> mapMatch = new HashMap<>(); - private static synchronized Map<String, String> getMatchMap () { + private static synchronized Map<String, String> getMatchMap() { return mapMatch; } @@ -82,34 +79,33 @@ public class MicroServiceConfigPolicy extends Policy { super(); } - public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){ + public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { - if(policyName.endsWith(".xml")){ - policyName = policyName.replace(".xml", ""); - } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json")){ + if (policyName.endsWith(".xml")) { + policyName = policyName.replace(".xml", ""); + } + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) { out.println(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured While writing Configuration data"+e); + LOGGER.error("Exception Occured While writing Configuration data" + e); } } - @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -117,18 +113,18 @@ public class MicroServiceConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //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 + // 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 @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -156,7 +152,6 @@ public class MicroServiceConfigPolicy extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -170,32 +165,33 @@ public class MicroServiceConfigPolicy extends Policy { name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); } - //setup values for pulling out matching attributes + // setup values for pulling out matching attributes ObjectMapper mapper = new ObjectMapper(); String matching = null; Map<String, String> matchMap = null; try { JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); - if (policyAdapter.getTtlDate()==null){ + if (policyAdapter.getTtlDate() == null) { policyAdapter.setTtlDate("NA"); } - if (policyAdapter.getServiceType().contains("-v")){ + if (policyAdapter.getServiceType().contains("-v")) { matching = getValueFromDictionary(policyAdapter.getServiceType()); } else { - String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), + new String[] {"\""}, new String[] {""}); matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); } - if (matching != null && !matching.isEmpty()){ + if (matching != null && !matching.isEmpty()) { matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); - setMatchMap(matchMap); - if(policyAdapter.getJsonBody() != null){ - pullMatchValue(rootNode); + setMatchMap(matchMap); + if (policyAdapter.getJsonBody() != null) { + pullMatchValue(rootNode); } } } catch (IOException e1) { throw new PAPException(e1); } - + // Match for policyName allOfOne.getMatch().add(createMatch("PolicyName", name)); @@ -203,7 +199,7 @@ public class MicroServiceConfigPolicy extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); - if (matchMap==null || matchMap.isEmpty()){ + if (matchMap == null || matchMap.isEmpty()) { // Match for ConfigName allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); // Match for Service @@ -212,29 +208,25 @@ public class MicroServiceConfigPolicy extends Policy { allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid())); // Match for location allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation())); - }else { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + } else { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ + if (value.contains("matching-true")) { + if (mapAttribute.containsKey(key)) { allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); } } } } // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -265,7 +257,8 @@ public class MicroServiceConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -284,7 +277,8 @@ public class MicroServiceConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -317,36 +311,38 @@ public class MicroServiceConfigPolicy extends Policy { private void pullMatchValue(JsonNode rootNode) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); String newValue = null; - while (fieldsIterator.hasNext()) { - Map.Entry<String, JsonNode> field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullMatchValue(value); // RECURSIVE CALL - } else { - newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - } - } - - } - - private String getValueFromDictionary(String service){ - String ruleTemplate=null; - String modelName = service.split("-v")[0]; - String modelVersion = service.split("-v")[1]; - - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion); - if(result != null && !result.isEmpty()){ - MicroServiceModels model = (MicroServiceModels) result.get(0); - ruleTemplate = model.getAnnotation(); - } - return ruleTemplate; - } - + while (fieldsIterator.hasNext()) { + Map.Entry<String, JsonNode> field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = + StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, new String[] {"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service) { + String ruleTemplate = null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = + dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName + ":" + modelVersion); + if (result != null && !result.isEmpty()) { + MicroServiceModels model = (MicroServiceModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) { AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("MSID"); @@ -372,12 +368,12 @@ public class MicroServiceConfigPolicy extends Policy { AttributeValueType AttributeValue = new AttributeValueType(); AttributeValue.setDataType(URI_DATATYPE); String configName; - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { configName = policyName.replace(".xml", ""); - }else{ + } else { configName = policyName; } - String content = CONFIG_URL +"/Config/" + configName + ".json"; + String content = CONFIG_URL + "/Config/" + configName + ".json"; AttributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); @@ -427,16 +423,16 @@ public class MicroServiceConfigPolicy extends Policy { assignment7.setAttributeId("matching:service"); assignment7.setCategory(CATEGORY_RESOURCE); assignment7.setIssuer(""); - + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); configNameAttributeValue7.setDataType(STRING_DATATYPE); configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - + advice.getAttributeAssignmentExpression().add(assignment7); Map<String, String> matchMap = getMatchMap(); - if (matchMap==null || matchMap.isEmpty()){ + if (matchMap == null || matchMap.isEmpty()) { AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -449,7 +445,6 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment6); - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("matching:uuid"); assignment8.setCategory(CATEGORY_RESOURCE); @@ -474,28 +469,28 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment9); } else { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ + if (value.contains("matching-true")) { + if (mapAttribute.containsKey(key)) { AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); assignment9.setAttributeId("matching:" + key); assignment9.setCategory(CATEGORY_RESOURCE); assignment9.setIssuer(""); - + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); configNameAttributeValue9.setDataType(STRING_DATATYPE); configNameAttributeValue9.getContent().add(mapAttribute.get(key)); assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - + advice.getAttributeAssignmentExpression().add(assignment9); - + } } } } - + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); assignment10.setAttributeId("Priority"); assignment10.setCategory(CATEGORY_RESOURCE); @@ -508,7 +503,7 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment10); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); assignment11.setAttributeId("RiskType"); assignment11.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java index 2e2a74015..e9db043bf 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,14 +34,14 @@ import java.util.List; import java.util.UUID; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.XacmlRestProperties; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; import org.onap.policy.utils.PeCryptoUtils; public class NotifyOtherPaps { private static final Logger LOGGER = FlexLogger.getLogger(NotifyOtherPaps.class); - private List<PolicyDBDaoEntity> failedPaps = null; + private List<PolicyDbDaoEntity> failedPaps = null; public void notifyOthers(long entityId, String entityType) { notifyOthers(entityId, entityType, null); @@ -55,10 +56,10 @@ public class NotifyOtherPaps { */ public void notifyOthers(long entityId, String entityType, String newGroupId) { LOGGER.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers(" + entityId + "," - + entityType + "," + newGroupId + ") called"); + + entityType + "," + newGroupId + ") called"); failedPaps = new ArrayList<>(); - List<?> otherServers = PolicyDBDao.getPolicyDBDaoInstance().getOtherServers(); + List<?> otherServers = PolicyDbDao.getPolicyDbDaoInstance().getOtherServers(); // Notify other paps startNotifyThreads(otherServers, entityId, entityType, newGroupId); // Retry for failed paps @@ -67,7 +68,7 @@ public class NotifyOtherPaps { } } - private void startNotifyThreads(List<?> otherServers, long entityId, String entityType, String newGroupId) { + protected void startNotifyThreads(List<?> otherServers, long entityId, String entityType, String newGroupId) { LinkedList<Thread> notifyThreads = new LinkedList<>(); // we're going to run notifications in parallel threads to speed things // up @@ -102,10 +103,9 @@ public class NotifyOtherPaps { @Override public void run() { - PolicyDBDao dao = new PolicyDBDao(); - PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity) obj; - String otherPap = dbdEntity.getPolicyDBDaoUrl(); - String username = dbdEntity.getUsername(); + PolicyDbDao dao = new PolicyDbDao(); + PolicyDbDaoEntity dbdEntity = (PolicyDbDaoEntity) obj; + String otherPap = dbdEntity.getPolicyDbDaoUrl(); String txt; try { txt = PeCryptoUtils.decrypt(dbdEntity.getPassword()); @@ -116,7 +116,6 @@ public class NotifyOtherPaps { } HttpURLConnection connection = null; - UUID requestId = UUID.randomUUID(); URL url; String papUrl; try { @@ -143,11 +142,11 @@ public class NotifyOtherPaps { return; } if (newGroupId == null) { - url = new URL(otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" - + entityType); + url = new URL( + otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" + entityType); } else { url = new URL(otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" - + entityType + "&extradata=" + newGroupId); + + entityType + "&extradata=" + newGroupId); } } catch (MalformedURLException e) { LOGGER.warn("Caught MalformedURLException on: new URL()", e); @@ -174,6 +173,10 @@ public class NotifyOtherPaps { LOGGER.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");", e); return; } + + String username = dbdEntity.getUsername(); + UUID requestId = UUID.randomUUID(); + Base64.Encoder encoder = Base64.getEncoder(); String encoding = encoder.encodeToString((username + ":" + txt).getBytes(StandardCharsets.UTF_8)); connection.setRequestProperty("Authorization", "Basic " + encoding); @@ -183,7 +186,7 @@ public class NotifyOtherPaps { int readTimeout; try { readTimeout = - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_NOTIFY_TIMEOUT)); + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_NOTIFY_TIMEOUT)); } catch (Exception e) { LOGGER.error("xacml.rest.pap.notify.timeoutms property not set, using a default.", e); readTimeout = 10000; @@ -212,7 +215,7 @@ public class NotifyOtherPaps { LOGGER.info("PolicyDBDao: NotifyOtherThread received response 200 from pap server on notify"); } else { LOGGER.warn("PolicyDBDao: NotifyOtherThread connection response code not 200, received: " - + connection.getResponseCode()); + + connection.getResponseCode()); failedPaps.add(dbdEntity); } } catch (Exception e) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java index 2719a155b..097a33f8e 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * 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. @@ -20,6 +20,11 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -32,23 +37,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.OptimizationModels; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -61,7 +49,16 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.OptimizationModels; public class OptimizationConfigPolicy extends Policy { @@ -70,7 +67,7 @@ public class OptimizationConfigPolicy extends Policy { private static Map<String, String> mapAttribute = new HashMap<>(); private static Map<String, String> mapMatch = new HashMap<>(); - private static synchronized Map<String, String> getMatchMap () { + private static synchronized Map<String, String> getMatchMap() { return mapMatch; } @@ -82,36 +79,35 @@ public class OptimizationConfigPolicy extends Policy { super(); } - public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter){ + public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { policyName = policyName.replace(".xml", ""); } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){ + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json");) { out.println(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured While writing Configuration data"+e); + LOGGER.error("Exception Occured While writing Configuration data" + e); } } - @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -119,18 +115,18 @@ public class OptimizationConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //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 + // 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 @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -158,7 +154,6 @@ public class OptimizationConfigPolicy extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -172,32 +167,33 @@ public class OptimizationConfigPolicy extends Policy { name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); } - //setup values for pulling out matching attributes + // setup values for pulling out matching attributes ObjectMapper mapper = new ObjectMapper(); String matching = null; Map<String, String> matchMap = null; try { JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); - if (policyAdapter.getTtlDate()==null){ + if (policyAdapter.getTtlDate() == null) { policyAdapter.setTtlDate("NA"); } - if (policyAdapter.getServiceType().contains("-v")){ + if (policyAdapter.getServiceType().contains("-v")) { matching = getValueFromDictionary(policyAdapter.getServiceType()); } else { - String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), + new String[] {"\""}, new String[] {""}); matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); } - if (matching != null && !matching.isEmpty()){ + if (matching != null && !matching.isEmpty()) { matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); setMatchMap(matchMap); - if(policyAdapter.getJsonBody() != null){ - pullMatchValue(rootNode); + if (policyAdapter.getJsonBody() != null) { + pullMatchValue(rootNode); } } } catch (IOException e1) { throw new PAPException(e1); } - + // Match for policyName allOfOne.getMatch().add(createMatch("PolicyName", name)); @@ -205,28 +201,24 @@ public class OptimizationConfigPolicy extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); - if (matchMap!=null && !matchMap.isEmpty()) { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + if (matchMap != null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + if (value.contains("matching-true") && mapAttribute.containsKey(key)) { allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); } } } // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -257,7 +249,8 @@ public class OptimizationConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -276,7 +269,8 @@ public class OptimizationConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -309,36 +303,38 @@ public class OptimizationConfigPolicy extends Policy { private void pullMatchValue(JsonNode rootNode) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); String newValue = null; - while (fieldsIterator.hasNext()) { - Map.Entry<String, JsonNode> field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullMatchValue(value); // RECURSIVE CALL - } else { - newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - } - } - - } - - private String getValueFromDictionary(String service){ - String ruleTemplate=null; - String modelName = service.split("-v")[0]; - String modelVersion = service.split("-v")[1]; - - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion); - if(result != null && !result.isEmpty()){ - OptimizationModels model = (OptimizationModels) result.get(0); - ruleTemplate = model.getAnnotation(); - } - return ruleTemplate; - } - + while (fieldsIterator.hasNext()) { + Map.Entry<String, JsonNode> field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = + StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, new String[] {"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service) { + String ruleTemplate = null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = + dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + modelVersion); + if (result != null && !result.isEmpty()) { + OptimizationModels model = (OptimizationModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) { AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("OptimizationID"); @@ -366,18 +362,18 @@ public class OptimizationConfigPolicy extends Policy { AttributeValueType attributeValue = new AttributeValueType(); attributeValue.setDataType(URI_DATATYPE); String configName; - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { configName = policyName.replace(".xml", ""); - }else{ + } else { configName = policyName; } - String content = CONFIG_URL +"/Config/" + configName + ".json"; + String content = CONFIG_URL + "/Config/" + configName + ".json"; attributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); - //PolicyName Attribute Assignment + // PolicyName Attribute Assignment AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); assignment3.setAttributeId("PolicyName"); assignment3.setCategory(CATEGORY_RESOURCE); @@ -395,7 +391,7 @@ public class OptimizationConfigPolicy extends Policy { assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); - //VersionNumber Attribute Assignment + // VersionNumber Attribute Assignment AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); assignment4.setAttributeId("VersionNumber"); assignment4.setCategory(CATEGORY_RESOURCE); @@ -408,7 +404,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment4); - //OnapName Attribute Assignment + // OnapName Attribute Assignment AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); assignment5.setAttributeId("matching:" + ONAPID); assignment5.setCategory(CATEGORY_RESOURCE); @@ -421,41 +417,41 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment5); - //ServiceType Attribute Assignment + // ServiceType Attribute Assignment AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("matching:service"); assignment7.setCategory(CATEGORY_RESOURCE); assignment7.setIssuer(""); - + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); configNameAttributeValue7.setDataType(STRING_DATATYPE); configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - + advice.getAttributeAssignmentExpression().add(assignment7); // Add matching attribute assignments if exist Map<String, String> matchMap = getMatchMap(); - if (matchMap!=null && !matchMap.isEmpty()) { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + if (matchMap != null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + if (value.contains("matching-true") && mapAttribute.containsKey(key)) { AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); assignment9.setAttributeId("matching:" + key); assignment9.setCategory(CATEGORY_RESOURCE); assignment9.setIssuer(""); - + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); configNameAttributeValue9.setDataType(STRING_DATATYPE); configNameAttributeValue9.getContent().add(mapAttribute.get(key)); assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - + advice.getAttributeAssignmentExpression().add(assignment9); } } } - + // Priority Attribute Assignment AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); assignment10.setAttributeId("Priority"); @@ -469,7 +465,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment10); - //RiskType Attribute Assignment + // RiskType Attribute Assignment AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); assignment11.setAttributeId("RiskType"); assignment11.setCategory(CATEGORY_RESOURCE); @@ -482,7 +478,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment11); - //RiskLevel Attribute Assignment + // RiskLevel Attribute Assignment AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType(); assignment12.setAttributeId("RiskLevel"); assignment12.setCategory(CATEGORY_RESOURCE); @@ -495,7 +491,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment12); - //Guard Attribute Assignment + // Guard Attribute Assignment AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType(); assignment13.setAttributeId("guard"); assignment13.setCategory(CATEGORY_RESOURCE); @@ -508,7 +504,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment13); - //TTLDate Attribute Assignment + // TTLDate Attribute Assignment AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType(); assignment14.setAttributeId("TTLDate"); assignment14.setCategory(CATEGORY_RESOURCE); 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 549d26b28..4873fc5ce 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 @@ -2,15 +2,15 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -21,6 +21,12 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; + import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -30,24 +36,21 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.apache.commons.io.FilenameUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.xacml.util.XACMLPolicyWriter; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.util.XACMLProperties; -import com.att.research.xacmlatt.pdp.policy.PolicyDef; -import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; public abstract class Policy { @@ -141,7 +144,7 @@ public abstract class Policy { /** * 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(); @@ -324,12 +327,12 @@ public abstract class Policy { private static void loadWebapps() throws PAPException { if (actionHome == null || configHome == null) { - Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + 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); + PolicyLogger.error("Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS); throw new PAPException( - "Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + "Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS); } Path webappsPathConfig; Path webappsPathAction; 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 9a39b6ed1..9af380b05 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 @@ -24,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; @@ -36,7 +37,9 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; + import javax.persistence.PersistenceException; + import org.apache.commons.io.FilenameUtils; import org.hibernate.Criteria; import org.hibernate.LockMode; @@ -48,15 +51,15 @@ import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; import org.onap.policy.rest.jpa.DatabaseLockEntity; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -68,9 +71,12 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +/** + * The Class PolicyDbDao. + */ @Component -public class PolicyDBDao { - private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); +public class PolicyDbDao { + private static final Logger logger = FlexLogger.getLogger(PolicyDbDao.class); public static final String JSON_CONFIG = "JSON"; public static final String XML_CONFIG = "XML"; public static final String PROPERTIES_CONFIG = "PROPERTIES"; @@ -86,65 +92,82 @@ public class PolicyDBDao { public static final String PDPENTITY_SELECT = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; public static final String GROUP_NOT_FOUND = "The group could not be found with id "; - public static final String FOUND_IN_DB_NOT_DEL = - " were found in the database that are not deleted"; + public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted"; public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id "; - public static final String DELETED_STATUS_FOUND = - " and deleted status were found in the database"; + public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database"; public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id "; public static final String PDP_ID = "pdpId"; - public static final String QUERY_FAILED_FOR_GROUP = - "Query failed trying to check for existing group"; + public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group"; public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group "; public static final String SCOPE = "scope"; public static final String POLICYDBDAO_VAR = "PolicyDBDao"; public static final String DUP_POLICYID = "Somehow, more than one policy with the id "; public static final String FOUND_IN_DB = " were found in the database"; - private static PolicyDBDao currentInstance = null; + + private static final String AUDIT_STR = "Audit"; + + private static PolicyDbDao currentInstance = null; private static boolean isJunit = false; private static SessionFactory sessionfactory; private List<?> otherServers; private PAPPolicyEngine papEngine; - /** * Gets the current instance of PolicyDBDao. * * @return The instance of PolicyDBDao or throws exception if the given instance is null. - * @throws IllegalStateException if a PolicyDBDao instance is null. Call - * createPolicyDBDaoInstance (EntityManagerFactory emf) to get this. + * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance + * (EntityManagerFactory emf) to get this. */ - public static PolicyDBDao getPolicyDBDaoInstance() { + public static PolicyDbDao getPolicyDbDaoInstance() { logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); if (currentInstance != null) { return currentInstance; } else { - currentInstance = new PolicyDBDao("init"); + currentInstance = new PolicyDbDao("init"); } return currentInstance; } + /** + * Sets the pap engine. + * + * @param papEngine2 the new pap engine + */ public void setPapEngine(PAPPolicyEngine papEngine2) { this.papEngine = papEngine2; } + /** + * Instantiates a new policy db dao. + * + * @param sessionFactory the session factory + */ @Autowired - public PolicyDBDao(SessionFactory sessionFactory) { - PolicyDBDao.sessionfactory = sessionFactory; + public PolicyDbDao(SessionFactory sessionFactory) { + PolicyDbDao.sessionfactory = sessionFactory; } - public PolicyDBDao() { + /** + * Instantiates a new policy db dao. + */ + public PolicyDbDao() { // Default Constructor } - public PolicyDBDao(String init) { + /** + * Initialize the DAO. + * + * @param init initiation parameters + */ + public PolicyDbDao(String init) { // not needed in this release if (!register()) { - PolicyLogger.error( - "This server's PolicyDBDao instance could not be registered and may not reveive updates"); + PolicyLogger + .error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); } - otherServers = getRemotePolicyDBDaoList(); + otherServers = getRemotePolicyDbDaoList(); if (logger.isDebugEnabled()) { logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size()); } @@ -153,21 +176,26 @@ public class PolicyDBDao { } } - // not static because we are going to be using the instance's emf - // waitTime in ms to wait for lock, or -1 to wait forever (no) + /** + * Start a synchronized transaction. + * + * <p>Not static because we are going to be using the instance's emf waitTime in ms to wait for lock, or -1 to wait + * forever (no) + * + * @param session the session + * @param waitTime the wait time + */ @SuppressWarnings("deprecation") public void startTransactionSynced(Session session, int waitTime) { - logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " - + "\n startTransactionSynced(" + session + "," + waitTime + ") called\n\n"); + logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced(" + + session + "," + waitTime + ") called\n\n"); DatabaseLockEntity lock = null; session.beginTransaction(); try { if (logger.isDebugEnabled()) { - logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" - + "\n\n"); + logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n"); } - lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, - LockMode.PESSIMISTIC_WRITE); + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE); if (logger.isDebugEnabled()) { logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); } @@ -182,17 +210,17 @@ public class PolicyDBDao { } /** - * Gets the list of other registered PolicyDBDaos from the database + * Gets the list of other registered PolicyDBDaos from the database. * - * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos + * @return List (type PolicyDbDaoEntity) of other PolicyDBDaos */ - private List<?> getRemotePolicyDBDaoList() { + private List<?> getRemotePolicyDbDaoList() { logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called"); - List<?> policyDBDaoEntityList = new LinkedList<>(); + List<?> policyDbDaoEntityList = new LinkedList<>(); Session session = sessionfactory.openSession(); try { - Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); - policyDBDaoEntityList = cr.list(); + Criteria cr = session.createCriteria(PolicyDbDaoEntity.class); + policyDbDaoEntityList = cr.list(); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception querying for other registered PolicyDBDaos"); @@ -201,32 +229,37 @@ public class PolicyDBDao { try { session.close(); } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); } } - return policyDBDaoEntityList; + return policyDbDaoEntityList; } - public PolicyDBDaoTransaction getNewTransaction() { + /** + * Gets the new transaction. + * + * @return the new transaction + */ + public PolicyDbDaoTransaction getNewTransaction() { logger.debug("getNewTransaction() as getNewTransaction() called"); return new PolicyDbDaoTransactionInstance("init"); } - /* - * Because the normal transactions are not used in audits, we can use the same transaction - * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to provide - * different transaction timeout values in ms because the audit will run longer than normal - * transactions. + /** + * Get a new audit transaction. + * + * <p>Because the normal transactions are not used in audits, we can use the same transaction mechanism to get a + * transaction and obtain the emlock and the DB lock. We just need to provide different transaction timeout values + * in ms because the audit will run longer than normal transactions. + * + * @return the new audit transaction */ - public PolicyDBDaoTransaction getNewAuditTransaction() { + public PolicyDbDaoTransaction getNewAuditTransaction() { logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); // Use the standard transaction wait time in ms - int auditWaitMs = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT)); // Use the (extended) audit timeout time in ms - int auditTimeoutMs = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT)); return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs); } @@ -235,10 +268,10 @@ public class PolicyDBDao { * * @param one A String or null to compare * @param two A String or null to compare + * @return true, if successful */ public static boolean stringEquals(String one, String two) { - logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two - + ") called"); + logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called"); if (one == null && two == null) { return true; } @@ -249,20 +282,25 @@ public class PolicyDBDao { } /** - * Returns the url of this local pap server, removing the username and password, if they are - * present + * Returns the url of this local pap server, removing the username and password, if they are present. * * @return The url of this local pap server */ public String[] getPapUrlUserPass() { logger.debug("getPapUrl() as getPapUrl() called"); - String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL); if (url == null) { return null; } return splitPapUrlUserPass(url); } + /** + * Split the user and password of a PAP URL. + * + * @param url the URL + * @return the user and password + */ public String[] splitPapUrlUserPass(String url) { String[] urlUserPass = new String[3]; String[] commaSplit = url.split(","); @@ -272,15 +310,14 @@ public class PolicyDBDao { urlUserPass[2] = commaSplit[2]; } if (urlUserPass[1] == null || "".equals(urlUserPass[1])) { - String usernamePropertyValue = - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String usernamePropertyValue = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID); if (usernamePropertyValue != null) { urlUserPass[1] = usernamePropertyValue; } } if (urlUserPass[2] == null || "".equals(urlUserPass[2])) { String passwordPropertyValue = - PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)); if (passwordPropertyValue != null) { urlUserPass[2] = passwordPropertyValue; } @@ -291,7 +328,7 @@ public class PolicyDBDao { } /** - * Register the PolicyDBDao instance in the PolicyDBDaoEntity table + * Register the PolicyDBDao instance in the PolicyDbDaoEntity table. * * @return Boolean, were we able to register? */ @@ -332,26 +369,25 @@ public class PolicyDBDao { } } } - logger.debug( - "\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); - PolicyDBDaoEntity foundPolicyDBDaoEntity = null; - Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); - cr.add(Restrictions.eq("policyDBDaoUrl", url[0])); + logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); + PolicyDbDaoEntity foundPolicyDbDaoEntity = null; + Criteria cr = session.createCriteria(PolicyDbDaoEntity.class); + cr.add(Restrictions.eq("policyDbDaoUrl", url[0])); List<?> data = cr.list(); if (!data.isEmpty()) { - foundPolicyDBDaoEntity = (PolicyDBDaoEntity) data.get(0); + foundPolicyDbDaoEntity = (PolicyDbDaoEntity) data.get(0); } // encrypt the password String txt = PeCryptoUtils.encrypt(url[2]); - if (foundPolicyDBDaoEntity == null) { - PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity(); - newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]); - newPolicyDBDaoEntity.setDescription("PAP server at " + url[0]); - newPolicyDBDaoEntity.setUsername(url[1]); - newPolicyDBDaoEntity.setPassword(txt); + if (foundPolicyDbDaoEntity == null) { + PolicyDbDaoEntity newPolicyDbDaoEntity = new PolicyDbDaoEntity(); + newPolicyDbDaoEntity.setPolicyDbDaoUrl(url[0]); + newPolicyDbDaoEntity.setDescription("PAP server at " + url[0]); + newPolicyDbDaoEntity.setUsername(url[1]); + newPolicyDbDaoEntity.setPassword(txt); try { - session.persist(newPolicyDBDaoEntity); + session.persist(newPolicyDbDaoEntity); session.getTransaction().commit(); } catch (Exception e) { logger.debug(e); @@ -365,13 +401,13 @@ public class PolicyDBDao { } } else { // just want to update in order to change modified date - if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) { - foundPolicyDBDaoEntity.setUsername(url[1]); + if (url[1] != null && !stringEquals(url[1], foundPolicyDbDaoEntity.getUsername())) { + foundPolicyDbDaoEntity.setUsername(url[1]); } - if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) { - foundPolicyDBDaoEntity.setPassword(txt); + if (txt != null && !stringEquals(txt, foundPolicyDbDaoEntity.getPassword())) { + foundPolicyDbDaoEntity.setPassword(txt); } - foundPolicyDBDaoEntity.preUpdate(); + foundPolicyDbDaoEntity.preUpdate(); try { session.getTransaction().commit(); } catch (Exception e) { @@ -390,12 +426,20 @@ public class PolicyDBDao { return true; } - /* - * This method is called during all pushPolicy transactions and makes sure the file system group - * is in sync with the database groupentity + /** + * Synchronize group policies in the fuile system. + * + * <p>This method is called during all pushPolicy transactions and makes sure the file system group is in sync with + * the database group entity + * + * @param pdpGroup the pdp group + * @param groupentity the groupentity + * @return the std PDP group + * @throws PAPException the PAP exception + * @throws PolicyDbException the policy db exception */ - public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, - GroupEntity groupentity) throws PAPException, PolicyDBException { + public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) + throws PAPException, PolicyDbException { HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>(); HashSet<String> newPolicyIdSet = new HashSet<>(); @@ -415,23 +459,19 @@ public class PolicyDBDao { // convert PolicyEntity object to PDPPolicy String name = pdpPolicyId.replace(".xml", ""); name = name.substring(0, name.lastIndexOf('.')); - InputStream policyStream = - new ByteArrayInputStream(policy.getPolicyData().getBytes()); + InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream); - URI location = - Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId) - .toUri(); + URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); StdPDPPolicy newPolicy = null; try { newPolicy = new StdPDPPolicy(pdpPolicyId, true, removeExtensionAndVersionFromPolicyName(pdpPolicyId), location); newPolicySet.add(newPolicy); - logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() - + ", Location - " + location); + logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location); } catch (Exception e) { logger.debug(e); - PolicyLogger.error( - "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + PolicyLogger + .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + e.getMessage()); } } @@ -444,39 +484,44 @@ public class PolicyDBDao { } catch (Exception e) { logger.debug(e); PolicyLogger.error( - "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. " - + e.getMessage()); + "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy" + + " file from the group. " + e.getMessage()); } } } - logger.info( - "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); + logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); pdpGroup.setPolicies(newPolicySet); return pdpGroup; } - public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) - throws PolicyDBException { + /** + * Removes the extension and version from policy name. + * + * @param originalPolicyName the original policy name + * @return the string + * @throws PolicyDbException the policy db exception + */ + public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDbException { return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; } /** - * Splits apart the policy name and version from a policy file path + * Splits apart the policy name and version from a policy file path. * - * @param originalPolicyName: a policy file name ex: Config_policy.2.xml + * @param originalPolicyName the original policy name * @return An array [0]: The policy name, [1]: the policy version, as a string + * @throws PolicyDbException the policy db exception */ - public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) - throws PolicyDBException { + public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException { String policyName = originalPolicyName; String[] nameAndVersion = new String[2]; try { policyName = removeFileExtension(policyName); nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.')); if (isNullOrEmpty(nameAndVersion[0])) { - throw new PolicyDBException(); + throw new PolicyDbException(); } } catch (Exception e) { nameAndVersion[0] = originalPolicyName; @@ -485,7 +530,7 @@ public class PolicyDBDao { try { nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1); if (isNullOrEmpty(nameAndVersion[1])) { - throw new PolicyDBException(); + throw new PolicyDbException(); } } catch (Exception e) { nameAndVersion[1] = "1"; @@ -494,6 +539,13 @@ public class PolicyDBDao { return nameAndVersion; } + /** + * Get the PDP policy by name. + * + * @param name The name to get + * @param scope The scope to use + * @return the policy. + */ public String getPdpPolicyName(String name, String scope) { String finalName = ""; finalName += scope; @@ -507,18 +559,28 @@ public class PolicyDBDao { return fileName.substring(0, fileName.lastIndexOf('.')); } + /** + * Audit local database. + * + * @param papEngine2 the pap engine 2 + */ public void auditLocalDatabase(PAPPolicyEngine papEngine2) { logger.debug("PolicyDBDao.auditLocalDatabase() is called"); try { deleteAllGroupTables(); auditGroups(papEngine2); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "auditLocalDatabase() error"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error"); logger.error("Exception Occured" + e); } } + /** + * Audit local file system. + * + * @param group the group + * @return the std PDP group + */ public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) { logger.info("Starting Local File System group audit"); @@ -534,17 +596,15 @@ public class PolicyDBDao { if (groupQueryList != null && !groupQueryList.isEmpty()) { GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0); updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup); - logger.info( - "Group was updated during file system audit: " + updatedGroup.toString()); + logger.info("Group was updated during file system audit: " + updatedGroup.toString()); } - } catch (PAPException | PolicyDBException e) { + } catch (PAPException | PolicyDbException e) { logger.error(e); } catch (Exception e) { logger.error(e); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException( - "Query failed trying to check if group " + group.getId() + " exists"); + throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists"); } session.getTransaction().commit(); @@ -553,9 +613,8 @@ public class PolicyDBDao { return updatedGroup; } - /* - * This method is called at startup to recreate config data from DB to the file system. - * + /** + * Synchronize config data in file system. */ public void synchronizeConfigDataInFileSystem() { @@ -571,8 +630,7 @@ public class PolicyDBDao { final Criteria configDataQuery = session.createCriteria(cl.getName()); @SuppressWarnings("unchecked") final List<T> configDataResult = configDataQuery.list(); - Path webappsPath = Paths - .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type); + Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type); for (final T configData : configDataResult) { String configName = null; @@ -588,8 +646,7 @@ public class PolicyDBDao { } else { configName = ((ActionBodyEntity) configData).getActionBodyName(); configBody = (((ActionBodyEntity) configData).getActionBody() != null) - ? ((ActionBodyEntity) configData).getActionBody() - .getBytes(StandardCharsets.UTF_8) + ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8) : "".getBytes(); } Path filePath = Paths.get(webappsPath.toString(), configName); @@ -609,6 +666,9 @@ public class PolicyDBDao { session.close(); } + /** + * Delete all group tables. + */ public void deleteAllGroupTables() { logger.debug("PolicyDBDao.deleteAllGroupTables() called"); Session session = sessionfactory.openSession(); @@ -624,13 +684,17 @@ public class PolicyDBDao { session.close(); } + /** + * Audit groups. + * + * @param papEngine2 the pap engine 2 + */ @SuppressWarnings("unchecked") public void auditGroups(PAPPolicyEngine papEngine2) { logger.debug("PolicyDBDao.auditGroups() called"); Session session = sessionfactory.openSession(); session.getTransaction().begin(); - final String AUDIT_STR = "Audit"; try { Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups(); @@ -642,7 +706,7 @@ public class PolicyDBDao { groupEntity.setDescription(grp.getDescription()); groupEntity.setDefaultGroup(grp.isDefaultGroup()); groupEntity.setCreatedBy(AUDIT_STR); - groupEntity.setGroupId(createNewPDPGroupId(grp.getId())); + groupEntity.setGroupId(createNewPdpGroupId(grp.getId())); groupEntity.setModifiedBy(AUDIT_STR); session.persist(groupEntity); Set<OnapPDP> pdps = grp.getOnapPdps(); @@ -662,15 +726,13 @@ public class PolicyDBDao { for (PDPPolicy policy : policies) { try { - String[] stringArray = - getNameScopeAndVersionFromPdpPolicy(policy.getId()); + String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); if (stringArray == null) { throw new IllegalArgumentException( "Invalid input - policyID must contain name, scope and version"); } List<PolicyEntity> policyEntityList; - Query getPolicyEntitiesQuery = - session.getNamedQuery("PolicyEntity.findByNameAndScope"); + Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope"); getPolicyEntitiesQuery.setParameter("name", stringArray[0]); getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]); @@ -694,8 +756,7 @@ public class PolicyDBDao { } } catch (Exception e) { session.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "Exception auditGroups outer catch"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch"); session.close(); return; } @@ -705,6 +766,13 @@ public class PolicyDBDao { } + /** + * Gets the config file. + * + * @param filename the filename + * @param policy the policy + * @return the config file + */ public String getConfigFile(String filename, PolicyRestAdapter policy) { if (policy == null) { return getConfigFile(filename, (String) null); @@ -714,12 +782,18 @@ public class PolicyDBDao { // copied from ConfigPolicy.java and modified // Here we are adding the extension for the configurations file based on the + /** + * Gets the config file. + * + * @param inputFilename the input filename + * @param configType the config type + * @return the config file + */ // config type selection for saving. public String getConfigFile(String inputFilename, String configType) { String filename = inputFilename; - logger.debug( - "getConfigFile(String filename, String scope, String configType) as getConfigFile(" - + filename + ", " + configType + ") called"); + logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename + + ", " + configType + ") called"); filename = FilenameUtils.removeExtension(filename); String id = configType; @@ -740,6 +814,12 @@ public class PolicyDBDao { return filename; } + /** + * Gets the name scope and version from pdp policy. + * + * @param fileName the file name + * @return the name scope and version from pdp policy + */ public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { String[] splitByDots = fileName.split("\\."); if (splitByDots.length < 3) { @@ -763,7 +843,13 @@ public class PolicyDBDao { return returnArray; } - public static String createNewPDPGroupId(String name) { + /** + * Creates the new PDP group id. + * + * @param name the name + * @return the string + */ + public static String createNewPdpGroupId(String name) { String id = name; // replace "bad" characters with sequences that will be ok for file // names and properties keys. @@ -786,7 +872,7 @@ public class PolicyDBDao { } /** - * Checks if any of the given strings are empty or null + * Checks if any of the given strings are empty or null. * * @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 @@ -800,47 +886,107 @@ public class PolicyDBDao { return false; } + /** + * Gets the other servers. + * + * @return the other servers + */ public List<?> getOtherServers() { return otherServers; } + /** + * Sets the other servers. + * + * @param otherServers the new other servers + */ public void setOtherServers(List<?> otherServers) { this.otherServers = otherServers; } + /** + * Gets the pap engine. + * + * @return the pap engine + */ public PAPPolicyEngine getPapEngine() { return papEngine; } - + /** + * Checks if is junit. + * + * @return true, if is junit + */ public static boolean isJunit() { return isJunit; } + /** + * Sets the junit. + * + * @param isJunit the new junit + */ public static void setJunit(boolean isJunit) { - PolicyDBDao.isJunit = isJunit; + PolicyDbDao.isJunit = isJunit; } - public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() { - return new PolicyDBDao().new PolicyDBDaoTestClass(); + /** + * Gets the policy DB dao test class. + * + * @return the policy DB dao test class + */ + public static PolicyDbDaoTestClass getPolicyDbDaoTestClass() { + return new PolicyDbDao().new PolicyDbDaoTestClass(); } - final class PolicyDBDaoTestClass { + /** + * The Class PolicyDBDaoTestClass. + */ + final class PolicyDbDaoTestClass { + + /** + * Gets the config file. + * + * @param filename the filename + * @param scope the scope + * @param policy the policy + * @return the config file + */ String getConfigFile(String filename, String scope, PolicyRestAdapter policy) { - return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); - } - - String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) - throws PolicyDBException { - return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); - } - + return scope + "." + PolicyDbDao.this.getConfigFile(filename, policy); + } + + /** + * Gets the policy name and version from policy file name. + * + * @param originalPolicyName the original policy name + * @return the policy name and version from policy file name + * @throws PolicyDbException the policy db exception + */ + String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException { + return PolicyDbDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); + } + + /** + * Gets the name scope and version from pdp policy. + * + * @param fileName the file name + * @return the name scope and version from pdp policy + */ String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { - return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName); + return PolicyDbDao.this.getNameScopeAndVersionFromPdpPolicy(fileName); } + /** + * Gets the pdp policy name. + * + * @param name the name + * @param scope the scope + * @return the pdp policy name + */ String getPdpPolicyName(String name, String scope) { - return PolicyDBDao.this.getPdpPolicyName(name, scope); + return PolicyDbDao.this.getPdpPolicyName(name, scope); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java index dbb2fa830..70ca36ac7 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,16 +22,19 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; + import java.util.List; + import javax.persistence.PersistenceException; -import org.onap.policy.rest.dao.PolicyDBException; + +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroup; -public interface PolicyDBDaoTransaction { +public interface PolicyDbDaoTransaction { /** * Commits (makes permanent) the current transaction. Also, notifies other PolicyDBDao instances on other PAP @@ -42,7 +46,7 @@ public interface PolicyDBDaoTransaction { public void commitTransaction(); /** - * Create or update a policy + * Create or update a policy. * * @param policy A Policy object representing the policy to store or update * @param username A string of the username you want to be stored for doing this operation @@ -50,10 +54,10 @@ public interface PolicyDBDaoTransaction { * @throws PersistenceException If a database error occurs * @throws IllegalArgumentException If the Policy's PolicyRestAdapter contains incorrect data. */ - public void createPolicy(Policy policy, String username) throws PolicyDBException; + public void createPolicy(Policy policy, String username) throws PolicyDbException; /** - * Check if the PolicyDBDaoTransaction is currently open + * Check if the PolicyDBDaoTransaction is currently open. * * @return False if the PolicyDBDao transaction has not been used or has been committed already, true if it is open. */ @@ -70,9 +74,8 @@ public interface PolicyDBDaoTransaction { */ public void close(); - /** - * Create a new PDP group in the database + * Create a new PDP group in the database. * * @param groupID The ID to name the new group (use PolicyDBDao.createNewPDPGroupId) * @param groupName The name to use for the new group @@ -83,23 +86,22 @@ public interface PolicyDBDaoTransaction { * @throws PersistenceException If a database error occurs */ public void createGroup(String groupID, String groupName, String groupDescription, String username) - throws PolicyDBException; + throws PolicyDbException; /** - * Updates a group in the database with a new name of description + * Updates a group in the database with a new name of description. * * @param group The group with updated information. The id must match an existing group, but the name and * description can be changed. - * @param username Username of the user performing the operation * @param userId needed to store user information in policyAuditlog table during transaction. * @throws IllegalArgumentException If non-optional parameters are null or empty strings * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs or if the group can not be found */ - public void updateGroup(OnapPDPGroup group, String requestType, String userId) throws PolicyDBException; + public void updateGroup(OnapPDPGroup group, String requestType, String userId) throws PolicyDbException; /** - * Updates a PDP in the database with new information + * Updates a PDP in the database with new information. * * @param pdp The PDP to update * @param username Username of the user performing the operation @@ -107,7 +109,7 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs or if the pdp can not be found */ - public void updatePdp(OnapPDP pdp, String username) throws PolicyDBException; + public void updatePdp(OnapPDP pdp, String username) throws PolicyDbException; /** * Change the default group in the database to the group provided. @@ -118,7 +120,7 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ - public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDBException; + public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDbException; /** * Moves a PDP to a new group. @@ -130,41 +132,37 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ - public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws PolicyDBException; + public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws PolicyDbException; /** - * Add a new PDP to an existing group + * Add a new PDP to an existing group. * * @param pdpID The ID to name the new PDP * @param groupID The ID of the existing group to add the PDP to * @param pdpName The name to use for the new PDP * @param pdpDescription Description of the new PDP (optional) - * @param pdpJmxPort + * @param pdpJmxPort PDP JMX port * @param username Username of the user performing the operation * @throws IllegalArgumentException If non-optional parameters are null or empty strings * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, - String username) throws PolicyDBException; + String username) throws PolicyDbException; /** - * Add an existing policy to an existing group + * Add an existing policy to an existing group. * * @param group The ID of the existing group to add the policy to * @param policyID The ID of an existing policy - * @return - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - * @throws PolicyDBException + * @return the PDP groups + * @throws PolicyDbException on DB exceptions */ public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username) - throws PolicyDBException; - + throws PolicyDbException; /** - * Delete an existing PDP groupPolicyDBException + * Delete an existing PDP groupPolicyDBException. * * @param group A PDPGroup object representing the group to delete * @param moveToGroup A PDPGroup object representing another existing group which PDPs in the group being deleted @@ -174,7 +172,7 @@ public interface PolicyDBDaoTransaction { * @throws PersistenceException If a database error occurs * @throws PAPException If an error relating to how groups are handled occurs */ - public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException; + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException; /** * Removes an existing PDP from its group and deletes it. @@ -184,7 +182,7 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ - public void removePdpFromGroup(String pdpID, String username) throws PolicyDBException; + public void removePdpFromGroup(String pdpID, String username) throws PolicyDbException; public GroupEntity getGroup(long groupKey); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java index f63649ddc..e694f7e0b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -36,14 +38,17 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; + import javax.persistence.PersistenceException; import javax.persistence.RollbackException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.hibernate.Query; @@ -53,9 +58,9 @@ import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; import org.onap.policy.rest.jpa.GroupEntity; @@ -71,12 +76,16 @@ import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.xml.sax.InputSource; - @Component -public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { - +public class PolicyDbDaoTransactionInstance implements PolicyDbDaoTransaction { private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class); + // Recurring constants + private static final String BRACKET_CALLED = ") called"; + private static final String EXISTS = " exists"; + private static final String GROUP = "group"; + private static final String CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS = "Caught Exception on notifyOthers("; + private final Object emLock = new Object(); long policyId; long groupId; @@ -86,8 +95,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private Thread transactionTimer; private static final String POLICY_NOTIFICATION = "policy"; private static final String PDP_NOTIFICATION = "pdp"; - private static final String GROUP_NOTIFICATION = "group"; - + private static final String GROUP_NOTIFICATION = GROUP; private static final String DECISIONMS_MODEL = "MicroService_Model"; private static boolean isJunit = false; @@ -100,8 +108,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { */ public PolicyDbDaoTransactionInstance(String test) { // call the constructor with arguments - this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)), - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT))); + this(Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT)), + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT))); } public PolicyDbDaoTransactionInstance() { @@ -115,7 +123,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private static SessionFactory sessionfactory; - /** * Instantiates a new policy DB dao transaction instance. * @@ -134,7 +141,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { session = sessionfactory.openSession(); try { - PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session, transactionWaitTime); + PolicyDbDao.getPolicyDbDaoInstance().startTransactionSynced(session, transactionWaitTime); } catch (Exception e) { logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e); throw new PersistenceException( @@ -221,7 +228,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { session.getTransaction().commit(); } catch (RollbackException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught RollbackException on em.getTransaction().commit()"); throw new PersistenceException("The commit failed. Message:\n" + e.getMessage()); } @@ -232,16 +239,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + "," + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + "," + newGroupId + ")"); } } else { try { otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + ")"); } } } @@ -251,16 +258,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + "," + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + "," + newGroupId + ")"); } } else { try { otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + ")"); } } } @@ -269,8 +276,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + pdpId + "," + PDP_NOTIFICATION + ")"); } } } @@ -287,13 +294,13 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { session.getTransaction().rollback(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not rollback transaction"); } try { session.close(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not close Hibernate Session."); } @@ -317,7 +324,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", " + policyScope + ", " + policyName + ", " + policyDataString + ") called"); synchronized (emLock) { - PolicyDBDao policyDbDao = new PolicyDBDao(); + PolicyDbDao policyDbDao = new PolicyDbDao(); checkBeforeOperationRun(); String configName = policyName; if (policyName.contains("Config_")) { @@ -332,7 +339,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyName = policyName.split(":")[1]; Query createPolicyQuery = session .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); - createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope); + createPolicyQuery.setParameter(PolicyDbDao.SCOPE, policyScope); createPolicyQuery.setParameter("policyName", policyName); List<?> createPolicyQueryList = createPolicyQuery.list(); PolicyEntity newPolicyEntity; @@ -351,7 +358,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } ActionBodyEntity newActionBodyEntity = null; - if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) { + if (policy.getPolicyType().equals(PolicyDbDao.ACTION)) { boolean abupdate = false; if (newPolicyEntity.getActionBodyEntity() == null) { newActionBodyEntity = new ActionBodyEntity(); @@ -410,7 +417,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } ConfigurationDataEntity newConfigurationDataEntity; - if (PolicyDBDao.CONFIG.equals(policy.getPolicyType()) + if (PolicyDbDao.CONFIG.equals(policy.getPolicyType()) || DECISIONMS_MODEL.equals(policy.getRuleProvider())) { boolean configUpdate; if (newPolicyEntity.getConfigurationData() == null) { @@ -423,7 +430,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (newConfigurationDataEntity != null) { - if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(), + if (!PolicyDbDao.stringEquals(newConfigurationDataEntity.getConfigurationName(), policyDbDao.getConfigFile(configName, policy))) { newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy)); } @@ -478,22 +485,22 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } policyId = newPolicyEntity.getPolicyId(); - if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) { newPolicyEntity.setPolicyName(policyName); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) { newPolicyEntity.setCreatedBy(username); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) { newPolicyEntity.setDescription(policy.getPolicyDescription()); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) { newPolicyEntity.setModifiedBy(username); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) { newPolicyEntity.setPolicyData(policyDataString); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getScope(), policyScope)) { newPolicyEntity.setScope(policyScope); } if (newPolicyEntity.isDeleted()) { @@ -518,7 +525,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { InputStream policyXmlStream = null; try { logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + "," - + username + ") called"); + + username + BRACKET_CALLED); String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); // Does not need to be XACMLPolicyWriterWithPapNotify since it is // already in the PAP @@ -535,22 +542,26 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyDataString = IOUtils.toString(policyXmlStream); } catch (IOException e) { policyDataString = "could not read"; - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught IOException on IOUtils.toString(" + policyXmlStream + ")"); throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter."); } IOUtils.closeQuietly(policyXmlStream); - if (PolicyDBDao.isJunit()) { + if (PolicyDbDao.isJunit()) { + if (policyDataString != null) { + logger.warn("isJUnit will overwrite policyDataString"); + } // Using parentPath object to set policy data. policyDataString = policy.policyAdapter.getParentPath(); } String configPath = ""; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { configPath = evaluateXPath( - "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", + "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/" + + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { configPath = evaluateXPath( "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " + policy.policyAdapter.getActionAttribute() @@ -558,16 +569,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyDataString); } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) { configPath = evaluateXPath( - "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", + "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/" + + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); } String prefix = null; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType()) + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType()) || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) { prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(), configPath.lastIndexOf(policy.policyAdapter.getPolicyName())); - if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { + if (PolicyDbDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { String configData = ""; try { String newConfigPath = configPath; @@ -582,7 +594,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } policy.policyAdapter.setConfigBodyData(configData); } - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { prefix = "Action_"; } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { prefix = "Decision_"; @@ -599,20 +611,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // get the config file extension String ext = ""; if (configPath != null && !"".equalsIgnoreCase(configPath)) { - ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());; + ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length()); } if (ext.contains("txt")) { - policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.OTHER_CONFIG); } else if (ext.contains("json")) { - policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG); } else if (ext.contains("xml")) { - policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.XML_CONFIG); } else if (ext.contains("properties")) { - policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.PROPERTIES_CONFIG); } else { - if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) { - policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG); + if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDbDao.ACTION)) { + policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG); } } } @@ -629,7 +641,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } } - public PolicyEntity getPolicy(int policyId) { return getPolicy(policyId, null, null); } @@ -640,42 +651,42 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) { logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName - + ") called"); - if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) { + + BRACKET_CALLED); + if (policyIdVar < 0 && PolicyDbDao.isNullOrEmpty(policyName, scope)) { throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank"); } synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists - String policyId; + String locPolicyId; Query policyQuery; - if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) { - policyId = policyName; + if (!PolicyDbDao.isNullOrEmpty(policyName, scope)) { + locPolicyId = policyName; policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); - policyQuery.setParameter("name", policyId); + policyQuery.setParameter("name", locPolicyId); policyQuery.setParameter("scope", scope); } else { - policyId = String.valueOf(policyIdVar); + locPolicyId = String.valueOf(policyIdVar); policyQuery = session.getNamedQuery("PolicyEntity.FindById"); - policyQuery.setParameter("id", policyId); + policyQuery.setParameter("id", locPolicyId); } List<?> policyQueryList; try { policyQueryList = policyQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get policy with policyQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get policy " + policyId); + throw new PersistenceException("Query failed trying to get policy " + locPolicyId); } if (policyQueryList.isEmpty()) { - PolicyLogger.error("Policy does not exist with id " + policyId); - throw new PersistenceException("Group policy is being added to does not exist with id " + policyId); + PolicyLogger.error("Policy does not exist with id " + locPolicyId); + throw new PersistenceException("Group policy is being added to does not exist with id " + locPolicyId); } else if (policyQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB); - throw new PersistenceException(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB); + throw new PersistenceException(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB); } return (PolicyEntity) policyQueryList.get(0); } @@ -683,7 +694,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public GroupEntity getGroup(long groupKey) { - logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called"); + logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + BRACKET_CALLED); if (groupKey < 0) { throw new IllegalArgumentException("groupKey must be at least 0"); } @@ -696,18 +707,18 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupKey); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group does not exist with groupKey " + groupKey); throw new PersistenceException("Group does not exist with groupKey " + groupKey); } else if (groupQueryList.size() > 1) { PolicyLogger - .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB); + .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB); throw new PersistenceException( - "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB); + "Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB); } return (GroupEntity) groupQueryList.get(0); } @@ -715,29 +726,29 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public GroupEntity getGroup(String groupId) { - logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupId)) { + logger.debug("getGroup(String groupId) as getGroup(" + groupId + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupId)) { throw new IllegalArgumentException("groupId must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); - groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId); + groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId); List<?> groupQueryList; try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupId); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group does not exist with id " + groupId); throw new PersistenceException("Group does not exist with id " + groupId); } else if (groupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB); - throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB); + throw new PersistenceException(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB); } return (GroupEntity) groupQueryList.get(0); } @@ -745,21 +756,21 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public List<?> getPdpsInGroup(long groupKey) { - logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called"); + logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + BRACKET_CALLED); if (groupKey < 0) { throw new IllegalArgumentException("groupId must not be < 0"); } synchronized (emLock) { checkBeforeOperationRun(true); Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group"); - pdpsQuery.setParameter("group", getGroup(groupKey)); + pdpsQuery.setParameter(GROUP, getGroup(groupKey)); return pdpsQuery.list(); } } @Override public PdpEntity getPdp(long pdpKey) { - logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called"); + logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + BRACKET_CALLED); if (pdpKey < 0) { throw new IllegalArgumentException("pdpKey must be at least 0"); } @@ -772,7 +783,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { pdpQueryList = pdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp with pdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get pdp " + pdpKey); } @@ -780,9 +791,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey); throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey); } else if (pdpQueryList.size() > 1) { - PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB); throw new PersistenceException( - "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB); + "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB); } return (PdpEntity) pdpQueryList.get(0); } @@ -798,7 +809,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private String processConfigPath(String inputConfigPath) { String configPath = inputConfigPath; - String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS); + String webappsPath = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS); if (webappsPath == null) { logger.error("Webapps property does not exist"); throw new IllegalArgumentException("Webapps property does not exist"); @@ -835,7 +846,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { return configDataString; } - @Override public void close() { synchronized (emLock) { @@ -855,8 +865,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) { String groupDescription = inputGroupDescription; logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", " - + groupDescription + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) { + + groupDescription + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupId, groupName, username)) { throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty"); } if (groupDescription == null) { @@ -865,16 +875,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { checkBeforeOperationRun(); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The group being added already exists with id " + groupId); @@ -898,50 +908,50 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void updateGroup(OnapPDPGroup group, String requestType, String username) { logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + "," - + username + ") called"); + + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) { + if (PolicyDbDao.isNullOrEmpty(group.getId(), requestType)) { throw new IllegalArgumentException("group.getId() and username must not be null or empty"); } synchronized (emLock) { - PolicyDBDao policyDbDaoVar = new PolicyDBDao(); + PolicyDbDao policyDbDaoVar = new PolicyDbDao(); checkBeforeOperationRun(); - Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - getGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + getGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getGroupQueryList; try { getGroupQueryList = getGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing"); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing"); } if (getGroupQueryList.isEmpty()) { PolicyLogger.error("The group cannot be found to update with id " + group.getId()); throw new PersistenceException("The group cannot be found to update with id " + group.getId()); } else if (getGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0); - if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) { + if (!PolicyDbDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) { groupToUpdateInDb.setModifiedBy(requestType); } if (group.getDescription() != null - && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) { + && !PolicyDbDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) { groupToUpdateInDb.setDescription(group.getDescription()); } // let's find out what policies have been deleted StdPDPGroup oldGroup = null; try { - oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getId()); + oldGroup = (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, "We cannot get the group from the papEngine to delete policies"); } if (oldGroup == null) { @@ -992,7 +1002,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not get policy to remove: " + pol.getId()); throw new PersistenceException("Could not get policy to remove: " + pol.getId()); } @@ -1001,19 +1011,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (group.getName() != null - && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) { + && !PolicyDbDao.stringEquals(group.getName(), groupToUpdateInDb.getGroupName())) { // we need to check if the new id exists in the database - String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName()); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + String newGrpId = PolicyDbDao.createNewPdpGroupId(group.getName()); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, newGrpId); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The new group name already exists, group id " + newGrpId); @@ -1034,35 +1044,35 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, " + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", " + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username - + ") called"); - if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) { + + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) { throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (checkGroupQueryList.size() != 1) { PolicyLogger.error("The group does not exist"); throw new PersistenceException("The group does not exist"); } - Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId); - checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkDuplicateQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + checkDuplicateQuery.setParameter(PolicyDbDao.PDP_ID, pdpId); + checkDuplicateQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkDuplicateList; try { checkDuplicateList = checkDuplicateQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check for duplicate PDP " + pdpId + " on checkDuplicateQuery.getResultList()"); throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId); @@ -1094,24 +1104,24 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void updatePdp(OnapPDP pdp, String username) { - logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + ") called"); + logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + BRACKET_CALLED); if (pdp == null) { throw new IllegalArgumentException("PDP pdp must not be null"); } - if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) { + if (PolicyDbDao.isNullOrEmpty(pdp.getId(), username)) { throw new IllegalArgumentException("pdp.getId() and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId()); - getPdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId()); + getPdpQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getPdpQueryList; try { getPdpQueryList = getPdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getPdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get PDP " + pdp.getId()); } @@ -1119,19 +1129,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId()); throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId()); } else if (getPdpQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0); - if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { pdpToUpdate.setModifiedBy(username); } if (pdp.getDescription() != null - && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) { + && !PolicyDbDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) { pdpToUpdate.setDescription(pdp.getDescription()); } - if (pdp.getName() != null && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) { + if (pdp.getName() != null && !PolicyDbDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) { pdpToUpdate.setPdpName(pdp.getName()); } if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) { @@ -1146,25 +1156,25 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) { logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + "," - + username + ") called"); + + username + BRACKET_CALLED); if (pdp == null || group == null) { throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) { + if (PolicyDbDao.isNullOrEmpty(username, pdp.getId(), group.getId())) { throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); // check if pdp exists - Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId()); - getPdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId()); + getPdpQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getPdpQueryList; try { getPdpQueryList = getPdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getPdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId()); } @@ -1172,20 +1182,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId()); throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId()); } else if (getPdpQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } // check if new group exists - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group on checkGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to get new group " + group.getId()); } @@ -1196,7 +1206,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0); PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0); pdpToUpdate.setGroup(groupToMoveInto); - if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { pdpToUpdate.setModifiedBy(username); } @@ -1208,38 +1218,38 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void changeDefaultGroup(OnapPDPGroup group, String username) { logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + "," - + username + ") called"); + + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) { + if (PolicyDbDao.isNullOrEmpty(group.getId(), username)) { throw new IllegalArgumentException("group.getId() and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - getGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + getGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getGroupQueryList; try { getGroupQueryList = getGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId()); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId()); } if (getGroupQueryList.isEmpty()) { PolicyLogger.error("The group cannot be found to set default with id " + group.getId()); throw new PersistenceException("The group cannot be found to set default with id " + group.getId()); } else if (getGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0); newDefaultGroup.setDefaultGroup(true); - if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) { newDefaultGroup.setModifiedBy(username); } @@ -1249,12 +1259,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey"); // not going to set modified by for all groups setAllGroupsNotDefault.setParameter("defaultGroup", false); - setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false); + setAllGroupsNotDefault.setParameter(PolicyDbDao.DELETED, false); setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey()); try { logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default"); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on setAllGroupsNotDefault.executeUpdate()"); throw new PersistenceException("Could not set all other groups default to false"); } @@ -1263,51 +1273,51 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } @Override - public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException { + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException { logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", " - + moveToGroup + "," + username + ") called"); + + moveToGroup + "," + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group cannot be null"); } - if (PolicyDBDao.isNullOrEmpty(username, group.getId())) { + if (PolicyDbDao.isNullOrEmpty(username, group.getId())) { throw new IllegalArgumentException("group.getId() and and username must not be null or empty"); } if (group.isDefaultGroup()) { PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be."); - throw new PolicyDBException("You cannot delete the default group."); + throw new PolicyDbException("You cannot delete the default group."); } synchronized (emLock) { checkBeforeOperationRun(); - Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query deleteGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + deleteGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + deleteGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> deleteGroupQueryList; try { deleteGroupQueryList = deleteGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to check if group exists"); } if (deleteGroupQueryList.isEmpty()) { - logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId()); + logger.warn(PolicyDbDao.GROUP_NOT_FOUND + group.getId()); return; } else if (deleteGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } Query pdpsInGroupQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted"); - pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0))); - pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false); + pdpsInGroupQuery.setParameter(GROUP, (deleteGroupQueryList.get(0))); + pdpsInGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> pdpsInGroupList; try { pdpsInGroupList = pdpsInGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to get PDPs in group"); } @@ -1315,37 +1325,37 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { if (moveToGroup != null) { Query checkMoveToGroupQuery = session .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted"); - checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId()); - checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false); + checkMoveToGroupQuery.setParameter(PolicyDbDao.GROUP_ID, moveToGroup.getId()); + checkMoveToGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkMoveToGroupList; try { checkMoveToGroupList = checkMoveToGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList"); throw new PersistenceException("Query failed trying to check if group exists"); } if (checkMoveToGroupList.isEmpty()) { - PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId()); - throw new PersistenceException(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId()); + PolicyLogger.error(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId()); + throw new PersistenceException(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId()); } else if (checkMoveToGroupList.size() > 1) { PolicyLogger.error( - PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } else { GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0); for (Object pdpObject : pdpsInGroupList) { PdpEntity pdp = (PdpEntity) pdpObject; pdp.setGroup(newGroup); - if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) { pdp.setModifiedBy(username); } try { session.flush(); this.newGroupId = newGroup.getGroupId(); } catch (PersistenceException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PersistenceException trying to set pdp group to null on em.flush()"); throw new PersistenceException("Query failed trying to set pdp group to "); } @@ -1354,14 +1364,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } else { PolicyLogger.error("Group " + group.getId() + " is trying to be delted with PDPs. No group was provided to move them to"); - throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to"); + throw new PolicyDbException("Group has PDPs. Must provide a group for them to move to"); } } // delete group here GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0); groupToDelete.setDeleted(true); - if (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(groupToDelete.getModifiedBy(), username)) { groupToDelete.setModifiedBy(username); } session.flush(); @@ -1371,40 +1381,40 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username) - throws PolicyDBException { + throws PolicyDbException { logger.info( "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup(" - + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) { + + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) { throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); // check if group exists - Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar); - groupQuery.setParameter(PolicyDBDao.DELETED, false); + Query groupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar); + groupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> groupQueryList; try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group " + groupIdVar + " exists"); + throw new PersistenceException("Query failed trying to check if group " + groupIdVar + EXISTS); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar); throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar); } else if (groupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } // we need to convert the form of the policy id that is used groups // into the form that is used // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml) - PolicyDBDao policyDbDao = new PolicyDBDao(); + PolicyDbDao policyDbDao = new PolicyDbDao(); String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar); if (policyNameScopeAndVersion == null) { throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version"); @@ -1412,17 +1422,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName " + "AND p.scope=:scope AND p.deleted=:deleted"); policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]); - policyQuery.setParameter(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]); - policyQuery.setParameter(PolicyDBDao.DELETED, false); + policyQuery.setParameter(PolicyDbDao.SCOPE, policyNameScopeAndVersion[1]); + policyQuery.setParameter(PolicyDbDao.DELETED, false); List<?> policyQueryList; try { policyQueryList = policyQuery.list(); } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if policy exists policyQuery.getResultList()"); throw new PersistenceException( - "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + " exists"); + "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + EXISTS); } if (policyQueryList.isEmpty()) { PolicyLogger.error("Policy being added to the group does not exist with policy id " @@ -1431,9 +1441,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + policyNameScopeAndVersion[0]); } else if (policyQueryList.size() > 1) { PolicyLogger.error( - PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } logger.info("PolicyDBDao: Getting group and policy from database"); GroupEntity group = (GroupEntity) groupQueryList.get(0); @@ -1464,7 +1474,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // filesytem group is in sync with the db group try { StdPDPGroup pdpGroup = - (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId()); + (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getGroupId()); return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group); } catch (PAPException e) { logger.debug(e); @@ -1479,27 +1489,27 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void removePdpFromGroup(String pdpId, String username) { logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username - + ") called"); - if (PolicyDBDao.isNullOrEmpty(pdpId, username)) { + + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(pdpId, username)) { throw new IllegalArgumentException("pdpID and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId); - pdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query pdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + pdpQuery.setParameter(PolicyDbDao.PDP_ID, pdpId); + pdpQuery.setParameter(PolicyDbDao.DELETED, false); List<?> pdpList; try { pdpList = pdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if pdp exists pdpQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if pdp " + pdpId + " exists"); + throw new PersistenceException("Query failed trying to check if pdp " + pdpId + EXISTS); } if (pdpList.size() > 1) { - PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - "Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + "Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } else if (pdpList.isEmpty()) { PolicyLogger.error("Pdp being removed does not exist with id " + pdpId); return; @@ -1509,7 +1519,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { pdp.setGroup(null); } - if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) { pdp.setModifiedBy(username); } pdp.setDeleted(true); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java index 7a0f708d8..6ef7a8f18 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import java.util.List; @@ -31,8 +32,8 @@ import org.yaml.snakeyaml.constructor.Constructor; public class SafePolicyBuilder { - private SafePolicyBuilder(){ - //Private Constructor. + private SafePolicyBuilder() { + // Private Constructor. } public static ControlLoopGuard loadYamlGuard(String specification) { @@ -45,40 +46,42 @@ public class SafePolicyBuilder { return (ControlLoopGuard) obj; } - public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap, List<String> blacklist, List<String> targets) { - //Setup default values and Targets. - StringBuilder targetRegex= new StringBuilder(".*|"); - if(targets!=null && !targets.isEmpty()){ + public static String generateXacmlGuard(String xacmlFileContent, Map<String, String> generateMap, + List<String> blacklist, List<String> targets) { + // Setup default values and Targets. + StringBuilder targetRegex = new StringBuilder(".*|"); + if (targets != null && !targets.isEmpty()) { targetRegex = new StringBuilder(); - for(String t : targets){ + for (String t : targets) { targetRegex.append(t + "|"); } } - if(generateMap.get("clname")==null|| generateMap.get("clname").isEmpty()){ - generateMap.put("clname",".*"); + if (generateMap.get("clname") == null || generateMap.get("clname").isEmpty()) { + generateMap.put("clname", ".*"); } - generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length()-1)); + generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length() - 1)); // Replace values. - for(Map.Entry<String,String> map: generateMap.entrySet()){ - Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}"); + for (Map.Entry<String, String> map : generateMap.entrySet()) { + Pattern p = Pattern.compile("\\$\\{" + map.getKey() + "\\}"); Matcher m = p.matcher(xacmlFileContent); String finalInput = map.getValue(); - if(finalInput.contains("$")){ + if (finalInput.contains("$")) { finalInput = finalInput.replace("$", "\\$"); } - xacmlFileContent=m.replaceAll(finalInput); + xacmlFileContent = m.replaceAll(finalInput); } - if(blacklist!=null && !blacklist.isEmpty()){ + if (blacklist != null && !blacklist.isEmpty()) { StringBuilder rule = new StringBuilder(); - for(String blackListName : blacklist){ - if(blackListName.contains("$")){ + for (String blackListName : blacklist) { + if (blackListName.contains("$")) { blackListName = blackListName.replace("$", "\\$"); } - rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">"+blackListName+"</AttributeValue>"); + rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + blackListName + + "</AttributeValue>"); } Pattern p = Pattern.compile("\\$\\{blackListElement\\}"); Matcher m = p.matcher(xacmlFileContent); - xacmlFileContent=m.replaceAll(rule.toString()); + xacmlFileContent = m.replaceAll(rule.toString()); } PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent); return xacmlFileContent; |