From: rb7147 Date: Tue, 4 Sep 2018 18:16:04 +0000 (-0400) Subject: XACML Platform Enhancements X-Git-Tag: 1.3.0~28^2 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=commitdiff_plain;h=7fd58e9a2427a215daa6b543e901534e83d3c246 XACML Platform Enhancements To Support Raw Policy Creation from GUI and API. GetDecision on combining algorithim with Policy Set. Issue-ID: POLICY-902 Change-Id: Ie3189f8ded2e03366bc7d65d15b95b88c89b0acd Signed-off-by: rb7147 --- 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 eece6c017..47ab45894 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 @@ -36,10 +36,9 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; - import javax.persistence.EntityManager; import javax.persistence.Query; - +import org.apache.commons.lang3.StringEscapeUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -61,11 +60,9 @@ import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine; import org.onap.policy.xacml.util.XACMLPolicyScanner; - import com.att.research.xacml.api.XACML3; 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; @@ -78,6 +75,7 @@ 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; @@ -86,7 +84,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; public class DecisionPolicy extends Policy { - private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class); + private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class); public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; private static final String AAFPROVIDER = "AAF"; @@ -113,7 +111,7 @@ public class DecisionPolicy extends Policy { super(); } - public DecisionPolicy(PolicyRestAdapter policyAdapter, CommonClassDao commonClassDao){ + public DecisionPolicy(PolicyRestAdapter policyAdapter, CommonClassDao commonClassDao) { this.policyAdapter = policyAdapter; this.commonClassDao = commonClassDao; } @@ -122,13 +120,13 @@ public class DecisionPolicy extends Policy { public Map savePolicies() throws PAPException { Map 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(); } @@ -136,17 +134,44 @@ public class DecisionPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } + + /** + * Scan the Raw Policy data and set to PolicyAdapter. + */ + private void readRawPolicyData() { + Object policy; + if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) { + 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@#"; + ((PolicySetType) policy).setDescription(policyRawDesc); + } else { + policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; + ((PolicyType) policy).setDescription(policyRawDesc); + } + policyAdapter.setPolicyData(policy); + policyAdapter.setData(policy); + setPreparedToSave(true); + + } - //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; } @@ -154,6 +179,10 @@ public class DecisionPolicy extends Policy { String policyID = policyAdapter.getPolicyID(); version = policyAdapter.getHighestVersion(); + if ("Raw".equals(policyAdapter.getRuleProvider())) { + readRawPolicyData(); + return true; + } // Create the Instance for pojo, PolicyType object is used in marshalling. if ("Decision".equals(policyAdapter.getPolicyType())) { PolicyType policyConfig = new PolicyType(); @@ -165,10 +194,13 @@ public class DecisionPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){ + if (policyAdapter.getRuleProvider().equals(GUARD_YAML) + || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)) { Map yamlParams = new HashMap<>(); - String blackListEntryType = policyAdapter.getBlackListEntryType() !=null ? policyAdapter.getBlackListEntryType(): "Use Manual Entry"; - String description = policyAdapter.getPolicyDescription() != null? policyAdapter.getPolicyDescription(): "YAML Guard Policy"; + 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@"); String fileName = policyAdapter.getNewFileName(); String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); @@ -190,8 +222,8 @@ public class DecisionPolicy extends Policy { LOGGER.error(e); throw new PAPException(e); } - }else if (policyAdapter.getData() != null) { - PolicyType decisionPolicy = (PolicyType) policyAdapter.getData(); + } else if (policyAdapter.getData() != null) { + PolicyType decisionPolicy = (PolicyType) policyAdapter.getData(); decisionPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -210,7 +242,7 @@ public class DecisionPolicy extends Policy { allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName()))); Map dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes(); - if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ + if (policyAdapter.getRuleProvider() != null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)) { dynamicFieldComponentAttributes = new HashMap<>(); } @@ -231,8 +263,8 @@ public class DecisionPolicy extends Policy { decisionPolicy.setTarget(target); Map dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap(); - if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals(AAFPROVIDER)|| - policyAdapter.getRuleProvider().equals(RAINY_DAY))){ + if (policyAdapter.getRuleProvider() != null && (policyAdapter.getRuleProvider().equals(AAFPROVIDER) + || policyAdapter.getRuleProvider().equals(RAINY_DAY))) { dynamicFieldDecisionSettings = new HashMap<>(); } @@ -246,8 +278,8 @@ public class DecisionPolicy extends Policy { } Map dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap(); - if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){ - for(String keyField : dynamicFieldTreatmentAttributes.keySet()) { + if (policyAdapter.getRuleProvider().equals(RAINY_DAY)) { + for (String keyField : dynamicFieldTreatmentAttributes.keySet()) { String errorcode = keyField; String treatment = dynamicFieldTreatmentAttributes.get(errorcode); createRainydayRule(decisionPolicy, errorcode, treatment, true); @@ -262,47 +294,47 @@ public class DecisionPolicy extends Policy { return true; } - public PolicyType getGuardPolicy(Map yamlParams, String ruleProvider) throws BuilderException{ + public PolicyType getGuardPolicy(Map yamlParams, String ruleProvider) throws BuilderException { try { ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe")); matchParameters.setControlLoopName(yamlParams.get("clname")); - if(yamlParams.containsKey("targets")){ + if (yamlParams.containsKey("targets")) { String targetString = yamlParams.get("targets"); List targets = null; - if(targetString!=null && !targetString.isEmpty()){ - if (targetString.contains(",")){ + if (targetString != null && !targetString.isEmpty()) { + if (targetString.contains(",")) { targets = Arrays.asList(targetString.split(",")); - } - else{ + } else { targets = new ArrayList<>(); targets.add(targetString); } } matchParameters.setTargets(targets); } - GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters); + GuardPolicy policy1 = new GuardPolicy( + (policyAdapter.getUuid() != null ? policyAdapter.getUuid() : UUID.randomUUID().toString()), + yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters); builder = builder.addGuardPolicy(policy1); Map activeTimeRange = new HashMap<>(); activeTimeRange.put("start", yamlParams.get("guardActiveStart")); activeTimeRange.put("end", yamlParams.get("guardActiveEnd")); String blackListString = yamlParams.get("blackList"); List blackList = null; - if(blackListString!=null && !blackListString.trim().isEmpty()){ - if (blackListString.contains(",")){ + if (blackListString != null && !blackListString.trim().isEmpty()) { + if (blackListString.contains(",")) { blackList = Arrays.asList(blackListString.split(",")); - } - else{ + } else { blackList = new ArrayList<>(); blackList.add(blackListString); } } - if(yamlParams.containsKey("appendBlackList")){ + if (yamlParams.containsKey("appendBlackList")) { String appendBlackListString = yamlParams.get("appendBlackList"); List appendBlackList = null; - if(appendBlackListString!=null && !appendBlackListString.trim().isEmpty()){ + if (appendBlackListString != null && !appendBlackListString.trim().isEmpty()) { appendBlackList = Arrays.asList(appendBlackListString.split(",")); - for(int i=0; i timeWindow = new HashMap<>(); - if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){ - throw new BuilderException("time window is not in Integer format."); - } - String timeUnits = yamlParams.get("timeUnits"); - if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day") - || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){ - throw new BuilderException("time Units is not in proper format."); - } - timeWindow.put("value", yamlParams.get("timeWindow")); - timeWindow.put("units", yamlParams.get("timeUnits")); - cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange); - break; + switch (ruleProvider) { + case GUARD_BL_YAML: + templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile()); + xacmlTemplatePath = templateFile.toPath(); + cons.setActive_time_range(activeTimeRange); + if (blackList == null || blackList.isEmpty()) { + throw new BuilderException("blackList is required"); + } + cons.setBlacklist(blackList); + break; + default: + templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile()); + xacmlTemplatePath = templateFile.toPath(); + Map timeWindow = new HashMap<>(); + if (!PolicyUtils.isInteger(yamlParams.get("timeWindow"))) { + throw new BuilderException("time window is not in Integer format."); + } + String timeUnits = yamlParams.get("timeUnits"); + if (timeUnits == null + || !("minute".equalsIgnoreCase(timeUnits) || "hour".equalsIgnoreCase(timeUnits) + || "day".equalsIgnoreCase(timeUnits) || "week".equalsIgnoreCase(timeUnits) + || "month".equalsIgnoreCase(timeUnits) || "year".equalsIgnoreCase(timeUnits))) { + throw new BuilderException("time Units is not in proper format."); + } + timeWindow.put("value", yamlParams.get("timeWindow")); + timeWindow.put("units", yamlParams.get("timeUnits")); + cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), timeWindow, activeTimeRange); + break; } builder = builder.addLimitConstraint(policy1.getId(), cons); // Build the specification @@ -352,25 +386,36 @@ public class DecisionPolicy extends Policy { yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME)); yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); - yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); - if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){ - yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString()); + yamlSpecs.put("clname", + yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); + if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() + .getFreq_limit_per_target() != null) { + yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() + .getFreq_limit_per_target().toString()); } - if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){ - yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value")); - yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units")); + if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window() != null) { + yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() + .getTime_window().get("value")); + yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() + .getTime_window().get("units")); } - yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start")); - yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end")); - String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets()); - // Convert the Policy into Stream input to Policy Adapter. - Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8))); + yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints() + .getFirst().getActive_time_range().get("start")); + yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() + .getActive_time_range().get("end")); + String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs, + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), + yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets()); + // Convert the Policy into Stream input to Policy Adapter. + Object policy = XACMLPolicyScanner + .readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8))); return (PolicyType) policy; } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(), + e); } } catch (BuilderException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(), e); throw e; } return null; @@ -431,7 +476,7 @@ public class DecisionPolicy extends Policy { dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1(); dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2(); - if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ + if (policyAdapter.getRuleProvider() != null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)) { // Values for AAF Provider are here for XML Creation. ConditionType condition = new ConditionType(); ApplyType decisionApply = new ApplyType(); @@ -470,7 +515,7 @@ public class DecisionPolicy extends Policy { targetInRule.getAnyOf().add(anyOfInRule); rule.setTarget(targetInRule); - if(!permitRule){ + if (!permitRule) { AdviceExpressionsType adviceExpressions = new AdviceExpressionsType(); AdviceExpressionType adviceExpression = new AdviceExpressionType(); adviceExpression.setAdviceId(AAFPROVIDER); @@ -491,7 +536,7 @@ public class DecisionPolicy extends Policy { decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(decisionPolicy); - }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) { + } else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) { boolean isCompound = false; ConditionType condition = new ConditionType(); int index = dynamicFieldOneRuleAlgorithms.size() - 1; @@ -513,7 +558,8 @@ public class DecisionPolicy extends Policy { // if rule algorithm not a compound if (!isCompound) { - condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index)))); + condition.setExpression(new ObjectFactory() + .createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index)))); } } if (!permitRule) { @@ -537,7 +583,8 @@ public class DecisionPolicy extends Policy { policyAdapter.setPolicyData(decisionPolicy); } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName()); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + + policyAdapter.getData().getClass().getCanonicalName()); } } @@ -647,17 +694,17 @@ public class DecisionPolicy extends Policy { // if two text field are rule attributes. if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) { ApplyType innerDecisionApply1 = new ApplyType(); - ApplyType innerDecisionApply2 = new ApplyType(); - AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType(); - AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType(); - //If selected function is Integer function set integer functionID - if(functionKey.toLowerCase().contains("integer")){ - innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY ); + ApplyType innerDecisionApply2 = new ApplyType(); + AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType(); + AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType(); + // If selected function is Integer function set integer functionID + if (functionKey.toLowerCase().contains("integer")) { + innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); attributeDesignator1.setDataType(INTEGER_DATATYPE); attributeDesignator2.setDataType(INTEGER_DATATYPE); - } else{ - //If selected function is not a Integer function set String functionID + } else { + // If selected function is not a Integer function set String functionID innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); attributeDesignator1.setDataType(STRING_DATATYPE); @@ -665,11 +712,15 @@ public class DecisionPolicy extends Policy { } attributeDesignator1.setCategory(CATEGORY_RESOURCE); attributeDesignator2.setCategory(CATEGORY_RESOURCE); - //Here set actual field values - attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8)); - attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8)); - innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1)); - innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2)); + // Here set actual field values + attributeDesignator1 + .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); + attributeDesignator2 + .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); + innerDecisionApply1.getExpression() + .add(new ObjectFactory().createAttributeDesignator(attributeDesignator1)); + innerDecisionApply2.getExpression() + .add(new ObjectFactory().createAttributeDesignator(attributeDesignator2)); decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1)); decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2)); } else { @@ -702,8 +753,10 @@ public class DecisionPolicy extends Policy { attributeDesignator.setAttributeId(attributeId); } decisionConditionAttributeValue.getContent().add(attributeValue); - innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); - decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); + innerDecisionApply.getExpression() + .add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); + decisionApply.getExpression() + .add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply)); } else { value1 = value1.substring(2, value1.length()); @@ -715,8 +768,10 @@ public class DecisionPolicy extends Policy { AttributeValueType decisionConditionAttributeValue = new AttributeValueType(); decisionConditionAttributeValue.setDataType(dataType); decisionConditionAttributeValue.getContent().add(value2); - decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType)); - decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); + decisionApply.getExpression() + .add(new ObjectFactory().createVariableReference(variableReferenceType)); + decisionApply.getExpression() + .add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); } } } @@ -753,12 +808,13 @@ public class DecisionPolicy extends Policy { private void populateDataTypeList(String value1) { String dataType = null; - if(value1.contains("S_")) { + if (value1.contains("S_")) { value1 = value1.substring(2, value1.length()); DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length())); if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) { dataType = STRING_DATATYPE; - } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { + } else if (decisionSettings != null + && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { dataType = BOOLEAN_DATATYPE; } else { dataType = INTEGER_DATATYPE; @@ -792,9 +848,10 @@ public class DecisionPolicy extends Policy { return policyAdapter.getData(); } - public String getFunctionDefinitionId(String key){ - FunctionDefinition object = (FunctionDefinition) commonClassDao.getDataById(FunctionDefinition.class, "shortname", key); - if(object != null){ + public String getFunctionDefinitionId(String key) { + FunctionDefinition object = + (FunctionDefinition) commonClassDao.getDataById(FunctionDefinition.class, "shortname", key); + if (object != null) { return object.getXacmlid(); } return null; 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 1be27ae71..549d26b28 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,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -30,7 +30,6 @@ import java.nio.file.Path; 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; @@ -39,22 +38,20 @@ import org.onap.policy.common.logging.flexlogger.Logger; 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 { - private static final Logger LOGGER = FlexLogger.getLogger(Policy.class); - + private static final Logger LOGGER = FlexLogger.getLogger(Policy.class); /** * Common Fields @@ -89,20 +86,26 @@ public abstract class Policy { } // Constants Used in XML Creation - public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; + public static final String CATEGORY_RECIPIENT_SUBJECT = + "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; - public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; - public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; - public static final String FUNCTION_BOOLEAN_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:boolean-one-and-only"; + public static final String FUNTION_INTEGER_ONE_AND_ONLY = + "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; + public static final String FUNCTION_STRING_ONE_AND_ONLY = + "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; + public static final String FUNCTION_BOOLEAN_ONE_AND_ONLY = + "urn:oasis:names:tc:xacml:1.0:function:boolean-one-and-only"; public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; public static final String FUNCTION_STRING_REGEX_MATCH = "org.onap.function.regex-match"; - public static final String FUNCTION_STRING_REGEXP_MATCH = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"; - public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; + public static final String FUNCTION_STRING_REGEXP_MATCH = + "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"; + public static final String FUNCTION_STRING_EQUAL_IGNORE = + "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; @@ -130,21 +133,26 @@ public abstract class Policy { performer.put("PEP", "PEPAction"); } - //Each policy type seems to either use policyData or data field policy adapter when - //getting the xml to save the policy. Instead of keep this hardcoded in the save method, - //this method makes it usable outside. + // Each policy type seems to either use policyData or data field policy + // adapter when + // getting the xml to save the policy. Instead of keep this hardcoded in the + // save method, + // this method makes it usable outside. /** - * Return the data field of the PolicyAdapter that will be used when saving this policy - * with the savePolicies method. + * Return the data field of the PolicyAdapter that will be used when saving this policy with the savePolicies + * method. + * * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData() */ public abstract Object getCorrectPolicyDataObject(); - public abstract Map savePolicies() throws PAPException; - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - public abstract boolean prepareToSave() throws PAPException; + public abstract Map savePolicies() throws PAPException; + // This is the method for preparing the policy for saving. We have broken it + // out + // separately because the fully configured policy is used for multiple + // things + public abstract boolean prepareToSave() throws PAPException; // create match for onap and config name protected MatchType createMatch(String key, String value) { @@ -157,9 +165,9 @@ public abstract class Policy { AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); URI uri = null; try { - uri = new URI(key); + uri = new URI(key.replaceAll("\\s+", "")); } catch (URISyntaxException e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } attributeDesignator.setCategory(CATEGORY_ACCESS_SUBJECT); attributeDesignator.setDataType(STRING_DATATYPE); @@ -183,9 +191,9 @@ public abstract class Policy { URI dynamicURI = null; try { - dynamicURI = new URI(key); + dynamicURI = new URI(key.replaceAll("\\s+", "")); } catch (URISyntaxException e) { - LOGGER.error("Exception Occured"+e);// log msg + LOGGER.error("Exception Occured" + e);// log msg } dynamicAttributeDesignator.setCategory(CATEGORY_RESOURCE); dynamicAttributeDesignator.setDataType(dataType); @@ -196,8 +204,7 @@ public abstract class Policy { return dynamicMatch; } - // the Policy Name as Unique One throws error - @SuppressWarnings("static-access") + // the Policy Name as Unique One throws error protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) { policyType = FilenameUtils.removeExtension(policyType); polcyFileName = FilenameUtils.removeExtension(polcyFileName); @@ -223,7 +230,8 @@ public abstract class Policy { return null; } - protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, String policyFileName, Integer version) { + protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, + String policyFileName, Integer version) { policyType = FilenameUtils.removeExtension(policyType); policyConfigType = FilenameUtils.removeExtension(policyConfigType); policyFileName = FilenameUtils.removeExtension(policyFileName); @@ -239,14 +247,18 @@ public abstract class Policy { String fileName = "default"; if (!policyDir.equals(EMPTY_STRING)) { - if("ClosedLoop_PM".equals(policyConfigType)){ - fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml"; - }else if("ClosedLoop_Fault".equals(policyConfigType)){ - fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; - }else if("Micro Service".equals(policyConfigType)){ - fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; - }else if("Optimization".equals(policyConfigType)) { - fileName = policyType + "_" + "OOF" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; + if ("ClosedLoop_PM".equals(policyConfigType)) { + fileName = policyType + "_" + "PM" + "_" + java.lang.String.format(policyFileName) + "." + version + + ".xml"; + } else if ("ClosedLoop_Fault".equals(policyConfigType)) { + fileName = policyType + "_" + "Fault" + "_" + java.lang.String.format(policyFileName) + "." + version + + ".xml"; + } else if ("Micro Service".equals(policyConfigType)) { + fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + + ".xml"; + } else if ("Optimization".equals(policyConfigType)) { + fileName = policyType + "_" + "OOF" + "_" + java.lang.String.format(policyFileName) + "." + version + + ".xml"; } } @@ -258,30 +270,29 @@ public abstract class Policy { return null; } - - //create policy once all the validations are completed + // create policy once all the validations are completed protected Map createPolicy(final Path policyPath, final Object policyData) { Map success = new HashMap<>(); // // Is the root a PolicySet or Policy? // - if (policyData instanceof PolicyType) { + if (policyData instanceof PolicyType || policyData instanceof PolicySetType) { // // Write it out // - //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP - //and this transaction is intercepted up stream. - - try(InputStream inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData)) { + // Does not need to be XACMLPolicyWriterWithPapNotify since it is + // already in the PAP + // and this transaction is intercepted up stream. + try (InputStream inputStream = XACMLPolicyWriter.getXmlAsInputStream(policyData)) { PolicyDef policyDef = DOMPolicyDef.load(inputStream); if (policyDef == null) { success.put("validation", "PolicyDef Validation Failed"); - }else{ + } else { success.put("success", "success"); } } catch (Exception e) { - LOGGER.error("PolicyDef Validation failed"+e); + LOGGER.error("PolicyDef Validation failed" + e); success.put("error", "Validation Failed"); } } else { @@ -291,7 +302,7 @@ public abstract class Policy { return success; } - public static String getConfigHome(){ + public static String getConfigHome() { try { loadWebapps(); } catch (Exception e) { @@ -301,7 +312,7 @@ public abstract class Policy { return configHome; } - public static String getActionHome(){ + public static String getActionHome() { try { loadWebapps(); } catch (Exception e) { @@ -311,35 +322,38 @@ public abstract class Policy { return actionHome; } - private static void loadWebapps() throws PAPException{ - if(actionHome == null || configHome == null){ + private static void loadWebapps() throws PAPException { + if (actionHome == null || configHome == null) { Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); - //Sanity Check + // Sanity Check if (webappsPath == null) { PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new PAPException( + "Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); } Path webappsPathConfig; Path webappsPathAction; - if(webappsPath.toString().contains("\\")){ - webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"\\Action"); - }else{ - webappsPathConfig = Paths.get(webappsPath.toString()+"/Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"/Action"); + if (webappsPath.toString().contains("\\")) { + webappsPathConfig = Paths.get(webappsPath.toString() + "\\Config"); + webappsPathAction = Paths.get(webappsPath.toString() + "\\Action"); + } else { + webappsPathConfig = Paths.get(webappsPath.toString() + "/Config"); + webappsPathAction = Paths.get(webappsPath.toString() + "/Action"); } - if(!webappsPathConfig.toFile().exists()){ + if (!webappsPathConfig.toFile().exists()) { try { Files.createDirectories(webappsPathConfig); } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", + "Failed to create config directory"); } } - if(!webappsPathAction.toFile().exists()){ + if (!webappsPathAction.toFile().exists()) { try { Files.createDirectories(webappsPathAction); } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", + "Failed to create config directory"); } } actionHome = webappsPathAction.toString(); @@ -373,5 +387,4 @@ public abstract class Policy { this.policyExists = policyExists; } - } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java index cedefb04e..ff4525ffb 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 @@ -49,7 +49,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; - import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.LockModeType; @@ -60,7 +59,6 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; - import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -87,8 +85,8 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.onap.policy.xacml.util.XACMLPolicyWriter; import org.w3c.dom.Document; import org.xml.sax.InputSource; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; - import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDP; import com.att.research.xacml.api.pap.PDPPolicy; @@ -106,7 +104,7 @@ public class PolicyDBDao { private static final String PROPERTIES_CONFIG = "PROPERTIES"; private static final String OTHER_CONFIG = "OTHER"; - //Declared to static variables which were repeating multiple times across the PolicyDBDao + // Declared to static variables which were repeating multiple times across the PolicyDBDao public static final String config = "Config"; public static final String action = "Action"; private static final String groupIdVar = "groupId"; @@ -135,13 +133,13 @@ public class PolicyDBDao { } /** - * Get an instance of a PolicyDBDao. It creates one if it does not exist. - * Only one instance is allowed to be created per server. + * Get an instance of a PolicyDBDao. It creates one if it does not exist. Only one instance is allowed to be created + * per server. * * @param emf The EntityFactoryManager to be used for database connections * @return The new instance of PolicyDBDao or throw exception if the given emf is null. - * @throws IllegalStateException if a PolicyDBDao has already been constructed. Call getPolicyDBDaoInstance() to - * get this. + * @throws IllegalStateException if a PolicyDBDao has already been constructed. Call getPolicyDBDaoInstance() to get + * this. */ public static PolicyDBDao getPolicyDBDaoInstance(EntityManagerFactory emf) { logger.debug("getPolicyDBDaoInstance(EntityManagerFactory emf) as getPolicyDBDaoInstance(" + emf + ") called"); @@ -160,7 +158,7 @@ public class 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. + * (EntityManagerFactory emf) to get this. */ public static PolicyDBDao getPolicyDBDaoInstance() { logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); @@ -179,7 +177,7 @@ public class PolicyDBDao { logger.debug("PolicyDBDao(EntityManagerFactory emf) as PolicyDBDao(" + emf + ") called"); this.emf = emf; - //not needed in this release + // not needed in this release if (!register()) { PolicyLogger .error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); @@ -194,8 +192,8 @@ 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) + // 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) private void startTransactionSynced(EntityManager entityMgr, int waitTime) { logger.debug("\n\nstartTransactionSynced(EntityManager entityMgr,int waitTime) as " + "\n startTransactionSynced(" + entityMgr + "," + waitTime + ") called\n\n"); @@ -206,21 +204,16 @@ public class PolicyDBDao { if (logger.isDebugEnabled()) { Map properties = entityMgr.getProperties(); - logger.debug("\n\nstartTransactionSynced():" - + "\n entityManager.getProperties() = " + properties - + "\n\n"); + logger.debug( + "\n\nstartTransactionSynced():" + "\n entityManager.getProperties() = " + properties + "\n\n"); } 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 = entityMgr.find(DatabaseLockEntity.class, 1, LockModeType.PESSIMISTIC_WRITE); if (logger.isDebugEnabled()) { - logger.debug("\n\nstartTransactionSynced():" - + "\n GOT the DB lock" - + "\n\n"); + logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); } } catch (Exception e) { System.out.println("Could not get lock entity"); @@ -272,16 +265,15 @@ public class PolicyDBDao { } /* - * 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. + * 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. */ public PolicyDBDaoTransaction getNewAuditTransaction() { logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); - //Use the standard transaction wait time in ms + // Use the standard transaction wait time in ms int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - //Use the (extended) audit timeout time in ms + // Use the (extended) audit timeout time in ms int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); return new PolicyDBDaoTransactionInstance(auditTimeoutMs, auditWaitMs); } @@ -338,7 +330,7 @@ public class PolicyDBDao { urlUserPass[2] = passwordPropertyValue; } } - //if there is no comma, for some reason there is no username and password, so don't try to cut them off + // if there is no comma, for some reason there is no username and password, so don't try to cut them off return urlUserPass; } @@ -350,7 +342,7 @@ public class PolicyDBDao { private boolean register() { logger.debug("register() as register() called"); String[] url = getPapUrlUserPass(); - //--- check URL length + // --- check URL length if (url == null || url.length < 3) { return false; } @@ -417,7 +409,7 @@ public class PolicyDBDao { } } } else { - //just want to update in order to change modified date + // just want to update in order to change modified date if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) { foundPolicyDBDaoEntity.setUsername(url[1]); } @@ -458,7 +450,7 @@ public class PolicyDBDao { @Override public void run() { - //naming of 'o' is for backwards compatibility with the rest of the function + // naming of 'o' is for backwards compatibility with the rest of the function PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity) obj; String o = dbdEntity.getPolicyDBDaoUrl(); String username = dbdEntity.getUsername(); @@ -467,7 +459,7 @@ public class PolicyDBDao { txt = new String(CryptoUtils.decryptTxt(dbdEntity.getPassword()), StandardCharsets.UTF_8); } catch (Exception e) { logger.debug(e); - //if we can't decrypt, might as well try it anyway + // if we can't decrypt, might as well try it anyway txt = dbdEntity.getPassword(); } Base64.Encoder encoder = Base64.getEncoder(); @@ -484,7 +476,7 @@ public class PolicyDBDao { papUrl = papUrlUserPass[0]; } logger.debug("We are going to try to notify " + o); - //is this our own url? + // is this our own url? String ourUrl = o; try { ourUrl = splitPapUrlUserPass((String) o)[0]; @@ -499,11 +491,11 @@ public class PolicyDBDao { return; } if (newGroupId == null) { - url = new URL(o + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" + - entityType); + url = new URL( + o + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" + entityType); } else { - url = new URL(o + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" + - entityType + "&extradata=" + newGroupId); + url = new URL(o + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" + + entityType + "&extradata=" + newGroupId); } } catch (MalformedURLException e) { logger.warn("Caught MalformedURLException on: new URL()", e); @@ -526,7 +518,7 @@ public class PolicyDBDao { try { connection.setRequestMethod("PUT"); } catch (ProtocolException e) { - //why would this error ever occur? + // why would this error ever occur? logger.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");", e); return; } @@ -565,8 +557,8 @@ public class PolicyDBDao { if (connection.getResponseCode() == 200) { 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()); + logger.warn("PolicyDBDao: NotifyOtherThread connection response code not 200, received: " + + connection.getResponseCode()); } } catch (Exception e) { logger.warn("Caught Exception on: connection.getResponseCode() ", e); @@ -600,19 +592,19 @@ public class PolicyDBDao { private static final String GROUP_NOTIFICATION = "group"; public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData, - XACMLPapServlet xacmlPapServlet) { + XACMLPapServlet xacmlPapServlet) { logger.info("DBDao url: " + url + " has reported an update on " + entityType + " entity " + entityId); PolicyDBDaoTransaction transaction = this.getNewTransaction(); - //although its named retries, this is the total number of tries + // although its named retries, this is the total number of tries int retries; try { - retries = Integer.parseInt( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES)); + retries = Integer + .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; } - //if someone sets it to some dumb value, we need to make sure it will try at least once + // if someone sets it to some dumb value, we need to make sure it will try at least once if (retries < 1) { retries = 1; } @@ -627,8 +619,8 @@ public class PolicyDBDao { } catch (Exception e) { logger.debug(e); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught exception on handleIncomingPolicyChange(" + url + ", " + entityId + ", " + - extraData + ")"); + "Caught exception on handleIncomingPolicyChange(" + url + ", " + entityId + ", " + + extraData + ")"); } try { Thread.sleep(pauseBetweenRetries); @@ -646,8 +638,8 @@ public class PolicyDBDao { } catch (Exception e) { logger.debug(e); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught exception on handleIncomingPdpChange(" + url + ", " + entityId + ", " + - transaction + ")"); + "Caught exception on handleIncomingPdpChange(" + url + ", " + entityId + ", " + + transaction + ")"); } try { Thread.sleep(pauseBetweenRetries); @@ -665,8 +657,8 @@ public class PolicyDBDao { } catch (Exception e) { logger.debug(e); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught exception on handleIncomingGroupChange(" + url + ", " + entityId + ", " + - extraData + ", " + transaction + ", " + xacmlPapServlet + ")"); + "Caught exception on handleIncomingGroupChange(" + url + ", " + entityId + ", " + + extraData + ", " + transaction + ", " + xacmlPapServlet + ")"); } try { Thread.sleep(pauseBetweenRetries); @@ -677,7 +669,7 @@ public class PolicyDBDao { } break; } - //no changes should be being made in this function, we still need to close + // no changes should be being made in this function, we still need to close transaction.rollbackTransaction(); } @@ -700,8 +692,8 @@ public class PolicyDBDao { if (groupRecord == null) { throw new PersistenceException("The group record returned is null"); } - //compare to local fs - //does group folder exist + // compare to local fs + // does group folder exist OnapPDPGroup localGroup = null; try { localGroup = papEngine.getGroup(groupRecord.getGroupId()); @@ -710,7 +702,7 @@ public class PolicyDBDao { e); } if (localGroup == null && extraData != null) { - //here we can try to load an old group id from the extraData + // here we can try to load an old group id from the extraData try { localGroup = papEngine.getGroup(extraData); } catch (Exception e) { @@ -726,37 +718,37 @@ public class PolicyDBDao { newLocalGroup = papEngine.getGroup(extraData); } catch (PAPException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to get new pdp group with papEngine.getGroup(" + extraData + - ");"); + "Caught PAPException trying to get new pdp group with papEngine.getGroup(" + extraData + + ");"); } } try { papEngine.removeGroup(localGroup, newLocalGroup); } catch (NullPointerException | PAPException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to get remove pdp group with papEngine.removeGroup(" + localGroup + - ", " + newLocalGroup + ");"); + "Caught PAPException trying to get remove pdp group with papEngine.removeGroup(" + localGroup + + ", " + newLocalGroup + ");"); throw new PAPException("Could not remove group " + groupId); } } else if (localGroup == null) { - //creating a new group + // creating a new group try { papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription()); } catch (NullPointerException | PAPException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord" + - ".getgroupName(), groupRecord.getDescription());"); + "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord" + + ".getgroupName(), groupRecord.getDescription());"); throw new PAPException("Could not create group " + groupRecord); } try { localGroup = papEngine.getGroup(groupRecord.getGroupId()); } catch (PAPException e1) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, policyDBDaoVar, - "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"); + "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 + // add possible pdps to group List pdpsInGroup = transaction.getPdpsInGroup(Long.parseLong(groupRecord.getGroupId())); for (Object pdpO : pdpsInGroup) { PdpEntity pdp = (PdpEntity) pdpO; @@ -765,34 +757,33 @@ public class PolicyDBDao { pdp.getJmxPort()); } catch (NullPointerException | PAPException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), " + - "localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); + "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); } } - //add possible policies to group (filesystem only, apparently) + // add possible policies to group (filesystem only, apparently) } else { if (!(localGroup instanceof StdPDPGroup)) { throw new PAPException("group is not a StdPDPGroup"); } - //clone the object - //because it will be comparing the new group to its own version - StdPDPGroup localGroupClone = - new StdPDPGroup(localGroup.getId(), localGroup.isDefaultGroup(), localGroup.getName(), - localGroup.getDescription(), ((StdPDPGroup) localGroup).getDirectory()); + // clone the object + // because it will be comparing the new group to its own version + StdPDPGroup localGroupClone = new StdPDPGroup(localGroup.getId(), localGroup.isDefaultGroup(), + localGroup.getName(), localGroup.getDescription(), ((StdPDPGroup) localGroup).getDirectory()); localGroupClone.setOnapPdps(localGroup.getOnapPdps()); localGroupClone.setPipConfigs(localGroup.getPipConfigs()); localGroupClone.setStatus(localGroup.getStatus()); - //we are updating a group or adding a policy or changing default - //set default if it should be + // we are updating a group or adding a policy or changing default + // set default if it should be if (!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()) { try { papEngine.setDefaultGroup(localGroup); return; } catch (PAPException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to set default group with papEngine.SetDefaultGroup(" + - localGroupClone + ");"); + "Caught PAPException trying to set default group with papEngine.SetDefaultGroup(" + + localGroupClone + ");"); throw new PAPException("Could not set default group to " + localGroupClone); } } @@ -800,10 +791,10 @@ public class PolicyDBDao { if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord, transaction)) { needToUpdate = true; } - if (!stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) || - !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 + if (!stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) + || !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()); needToUpdate = true; } @@ -816,24 +807,23 @@ public class PolicyDBDao { papEngine.updateGroup(localGroupClone); } catch (PAPException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to update group with papEngine.updateGroup(" + localGroupClone + - ");"); + "Caught PAPException trying to update group with papEngine.updateGroup(" + localGroupClone + + ");"); throw new PAPException("Could not update group " + localGroupClone); } } } } - //this will also handle removes, since incoming pdpGroup has no policies internally, we are just going to add + // 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, PolicyDBDaoTransaction transaction) throws PAPException, PolicyDBException { if (!(pdpGroup instanceof StdPDPGroup)) { throw new PAPException("group is not a StdPDPGroup"); } StdPDPGroup group = (StdPDPGroup) pdpGroup; - //this must always be true since we don't explicitly know when a delete is occuring + // this must always be true since we don't explicitly know when a delete is occuring boolean didUpdate = true; HashMap currentPolicySet = new HashMap<>(oldPdpGroup.getPolicies().size()); HashSet newPolicySet = new HashSet<>(); @@ -871,8 +861,8 @@ public class PolicyDBDao { } /* - * This method is called during all pushPolicy transactions and makes sure the file system - * group is in sync with the database groupentity + * This method is called during all pushPolicy transactions and makes sure the file system group is in sync with the + * database groupentity */ private StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) throws PAPException, PolicyDBException { @@ -892,7 +882,7 @@ public class PolicyDBDao { if (currentPolicyMap.containsKey(pdpPolicyId)) { newPolicySet.add(currentPolicyMap.get(pdpPolicyId)); } else { - //convert PolicyEntity object to PDPPolicy + // convert PolicyEntity object to PDPPolicy String name = pdpPolicyId.replace(".xml", ""); name = name.substring(0, name.lastIndexOf('.')); InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); @@ -900,15 +890,14 @@ public class PolicyDBDao { URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); StdPDPPolicy newPolicy = null; try { - newPolicy = - new StdPDPPolicy(pdpPolicyId, true, removeExtensionAndVersionFromPolicyName(pdpPolicyId), - location); + newPolicy = new StdPDPPolicy(pdpPolicyId, true, + removeExtensionAndVersionFromPolicyName(pdpPolicyId), location); newPolicySet.add(newPolicy); } catch (Exception e) { logger.debug(e); PolicyLogger - .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + - e.getMessage()); + .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + + e.getMessage()); } } } @@ -920,9 +909,8 @@ 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()); + .error("PolicyDBDao: Exception occurred while attempting to delete the old version of the" + + " policy file from the group. " + e.getMessage()); } } } @@ -969,7 +957,7 @@ public class PolicyDBDao { } private void handleIncomingPdpChange(String pdpId, PolicyDBDaoTransaction transaction) throws PAPException { - //get pdp + // get pdp long pdpIdLong = -1; try { pdpIdLong = Long.parseLong(pdpId); @@ -1002,15 +990,15 @@ public class PolicyDBDao { throw new PAPException("Could not remove pdp " + pdpId); } } else if (localPdp == null) { - //add new pdp - //get group + // add new pdp + // get group OnapPDPGroup localGroup = null; try { localGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e1) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, policyDBDaoVar, - "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup" + - "(pdpRecord.getGroup().getGroupId());"); + "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 { @@ -1018,16 +1006,16 @@ public class PolicyDBDao { pdpRecord.getJmxPort()); } catch (NullPointerException | PAPException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to create pdp with papEngine.newPDP(" + pdpRecord.getPdpId() + - ", " + localGroup + ", " + pdpRecord.getPdpName() + ", " + pdpRecord.getDescription() + - ", " + pdpRecord.getJmxPort() + ");"); + "Caught PAPException trying to create pdp with papEngine.newPDP(" + pdpRecord.getPdpId() + ", " + + localGroup + ", " + pdpRecord.getPdpName() + ", " + pdpRecord.getDescription() + ", " + + pdpRecord.getJmxPort() + ");"); throw new PAPException("Could not create pdp " + pdpRecord); } } else { boolean needToUpdate = false; - if (!stringEquals(localPdp.getId(), pdpRecord.getPdpId()) || - !stringEquals(localPdp.getName(), pdpRecord.getPdpName())) { - //again, we don't want to change the id, the papEngine will do this + if (!stringEquals(localPdp.getId(), pdpRecord.getPdpId()) + || !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; } @@ -1039,21 +1027,19 @@ public class PolicyDBDao { try { localPdpGroupId = papEngine.getPDPGroup((OnapPDP) 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); + // 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); } if (!stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) { OnapPDPGroup newPdpGroup = null; try { newPdpGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e) { - //ok, now we have an issue. Time to stop things + // ok, now we have an issue. Time to stop things PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PAPException trying to get id of local group to move pdp to with papEngine" + - ".getGroup(pdpRecord.getGroup().getGroupId());"); + "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 { @@ -1078,8 +1064,8 @@ public class PolicyDBDao { } } } - //compare to local situation - //call command to update + // compare to local situation + // call command to update } private void handleIncomingPolicyChange(String policyId) { @@ -1160,8 +1146,8 @@ public class PolicyDBDao { } private boolean writePolicySubFile(PolicyEntity policy, String policyType) { - logger.info("writePolicySubFile with policyName[" + policy.getPolicyName() + "] and policyType[" + policyType + - "]"); + logger.info("writePolicySubFile with policyName[" + policy.getPolicyName() + "] and policyType[" + policyType + + "]"); String type = null; String subTypeName = null; String subTypeBody = null; @@ -1361,14 +1347,13 @@ public class PolicyDBDao { return getConfigFile(filename, policy.getConfigType()); } - //copied from ConfigPolicy.java and modified + // copied from ConfigPolicy.java and modified // Here we are adding the extension for the configurations file based on the // config type selection for saving. private 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; @@ -1396,12 +1381,12 @@ public class PolicyDBDao { } String policyName = splitByDots[splitByDots.length - 3]; String version = splitByDots[splitByDots.length - 2]; - //policy names now include version + // policy names now include version String scope = ""; for (int i = 0; i < splitByDots.length - 3; i++) { scope += ".".concat(splitByDots[i]); } - //remove the first dot + // remove the first dot if (scope.length() > 0) { scope = scope.substring(1); } @@ -1460,18 +1445,18 @@ public class PolicyDBDao { private final Thread transactionTimer; private PolicyDBDaoTransactionInstance() { - //call the constructor with arguments + // call the constructor with arguments this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)), Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT))); } - //timeout is how long the transaction can sit before rolling back - //wait time is how long to wait for the transaction to start before throwing an exception + // timeout is how long the transaction can sit before rolling back + // wait time is how long to wait for the transaction to start before throwing an exception private PolicyDBDaoTransactionInstance(int transactionTimeout, int transactionWaitTime) { if (logger.isDebugEnabled()) { logger.debug("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:" - + "\n transactionTimeout = " + transactionTimeout - + "\n transactionWaitTime = " + transactionWaitTime + "\n\n"); + + "\n transactionTimeout = " + transactionTimeout + "\n transactionWaitTime = " + + transactionWaitTime + "\n\n"); } this.em = emf.createEntityManager(); policyId = -1; @@ -1499,29 +1484,25 @@ public class PolicyDBDao { public void run() { if (logger.isDebugEnabled()) { Date date = new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - SLEEPING: " - + "\n sleepTime (ms) = " + sleepTime - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + "\n sleepTime (ms) = " + sleepTime + + "\n TimeStamp = " + date.getTime() + "\n\n"); } try { Thread.sleep(sleepTime); } catch (InterruptedException e) { - //probably, the transaction was completed, the last thing we want to do is roll back + // probably, the transaction was completed, the last thing we want to do is roll back if (logger.isDebugEnabled()) { Date date = new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + "\n TimeStamp = " + + date.getTime() + "\n\n"); } Thread.currentThread().interrupt(); return; } if (logger.isDebugEnabled()) { Date date = new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n TimeStamp = " + + date.getTime() + "\n\n"); } rollbackTransaction(); } @@ -1544,9 +1525,8 @@ public class PolicyDBDao { throw new IllegalStateException("There is no transaction currently open"); } if (operationRun && !justCheckOpen) { - PolicyLogger - .error("An operation has already been performed and the current transaction should be " + - "committed"); + PolicyLogger.error( + "An operation has already been performed and the current transaction should be " + "committed"); throw new IllegalStateException( "An operation has already been performed and the current transaction should be committed"); } @@ -1581,8 +1561,8 @@ public class PolicyDBDao { notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + "," + - newGroupId + ")"); + "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + "," + + newGroupId + ")"); } } else { try { @@ -1594,14 +1574,14 @@ public class PolicyDBDao { } } if (groupId >= 0) { - //we don't want commit to fail just because this does + // we don't want commit to fail just because this does if (newGroupId != null) { try { notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + "," + - newGroupId + ")"); + "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + "," + + newGroupId + ")"); } } else { try { @@ -1613,7 +1593,7 @@ public class PolicyDBDao { } } if (pdpId >= 0) { - //we don't want commit to fail just because this does + // we don't want commit to fail just because this does try { notifyOthers(pdpId, PDP_NOTIFICATION); } catch (Exception e) { @@ -1661,13 +1641,12 @@ public class PolicyDBDao { } private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String inputPolicyName, - String policyDataString) { + String policyDataString) { String policyName = inputPolicyName; logger.debug( - "createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, " + - "String policyDataString) as createPolicy(" + - policy + ", " + username + ", " + policyScope + ", " + policyName + ", " + - policyDataString + ") called"); + "createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, " + + "String policyDataString) as createPolicy(" + policy + ", " + username + ", " + + policyScope + ", " + policyName + ", " + policyDataString + ") called"); synchronized (emLock) { checkBeforeOperationRun(); String configName = policyName; @@ -1679,8 +1658,8 @@ public class PolicyDBDao { policyName = policyName.replace(".Decision_", ":Decision_"); } policyName = policyName.split(":")[1]; - Query createPolicyQuery = em.createQuery( - "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); + Query createPolicyQuery = em + .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); createPolicyQuery.setParameter(scope, policyScope); createPolicyQuery.setParameter("policyName", policyName); List createPolicyQueryList = createPolicyQuery.getResultList(); @@ -1691,11 +1670,11 @@ public class PolicyDBDao { update = false; } else if (createPolicyQueryList.size() > 1) { PolicyLogger - .error("Somehow, more than one policy with the same scope, name, and deleted status were " + - "found in the database"); + .error("Somehow, more than one policy with the same scope, name, and deleted status were " + + "found in the database"); throw new PersistenceException( - "Somehow, more than one policy with the same scope, name, and deleted status were found " + - "in the database"); + "Somehow, more than one policy with the same scope, name, and deleted status were found " + + "in the database"); } else { newPolicyEntity = (PolicyEntity) createPolicyQueryList.get(0); update = true; @@ -1716,12 +1695,12 @@ public class PolicyDBDao { if (!abupdate) { em.persist(newActionBodyEntity); } - //build the file path - //trim the .xml off the end + // build the file path + // trim the .xml off the end String policyNameClean = FilenameUtils.removeExtension(configName); String actionBodyName = policyNameClean + ".json"; - //get the action body + // get the action body String actionBodyString = policy.getActionBody(); if (actionBodyString == null) { actionBodyString = "{}"; @@ -1734,30 +1713,26 @@ public class PolicyDBDao { newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()"); } if (logger.isDebugEnabled()) { - logger.debug("\nPolicyDBDao.createPolicy" - + "\n newActionBodyEntity.getActionBody() = " + - newActionBodyEntity.getActionBody() - + "\n newActionBodyEntity.getActionBodyName() = " + - newActionBodyEntity.getActionBodyName() - + "\n newActionBodyEntity.getModifiedBy() = " + - newActionBodyEntity.getModifiedBy() - + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy() - + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted() - + "\n FLUSHING to DB"); + logger.debug("\nPolicyDBDao.createPolicy" + "\n newActionBodyEntity.getActionBody() = " + + newActionBodyEntity.getActionBody() + + "\n newActionBodyEntity.getActionBodyName() = " + + newActionBodyEntity.getActionBodyName() + + "\n newActionBodyEntity.getModifiedBy() = " + + newActionBodyEntity.getModifiedBy() + "\n newActionBodyEntity.getCreatedBy() = " + + newActionBodyEntity.getCreatedBy() + "\n newActionBodyEntity.isDeleted() = " + + newActionBodyEntity.isDeleted() + "\n FLUSHING to DB"); } - //push the actionBodyEntity to the DB + // push the actionBodyEntity to the DB em.flush(); } else { - //newActionBodyEntity == null - //We have a actionBody in the policy but we found no actionBody in the DB + // newActionBodyEntity == null + // We have a actionBody in the policy but we found no actionBody in the DB String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an " - + "actionBody, but it could not be found in the DB for update." - + "\n policyScope = " + policyScope - + "\n policyName = " + policyName + "\n\n"; + + "actionBody, but it could not be found in the DB for update." + "\n policyScope = " + + policyScope + "\n policyName = " + policyName + "\n\n"; PolicyLogger - .error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, but it " + - "could not be found in the DB for update: policyName = " + - policyName); + .error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, but it " + + "could not be found in the DB for update: policyName = " + policyName); throw new IllegalArgumentException(msg); } } @@ -1782,25 +1757,25 @@ public class PolicyDBDao { getConfigFile(configName, policy))) { newConfigurationDataEntity.setConfigurationName(getConfigFile(configName, policy)); } - if (newConfigurationDataEntity.getConfigType() == null || - !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())) { + if (newConfigurationDataEntity.getConfigType() == null + || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())) { newConfigurationDataEntity.setConfigType(policy.getConfigType()); } if (!configUpdate) { newConfigurationDataEntity.setCreatedBy(username); } - if (newConfigurationDataEntity.getModifiedBy() == null || - !newConfigurationDataEntity.getModifiedBy().equals(username)) { + if (newConfigurationDataEntity.getModifiedBy() == null + || !newConfigurationDataEntity.getModifiedBy().equals(username)) { newConfigurationDataEntity.setModifiedBy(username); } - if (newConfigurationDataEntity.getDescription() == null || - !newConfigurationDataEntity.getDescription().equals("")) { + if (newConfigurationDataEntity.getDescription() == null + || !newConfigurationDataEntity.getDescription().equals("")) { newConfigurationDataEntity.setDescription(""); } - if (newConfigurationDataEntity.getConfigBody() == null || - newConfigurationDataEntity.getConfigBody().isEmpty() || - (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))) { - //hopefully one of these won't be null + if (newConfigurationDataEntity.getConfigBody() == null + || newConfigurationDataEntity.getConfigBody().isEmpty() + || (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))) { + // hopefully one of these won't be null if (policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()) { newConfigurationDataEntity.setConfigBody(policy.getJsonBody()); } else { @@ -1813,16 +1788,13 @@ public class PolicyDBDao { em.flush(); } else { - //We have a configurationData body in the policy but we found no configurationData body in + // We have a configurationData body in the policy but we found no configurationData body in // the DB String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a " + "configurationData body, but it could not be found in the DB for update." - + "\n policyScope = " + policyScope - + "\n policyName = " + policyName + "\n\n"; - PolicyLogger - .error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData " + - "body, but it could not be found in the DB for update: policyName = " + - policyName); + + "\n policyScope = " + policyScope + "\n policyName = " + policyName + "\n\n"; + PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData " + + "body, but it could not be found in the DB for update: policyName = " + policyName); throw new IllegalArgumentException(msg); } @@ -1874,8 +1846,8 @@ public class PolicyDBDao { } private PolicyEntity getPolicy(int policyID, String policyName, String scope) { - logger.debug("getPolicy(int policyId, String policyName) as getPolicy(" + policyID + "," + policyName + - ") called"); + logger.debug("getPolicy(int policyId, String policyName) as getPolicy(" + policyID + "," + policyName + + ") called"); if (policyID < 0 && isNullOrEmpty(policyName, scope)) { throw new IllegalArgumentException( "policyID must be at least 0 or policyName must be not null or blank"); @@ -1883,7 +1855,7 @@ public class PolicyDBDao { synchronized (emLock) { checkBeforeOperationRun(true); - //check if group exists + // check if group exists String policyId; Query policyQuery; if (!isNullOrEmpty(policyName, scope)) { @@ -1924,7 +1896,7 @@ public class PolicyDBDao { } synchronized (emLock) { checkBeforeOperationRun(true); - //check if group exists + // check if group exists Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey"); groupQuery.setParameter("groupKey", groupKey); List groupQueryList; @@ -1955,7 +1927,7 @@ public class PolicyDBDao { } synchronized (emLock) { checkBeforeOperationRun(true); - //check if group exists + // check if group exists Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); groupQuery.setParameter(groupIdVar, groupId); List groupQueryList; @@ -1999,7 +1971,7 @@ public class PolicyDBDao { } synchronized (emLock) { checkBeforeOperationRun(true); - //check if group exists + // check if group exists Query pdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey"); pdpQuery.setParameter("pdpKey", pdpKey); List pdpQueryList; @@ -2037,7 +2009,7 @@ public class PolicyDBDao { throw new IllegalArgumentException("Webapps property does not exist"); } configPath = configPath.replace("$URL", webappsPath); - //make sure the correct slashes are in + // make sure the correct slashes are in try { configPath = Paths.get(configPath).toString(); } catch (InvalidPathException e) { @@ -2068,37 +2040,37 @@ public class PolicyDBDao { public void createPolicy(Policy policy, String username) { try { - logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + "," + - username + ") called"); + logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + "," + + username + ") called"); String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); - //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP - //and this transaction is intercepted up stream. + // Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP + // and this transaction is intercepted up stream. - String policyDataString = getPolicyDataString((PolicyType) policy.getCorrectPolicyDataObject()); + String policyDataString = getPolicyDataString(policy); if (isJunit) { - //Using parentPath object to set policy data. + // Using parentPath object to set policy data. policyDataString = policy.policyAdapter.getParentPath(); } String configPath = ""; if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(config)) { 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 (policy.policyAdapter.getPolicyType().equalsIgnoreCase(action)) { configPath = evaluateXPath( - "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " + - policy.policyAdapter.getActionAttribute() + - ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()", + "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " + + policy.policyAdapter.getActionAttribute() + + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()", policyDataString); } String prefix = null; if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(config)) { - prefix = configPath - .substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(), - configPath.lastIndexOf(policy.policyAdapter.getPolicyName())); + prefix = configPath.substring( + configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(), + configPath.lastIndexOf(policy.policyAdapter.getPolicyName())); if (isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { policy.policyAdapter.setConfigBodyData(getConfigData(configPath)); } @@ -2108,18 +2080,19 @@ public class PolicyDBDao { prefix = "Decision_"; } - if (!(policy.policyAdapter.getData() instanceof PolicyType)) { - PolicyLogger.error("The data field is not an instance of PolicyType"); - throw new IllegalArgumentException("The data field is not an instance of PolicyType"); + if (!(policy.policyAdapter.getData() instanceof PolicyType) + && !(policy.policyAdapter.getData() instanceof PolicySetType)) { + PolicyLogger.error("The data field is not an instance of PolicyType or PolicySetType"); + throw new IllegalArgumentException( + "The data field is not an instance of PolicyType or PolicySetType"); } - String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "." + - ((PolicyType) policy.policyAdapter.getData()).getVersion() + ".xml"; + String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "." + + policy.policyAdapter.getHighestVersion() + ".xml"; if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) { - //get the config file extension + // 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")) { @@ -2163,13 +2136,19 @@ public class PolicyDBDao { return ""; } - private String getPolicyDataString(PolicyType policyType) { - try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyType)) { - return IOUtils.toString(policyXmlStream, StandardCharsets.UTF_8); + + /** + * @param policy input policy Object. + * @return read the stream and return policy xml data. + */ + private String getPolicyDataString(Policy policy) { + try (InputStream policyXmlStream = + XACMLPolicyWriter.getXmlAsInputStream(policy.getCorrectPolicyDataObject())) { + return IOUtils.toString(policyXmlStream); } catch (IOException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught IOException on IOUtils.toString(policyXmlStream)"); - throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.", e); + "Caught IOException on reading Policy Data."); + throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter."); } } @@ -2191,8 +2170,8 @@ public class PolicyDBDao { @Override 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"); + logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", " + + groupDescription + ") called"); if (isNullOrEmpty(groupId, groupName, username)) { throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty"); } @@ -2265,11 +2244,11 @@ public class PolicyDBDao { if (!stringEquals(groupToUpdateInDB.getModifiedBy(), username)) { groupToUpdateInDB.setModifiedBy(username); } - if (group.getDescription() != null && - !stringEquals(group.getDescription(), groupToUpdateInDB.getDescription())) { + if (group.getDescription() != null + && !stringEquals(group.getDescription(), groupToUpdateInDB.getDescription())) { groupToUpdateInDB.setDescription(group.getDescription()); } - //let's find out what policies have been deleted + // let's find out what policies have been deleted StdPDPGroup oldGroup = null; try { oldGroup = (StdPDPGroup) papEngine.getGroup(group.getId()); @@ -2281,12 +2260,12 @@ public class PolicyDBDao { PolicyLogger.error("We cannot get the group from the papEngine to delete policies"); } else { Set newPolicySet = new HashSet<>(group.getPolicies().size()); - //a multiple of n runtime is faster than n^2, so I am using a hashset to do the comparison + // a multiple of n runtime is faster than n^2, so I am using a hashset to do the comparison for (PDPPolicy pol : group.getPolicies()) { newPolicySet.add(pol.getId()); } for (PDPPolicy pol : oldGroup.getPolicies()) { - //should be fast since getPolicies uses a HashSet in StdPDPGroup + // should be fast since getPolicies uses a HashSet in StdPDPGroup if (!newPolicySet.contains(pol.getId())) { String[] scopeAndName = getNameScopeAndVersionFromPdpPolicy(pol.getId()); deletePolicyInScope(username, groupToUpdateInDB, pol, scopeAndName); @@ -2295,7 +2274,7 @@ public class PolicyDBDao { } if (group.getName() != null && !stringEquals(group.getName(), groupToUpdateInDB.getgroupName())) { - //we need to check if the new id exists in the database + // we need to check if the new id exists in the database String newGroupId = createNewPDPGroupId(group.getName()); Query checkGroupQuery = em.createQuery(groupEntitySelectQuery); checkGroupQuery.setParameter(groupIdVar, newGroupId); @@ -2322,7 +2301,7 @@ public class PolicyDBDao { } private void deletePolicyInScope(String username, GroupEntity groupToUpdateInDB, PDPPolicy pol, - String[] scopeAndName) { + String[] scopeAndName) { PolicyEntity policyToDelete; if (scopeAndName == null) { return; @@ -2344,35 +2323,33 @@ public class PolicyDBDao { } private void deletePolicyFromGroupEntity(GroupEntity groupToUpdateInDB, PolicyEntity policyToDelete, - Iterator dbPolicyIt, String policyName) { + Iterator dbPolicyIt, String policyName) { try { while (dbPolicyIt.hasNext()) { PolicyEntity dbpolicy = dbPolicyIt.next(); - if (policyToDelete.getScope().equals(dbpolicy.getScope()) && - getPolicyNameAndVersionFromPolicyFileName(dbpolicy.getPolicyName())[0].equals(policyName)) { + if (policyToDelete.getScope().equals(dbpolicy.getScope()) + && getPolicyNameAndVersionFromPolicyFileName(dbpolicy.getPolicyName())[0] + .equals(policyName)) { dbPolicyIt.remove(); - logger.info("PolicyDBDao: deleting policy from the existing group:\n " - + "policyName is " + policyToDelete.getScope() + "." + policyToDelete.getPolicyName() + - "\n" - + "group is " + groupToUpdateInDB.getGroupId()); + logger.info("PolicyDBDao: deleting policy from the existing group:\n " + "policyName is " + + policyToDelete.getScope() + "." + policyToDelete.getPolicyName() + "\n" + "group is " + + groupToUpdateInDB.getGroupId()); } } } catch (Exception e) { logger.debug(e); - PolicyLogger.error("Could not delete policy with name: " + policyToDelete.getScope() + "." + - policyToDelete.getPolicyName() + "\n ID: " + policyToDelete.getPolicyId()); + PolicyLogger.error("Could not delete policy with name: " + policyToDelete.getScope() + "." + + policyToDelete.getPolicyName() + "\n ID: " + policyToDelete.getPolicyId()); } } @Override public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, - String username) { - logger.debug( - "addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int " + - "pdpJmxPort, String username) as addPdpToGroup(" + - pdpID + ", " + groupID + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + - username + ") called"); + String username) { + logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int " + + "pdpJmxPort, String username) as addPdpToGroup(" + pdpID + ", " + groupID + ", " + pdpName + ", " + + pdpDescription + ", " + pdpJmxPort + ", " + username + ") called"); if (isNullOrEmpty(pdpID, groupID, pdpName, username)) { throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty"); } @@ -2401,8 +2378,8 @@ public class PolicyDBDao { checkDuplicateList = checkDuplicateQuery.getResultList(); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught Exception trying to check for duplicate PDP " + pdpID + - " on checkDuplicateQuery.getResultList()"); + "Caught Exception trying to check for duplicate PDP " + pdpID + + " on checkDuplicateQuery.getResultList()"); throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpID); } PdpEntity newPdp; @@ -2480,8 +2457,8 @@ public class PolicyDBDao { @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"); + logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + "," + + username + ") called"); if (pdp == null || group == null) { throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null"); } @@ -2492,7 +2469,7 @@ public class PolicyDBDao { synchronized (emLock) { checkBeforeOperationRun(); - //check if pdp exists + // check if pdp exists Query getPdpQuery = em.createQuery(pdpEntitySelectQuery); getPdpQuery.setParameter(pdpIdVariable, pdp.getId()); getPdpQuery.setParameter(deletedVar, false); @@ -2512,7 +2489,7 @@ public class PolicyDBDao { throw new PersistenceException(moreThanOnePDP + pdp.getId() + deletedStatusFound); } - //check if new group exists + // check if new group exists Query checkGroupQuery = em.createQuery(groupEntitySelectQuery); checkGroupQuery.setParameter(groupIdVar, group.getId()); checkGroupQuery.setParameter(deletedVar, false); @@ -2542,8 +2519,8 @@ public class PolicyDBDao { @Override public void changeDefaultGroup(OnapPDPGroup group, String username) { - logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + "," + - username + ") called"); + logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + "," + + username + ") called"); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } @@ -2580,9 +2557,9 @@ public class PolicyDBDao { em.flush(); this.groupId = newDefaultGroup.getGroupKey(); Query setAllGroupsNotDefault = em.createQuery( - "UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup WHERE g.deleted=:deleted AND g" + - ".groupKey<>:groupKey"); - //not going to set modified by for all groups + "UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup WHERE g.deleted=:deleted AND g" + + ".groupKey<>:groupKey"); + // not going to set modified by for all groups setAllGroupsNotDefault.setParameter("defaultGroup", false); setAllGroupsNotDefault.setParameter(deletedVar, false); setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey()); @@ -2601,8 +2578,8 @@ public class PolicyDBDao { @Override 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"); + logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + + ", " + moveToGroup + "," + username + ") called"); if (group == null) { throw new IllegalArgumentException("PDPGroup group cannot be null"); } @@ -2659,8 +2636,8 @@ public class PolicyDBDao { checkMoveToGroupList = checkMoveToGroupQuery.getResultList(); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught Exception trying to check if group exists checkMoveToGroupQuery" + - ".getResultList()"); + "Caught Exception trying to check if group exists checkMoveToGroupQuery" + + ".getResultList()"); throw new PersistenceException("Query failed trying to check if group exists"); } if (checkMoveToGroupList.isEmpty()) { @@ -2683,20 +2660,20 @@ public class PolicyDBDao { this.newGroupId = newGroup.getGroupId(); } catch (PersistenceException e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, - "Caught PersistenceException trying to set pdp group to null on em.flush" + - "()"); + "Caught PersistenceException trying to set pdp group to null on em.flush" + + "()"); throw new PersistenceException("Query failed trying to set pdp group to "); } } } } else { - PolicyLogger.error("Group " + group.getId() + - " is trying to be delted with PDPs. No group was provided to move them to"); + 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"); } } - //delete group here + // delete group here GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0); groupToDelete.setDeleted(true); if (!stringEquals(groupToDelete.getModifiedBy(), username)) { @@ -2709,16 +2686,14 @@ public class PolicyDBDao { @Override public StdPDPGroup addPolicyToGroup(String groupID, String policyID, String username) throws PolicyDBException { - logger.info( - "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as " + - "addPolicyToGroup(" + - groupID + ", " + policyID + "," + username + ") called"); + logger.info("PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as " + + "addPolicyToGroup(" + groupID + ", " + policyID + "," + username + ") called"); if (isNullOrEmpty(groupID, policyID, username)) { throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - //check if group exists + // check if group exists Query groupQuery = em.createQuery(groupEntitySelectQuery); groupQuery.setParameter(groupIdVar, groupID); groupQuery.setParameter(deletedVar, false); @@ -2738,15 +2713,15 @@ public class PolicyDBDao { throw new PersistenceException(duplicateGroupId + groupID + foundInDBNotDeleted); } - //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) + // 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) String[] policyNameScopeAndVersion = getNameScopeAndVersionFromPdpPolicy(policyID); if (policyNameScopeAndVersion == null) { throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version"); } Query policyQuery = em.createQuery( - "SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName AND p.scope=:scope AND p" + - ".deleted=:deleted"); + "SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName AND p.scope=:scope AND p" + + ".deleted=:deleted"); policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]); policyQuery.setParameter(scope, policyNameScopeAndVersion[1]); policyQuery.setParameter(deletedVar, false); @@ -2761,10 +2736,10 @@ public class PolicyDBDao { "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 " + - policyNameScopeAndVersion[0]); - throw new PersistenceException("Policy being added to the group does not exist with policy id " + - policyNameScopeAndVersion[0]); + PolicyLogger.error("Policy being added to the group does not exist with policy id " + + policyNameScopeAndVersion[0]); + throw new PersistenceException("Policy being added to the group does not exist with policy id " + + policyNameScopeAndVersion[0]); } else if (policyQueryList.size() > 1) { PolicyLogger.error(duplicatePolicyId + policyNameScopeAndVersion[0] + foundInDBNotDeleted); throw new PersistenceException( @@ -2780,38 +2755,40 @@ public class PolicyDBDao { try { while (policyIt.hasNext()) { PolicyEntity pol = policyIt.next(); - if (policy.getScope().equals(pol.getScope()) && - getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0].equals(policyName)) { + if (policy.getScope().equals(pol.getScope()) + && getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0] + .equals(policyName)) { policyIt.remove(); } } } catch (Exception e) { logger.debug(e); - PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: " + - policy.getPolicyId()); + PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: " + + policy.getPolicyId()); } group.addPolicyToGroup(policy); em.flush(); - // After adding policy to the db group we need to make sure the filesytem group is in sync with the db group + // After adding policy to the db group we need to make sure the filesytem group is in sync with the db + // group try { StdPDPGroup pdpGroup = (StdPDPGroup) papEngine.getGroup(group.getGroupId()); return synchronizeGroupPoliciesInFileSystem(pdpGroup, group); } catch (PAPException e) { logger.debug(e); PolicyLogger - .error("PolicyDBDao: Could not synchronize the filesystem group with the database group. " + - e.getMessage()); + .error("PolicyDBDao: Could not synchronize the filesystem group with the database group. " + + e.getMessage()); } return null; } } - //this means delete pdp not just remove from group + // this means delete pdp not just remove from group @Override public void removePdpFromGroup(String pdpID, String username) { - logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpID + "," + - username + ") called"); + logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpID + "," + + username + ") called"); if (isNullOrEmpty(pdpID, username)) { throw new IllegalArgumentException("pdpID and username must not be null or empty"); } @@ -2853,17 +2830,18 @@ public class PolicyDBDao { } private void notifyOthers(long entityId, String entityType, String newGroupId) { - logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers(" + entityId + - "," + entityType + "," + newGroupId + ") called"); + logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers(" + entityId + + "," + entityType + "," + newGroupId + ") called"); LinkedList notifyThreads = new LinkedList<>(); - //we're going to run notifications in parallel threads to speed things up + // we're going to run notifications in parallel threads to speed things up for (Object obj : otherServers) { Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId)); newNotifyThread.start(); notifyThreads.add(newNotifyThread); } - //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes + // we want to wait for all notifications to complete or timeout before we unlock the interface and allow + // more changes for (Thread t : notifyThreads) { try { t.join(); @@ -2875,7 +2853,7 @@ public class PolicyDBDao { } private PolicyDBDao() { - //empty constructor + // empty constructor } public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() { @@ -2892,4 +2870,4 @@ public class PolicyDBDao { } } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java index 335434fd4..2da84d754 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java @@ -138,7 +138,8 @@ public class SavePolicyHandler { policyAdapter.setRuleProvider(policy.getProviderComboBox()); policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); policyAdapter.setRainydayMap(policy.getTreatments()); - + policyAdapter.setRawXacmlPolicy(policy.getRawXacmlPolicy()); + return policyAdapter; } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java index bdfd8db33..89ddf84c5 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java @@ -156,6 +156,7 @@ public class PolicyDBDaoTest extends Mockito{ policyObject.policyAdapter.setPolicyType("Config"); policyObject.policyAdapter.setDomainDir("com"); policyObject.policyAdapter.setVersion("1"); + policyObject.policyAdapter.setHighestVersion(1); PolicyType policyTypeObject = new PolicyType(); policyObject.policyAdapter.setPolicyData(policyTypeObject); ClassLoader classLoader = getClass().getClassLoader(); diff --git a/ONAP-PDP-REST/pom.xml b/ONAP-PDP-REST/pom.xml index aa54f1b4b..97df34daa 100644 --- a/ONAP-PDP-REST/pom.xml +++ b/ONAP-PDP-REST/pom.xml @@ -169,6 +169,11 @@ springfox-swagger-ui 2.7.0 + + org.apache.commons + commons-text + 1.4 + org.onap.policy.engine PolicyEngineAPI diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java index 567ff2e78..87cafc4ef 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java @@ -34,7 +34,6 @@ import java.util.Properties; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; - import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; @@ -43,7 +42,6 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -65,7 +63,6 @@ import org.onap.policy.rest.XACMLRestProperties; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.pdp.std.functions.PolicyList; import org.onap.policy.xacml.std.pap.StdPDPStatus; - import com.att.research.xacml.api.Request; import com.att.research.xacml.api.Response; import com.att.research.xacml.api.pap.PDPStatus.Status; @@ -81,17 +78,17 @@ import com.fasterxml.jackson.databind.ObjectMapper; /** * Servlet implementation class XacmlPdpServlet * - * This is an implementation of the XACML 3.0 RESTful Interface with added features to support - * simple PAP RESTful API for policy publishing and PIP configuration changes. + * This is an implementation of the XACML 3.0 RESTful Interface with added features to support simple PAP RESTful API + * for policy publishing and PIP configuration changes. * - * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file. - * This properties file has all the default parameter settings. If you are running the servlet as is, - * then we recommend setting up you're container to run it on port 8080 with context "/pdp". Wherever - * the default working directory is set to, a "config" directory will be created that holds the policy - * and pip cache. This setting is located in the xacml.pdp.properties file. + * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file. This properties + * file has all the default parameter settings. If you are running the servlet as is, then we recommend setting up + * you're container to run it on port 8080 with context "/pdp". Wherever the default working directory is set to, a + * "config" directory will be created that holds the policy and pip cache. This setting is located in the + * xacml.pdp.properties file. * - * When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file - * system and setup the parameters as you wish. Just set the Java VM System variable to point to that file: + * When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file system and setup + * the parameters as you wish. Just set the Java VM System variable to point to that file: * * -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties * @@ -101,186 +98,189 @@ import com.fasterxml.jackson.databind.ObjectMapper; * * */ -@WebServlet( - description = "Implements the XACML PDP RESTful API and client PAP API.", - urlPatterns = { "/" }, - loadOnStartup=1, - initParams = { - @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pdp.properties", description = "The location of the PDP xacml.pdp.properties file holding configuration information.") - }) +@WebServlet(description = "Implements the XACML PDP RESTful API and client PAP API.", urlPatterns = {"/"}, + loadOnStartup = 1, initParams = {@WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pdp.properties", + description = "The location of the PDP xacml.pdp.properties file holding configuration information.")}) public class XACMLPdpServlet extends HttpServlet implements Runnable { - private static final long serialVersionUID = 1L; - private static final String DEFAULT_MAX_CONTENT_LENGTH = "999999999"; //32767 - private static final String CREATE_UPDATE_POLICY_SERVICE = "org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl"; - // - // Our application debug log - // - private static final Log logger = LogFactory.getLog(XACMLPdpServlet.class); - // - // This logger is specifically only for Xacml requests and their corresponding response. - // It's output ideally should be sent to a separate file from the application logger. - // - private static final Log requestLogger = LogFactory.getLog("xacml.request"); - // - // audit logger - private static final Log auditLogger = LogFactory.getLog("auditLogger"); - - private static final PdpRestMonitor monitor = PdpRestMonitor.getSingleton(); - - // - // This thread may getting invoked on startup, to let the PAP know - // that we are up and running. - // - private static transient Thread registerThread = null; - private static transient XACMLPdpRegisterThread registerRunnable = null; - // - // This is our PDP engine pointer. There is a synchronized lock used - // for access to the pointer. In case we are servicing PEP requests while - // an update is occurring from the PAP. - // - private static PDPEngine pdpEngine = null; - private static final Object pdpEngineLock = new Object(); - // - // This is our PDP's status. What policies are loaded (or not) and - // what PIP configurations are loaded (or not). - // There is a synchronized lock used for access to the object. - // - private static volatile StdPDPStatus status = new StdPDPStatus(); - private static final Object pdpStatusLock = new Object(); - private static Constructor createUpdatePolicyConstructor; - - private static final String ENVIORNMENT_HEADER = "Environment"; - private static String environment = null; - // - // Queue of PUT requests - // - public static class PutRequest { - private Properties policyProperties = null; - private Properties pipConfigProperties = null; - - PutRequest(Properties policies, Properties pips) { - this.policyProperties = policies; - this.pipConfigProperties = pips; - } - } - protected static volatile BlockingQueue queue = null; - // For notification Delay. - private static int notificationDelay = 0; - public static int getNotificationDelay(){ - return XACMLPdpServlet.notificationDelay; - } - - private static String pdpResourceName; - private static String[] dependencyNodes = null; - - // - // This is our configuration thread that attempts to load - // a new configuration request. - // - private static transient Thread configThread = null; - private static volatile boolean configThreadTerminate = false; - private transient ONAPLoggingContext baseLoggingContext = null; - private transient IntegrityMonitor im; - public IntegrityMonitor getIm() { - return im; - } - - public void setIm(IntegrityMonitor im) { - this.im = im; - } - - /** - * Default constructor. - */ - public XACMLPdpServlet() { - //Default constructor. - } - - /** - * @see Servlet#init(ServletConfig) - */ - @Override - public void init(ServletConfig config) throws ServletException { - String createUpdateResourceName = null; - String dependencyGroups = null; - // - // Initialize - // - XACMLRest.xacmlInit(config); - // Load the Notification Delay. - setNotificationDelay(); - // Load Queue size. Not sure if we really need to have the queue bounded, we should look further into this - int queueSize = 50; // Set default Queue Size here. - queueSize = Integer.parseInt(XACMLProperties.getProperty("REQUEST_BUFFER_SIZE",String.valueOf(queueSize))); - initQueue(queueSize); - // Load our engine - this will use the latest configuration - // that was saved to disk and set our initial status object. - // - PDPEngine engine = XACMLPdpLoader.loadEngine(XACMLPdpServlet.status, null, null); - if (engine != null) { - synchronized(pdpEngineLock) { - pdpEngine = engine; - } - // Notification will be Sent Here. - XACMLPdpLoader.sendNotification(); - } - // - // Logging stuff.... - // - baseLoggingContext = new ONAPLoggingContext(); - // fixed data that will be the same in all logging output goes here - try { - String hostname = InetAddress.getLocalHost().getCanonicalHostName(); - baseLoggingContext.setServer(hostname); - } catch (UnknownHostException e) { - logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"+e); - } - - Properties properties; - try { - properties = XACMLProperties.getProperties(); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, - "Error loading properties with: XACMLProperties.getProperties()"); - throw new ServletException(e.getMessage(), e.getCause()); - } - if(properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME)==null){ - XACMLProperties.reloadProperties(); - try { - properties = XACMLProperties.getProperties(); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, - "Error loading properties with: XACMLProperties.getProperties()"); - throw new ServletException(e.getMessage(), e.getCause()); - } - PolicyLogger.info("\n Properties Given : \n" + properties.toString()); - } - setPDPResourceName(properties); - dependencyGroups = properties.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS); - if(dependencyGroups == null){ - PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, IntegrityMonitorProperties.DEPENDENCY_GROUPS, "xacml.pdp"); - throw new ServletException("dependency_groups is null"); - } - setDependencyNodes(dependencyGroups); - - - // CreateUpdatePolicy ResourceName - createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE); - setCreateUpdatePolicyConstructor(createUpdateResourceName); - - // Create an IntegrityMonitor - try { - logger.info("Creating IntegrityMonitor"); - im = IntegrityMonitor.getInstance(pdpResourceName, properties); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" +e); - throw new ServletException(e); - } - startThreads(baseLoggingContext, new Thread(this)); - } - - private static void startThreads(ONAPLoggingContext baseLoggingContext, Thread thread) { - environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); + private static final long serialVersionUID = 1L; + private static final String DEFAULT_MAX_CONTENT_LENGTH = "999999999"; // 32767 + private static final String CREATE_UPDATE_POLICY_SERVICE = + "org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl"; + // + // Our application debug log + // + private static final Log logger = LogFactory.getLog(XACMLPdpServlet.class); + // + // This logger is specifically only for Xacml requests and their corresponding response. + // It's output ideally should be sent to a separate file from the application logger. + // + private static final Log requestLogger = LogFactory.getLog("xacml.request"); + // + // audit logger + private static final Log auditLogger = LogFactory.getLog("auditLogger"); + + public static final PdpRestMonitor monitor = PdpRestMonitor.getSingleton(); + + // + // This thread may getting invoked on startup, to let the PAP know + // that we are up and running. + // + private static transient Thread registerThread = null; + private static transient XACMLPdpRegisterThread registerRunnable = null; + // + // This is our PDP engine pointer. There is a synchronized lock used + // for access to the pointer. In case we are servicing PEP requests while + // an update is occurring from the PAP. + // + private static PDPEngine pdpEngine = null; + private static final Object pdpEngineLock = new Object(); + // + // This is our PDP's status. What policies are loaded (or not) and + // what PIP configurations are loaded (or not). + // There is a synchronized lock used for access to the object. + // + private static volatile StdPDPStatus status = new StdPDPStatus(); + private static final Object pdpStatusLock = new Object(); + private static Constructor createUpdatePolicyConstructor; + + private static final String ENVIORNMENT_HEADER = "Environment"; + private static String environment = null; + + // + // Queue of PUT requests + // + public static class PutRequest { + private Properties policyProperties = null; + private Properties pipConfigProperties = null; + + PutRequest(Properties policies, Properties pips) { + this.policyProperties = policies; + this.pipConfigProperties = pips; + } + } + + protected static volatile BlockingQueue queue = null; + // For notification Delay. + private static int notificationDelay = 0; + + public static int getNotificationDelay() { + return XACMLPdpServlet.notificationDelay; + } + + private static String pdpResourceName; + private static String[] dependencyNodes = null; + + // + // This is our configuration thread that attempts to load + // a new configuration request. + // + private static transient Thread configThread = null; + private static volatile boolean configThreadTerminate = false; + private transient ONAPLoggingContext baseLoggingContext = null; + private transient IntegrityMonitor im; + + public IntegrityMonitor getIm() { + return im; + } + + public void setIm(IntegrityMonitor im) { + this.im = im; + } + + /** + * Default constructor. + */ + public XACMLPdpServlet() { + // Default constructor. + } + + /** + * @see Servlet#init(ServletConfig) + */ + @Override + public void init(ServletConfig config) throws ServletException { + String createUpdateResourceName = null; + String dependencyGroups = null; + // + // Initialize + // + XACMLRest.xacmlInit(config); + // Load the Notification Delay. + setNotificationDelay(); + // Load Queue size. Not sure if we really need to have the queue bounded, we should look further into this + int queueSize = 50; // Set default Queue Size here. + queueSize = Integer.parseInt(XACMLProperties.getProperty("REQUEST_BUFFER_SIZE", String.valueOf(queueSize))); + initQueue(queueSize); + // Load our engine - this will use the latest configuration + // that was saved to disk and set our initial status object. + // + PDPEngine engine = XACMLPdpLoader.loadEngine(XACMLPdpServlet.status, null, null); + if (engine != null) { + synchronized (pdpEngineLock) { + pdpEngine = engine; + } + // Notification will be Sent Here. + XACMLPdpLoader.sendNotification(); + } + // + // Logging stuff.... + // + baseLoggingContext = new ONAPLoggingContext(); + // fixed data that will be the same in all logging output goes here + try { + String hostname = InetAddress.getLocalHost().getCanonicalHostName(); + baseLoggingContext.setServer(hostname); + } catch (UnknownHostException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging" + e); + } + + Properties properties; + try { + properties = XACMLProperties.getProperties(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, + "Error loading properties with: XACMLProperties.getProperties()"); + throw new ServletException(e.getMessage(), e.getCause()); + } + if (properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME) == null) { + XACMLProperties.reloadProperties(); + try { + properties = XACMLProperties.getProperties(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, + "Error loading properties with: XACMLProperties.getProperties()"); + throw new ServletException(e.getMessage(), e.getCause()); + } + PolicyLogger.info("\n Properties Given : \n" + properties.toString()); + } + setPDPResourceName(properties); + dependencyGroups = properties.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS); + if (dependencyGroups == null) { + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, IntegrityMonitorProperties.DEPENDENCY_GROUPS, + "xacml.pdp"); + throw new ServletException("dependency_groups is null"); + } + setDependencyNodes(dependencyGroups); + + + // CreateUpdatePolicy ResourceName + createUpdateResourceName = + properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE); + setCreateUpdatePolicyConstructor(createUpdateResourceName); + + // Create an IntegrityMonitor + try { + logger.info("Creating IntegrityMonitor"); + im = IntegrityMonitor.getInstance(pdpResourceName, properties); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" + e); + throw new ServletException(e); + } + startThreads(baseLoggingContext, new Thread(this)); + } + + private static void startThreads(ONAPLoggingContext baseLoggingContext, Thread thread) { + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); // // Kick off our thread to register with the PAP servlet. // @@ -298,1029 +298,1039 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { } private static void setDependencyNodes(String dependencyGroups) { - // dependency_groups is a semicolon-delimited list of groups, and + // dependency_groups is a semicolon-delimited list of groups, and // each group is a comma-separated list of nodes. For our purposes // we just need a list of dependencies without regard to grouping, // so split the list into nodes separated by either comma or semicolon. dependencyNodes = dependencyGroups.split("[;,]"); - for (int i = 0 ; i < dependencyNodes.length ; i++){ + for (int i = 0; i < dependencyNodes.length; i++) { dependencyNodes[i] = dependencyNodes[i].trim(); } } private static void setPDPResourceName(Properties properties) throws ServletException { - pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME); - if(pdpResourceName == null){ + pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME); + if (pdpResourceName == null) { PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp"); throw new ServletException("pdpResourceName is null"); } } private static void initQueue(int queueSize) { - queue = new LinkedBlockingQueue<>(queueSize); + queue = new LinkedBlockingQueue<>(queueSize); } private static void setNotificationDelay() { - try{ - XACMLPdpServlet.notificationDelay = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY)); - }catch(NumberFormatException e){ + try { + XACMLPdpServlet.notificationDelay = + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY)); + } catch (NumberFormatException e) { logger.error("Error in notification delay format, Taking the default value.", e); } } /** - * @see Servlet#destroy() - */ - @Override - public void destroy() { - super.destroy(); - logger.info("Destroying...."); - // - // Make sure the register thread is not running - // - if (XACMLPdpServlet.registerRunnable != null) { - try { - XACMLPdpServlet.registerRunnable.terminate(); - if (XACMLPdpServlet.registerThread != null) { - XACMLPdpServlet.registerThread.interrupt(); - XACMLPdpServlet.registerThread.join(); - } - } catch (InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - XACMLPdpServlet.registerThread.interrupt(); - } - } - // - // Make sure the configure thread is not running - // - setConfigThreadTerminate(true); - try { - XACMLPdpServlet.configThread.interrupt(); - XACMLPdpServlet.configThread.join(); - } catch (InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - XACMLPdpServlet.configThread.interrupt(); - } - logger.info("Destroyed."); - } - - private static void setConfigThreadTerminate(boolean value) { - XACMLPdpServlet.configThreadTerminate = value; + * @see Servlet#destroy() + */ + @Override + public void destroy() { + super.destroy(); + logger.info("Destroying...."); + // + // Make sure the register thread is not running + // + if (XACMLPdpServlet.registerRunnable != null) { + try { + XACMLPdpServlet.registerRunnable.terminate(); + if (XACMLPdpServlet.registerThread != null) { + XACMLPdpServlet.registerThread.interrupt(); + XACMLPdpServlet.registerThread.join(); + } + } catch (InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + XACMLPdpServlet.registerThread.interrupt(); + } + } + // + // Make sure the configure thread is not running + // + setConfigThreadTerminate(true); + try { + XACMLPdpServlet.configThread.interrupt(); + XACMLPdpServlet.configThread.join(); + } catch (InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + XACMLPdpServlet.configThread.interrupt(); + } + logger.info("Destroyed."); + } + + private static void setConfigThreadTerminate(boolean value) { + XACMLPdpServlet.configThreadTerminate = value; + } + + /** + * PUT - The PAP engine sends configuration information using HTTP PUT request. + * + * One parameter is expected: + * + * config=[policy|pip|all] + * + * policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP + * should be using for PEP requests. + * + * Specifically should AT LEAST contain the following properties: xacml.rootPolicies xacml.referencedPolicies + * + * In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache. + * + * EXAMPLE: xacml.rootPolicies=PolicyA.1, PolicyB.1 + * + * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1 + * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1 + * + * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1 + * + * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1 + * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1 + * + * pip - Expect a properties file that contain PIP engine configuration properties. + * + * Specifically should AT LEAST the following property: xacml.pip.engines + * + * In addition, any relevant information needed by the PDP to load and configure the PIPs. + * + * EXAMPLE: xacml.pip.engines=foo,bar + * + * foo.classname=com.foo foo.sample=abc foo.example=xyz ...... + * + * bar.classname=com.bar ...... + * + * all - Expect ALL new configuration properties for the PDP + * + * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) + */ + @Override + protected void doPut(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())) { + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)"); + } + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); + // + // Dump our request out + // + if (logger.isDebugEnabled()) { + XACMLRest.dumpRequest(request); + } + + try { + im.startTransaction(); + } catch (IntegrityMonitorException e) { + String message = e.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } + // + // What is being PUT? + // + String cache = request.getParameter("cache"); + // + // Should be a list of policy and pip configurations in Java properties format + // + if (cache != null && request.getContentType().equals("text/x-java-properties")) { + loggingContext.setServiceName("PDP.putConfig"); + try { + if (request.getContentLength() > Integer + .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", DEFAULT_MAX_CONTENT_LENGTH))) { + String message = "Content-Length larger than server will accept."; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + loggingContext.transactionEnded(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + im.endTransaction(); + return; + } + logger.info("XACMLPdpServlet: calling doPutConfig to add properties to the queue"); + this.doPutConfig(cache, request, response, loggingContext); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction ended"); + + im.endTransaction(); + } catch (Exception e) { + logger.error("Exception Occured while getting Max Content lenght" + e); + } + } else { + String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'"; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + } + + protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, + ONAPLoggingContext loggingContext) throws ServletException, IOException { + try { + // prevent multiple configuration changes from stacking up + logger.info("XACMLPdpServlet: checking remainingCapacity of Queue."); + if (XACMLPdpServlet.queue.remainingCapacity() <= 0) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Queue capacity reached"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Queue capacity reached"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_CONFLICT, + "Multiple configuration changes waiting processing."); + return; + } + // + // Read the properties data into an object. + // + Properties newProperties = new Properties(); + newProperties.load(request.getInputStream()); + // should have something in the request + if (newProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); + return; + } + // + // Which set of properties are they sending us? Whatever they send gets + // put on the queue (if there is room). + // For audit logging purposes, we consider the transaction done once the + // the request gets put on the queue. + // + if (config.equals("policies")) { + newProperties = XACMLProperties.getPolicyProperties(newProperties, true); + if (newProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, + "PUT with cache=policies must contain at least one policy property"); + return; + } + logger.info("XACMLPdpServlet: offer policies to queue. No pip properties added."); + XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null)); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + } else if (config.equals("pips")) { + newProperties = XACMLProperties.getPipProperties(newProperties); + if (newProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, + "PUT with cache=pips must contain at least one pip property"); + return; + } + logger.info("XACMLPdpServlet: offer pips to queue. No policy properties added."); + XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties)); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + } else if (config.equals("all")) { + Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true); + if (newPolicyProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, + "PUT with cache=all must contain at least one policy property"); + return; + } + Properties newPipProperties = XACMLProperties.getPipProperties(newProperties); + if (newPipProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, + "PUT with cache=all must contain at least one pip property"); + return; + } + logger.info("XACMLPdpServlet: offer policies and pips to queue."); + XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties)); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + + } else { + // + // Invalid value + // + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid config value: " + config); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid config value: " + config); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, + "Config must be one of 'policies', 'pips', 'all'"); + return; + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to process new configuration.", e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to process new configuration"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } + + } + + /** + * Parameters: type=hb|config|Status + * + * 1. HeartBeat Status HeartBeat OK - All Policies are Loaded, All PIPs are Loaded LOADING_IN_PROGRESS - Currently + * loading a new policy set/pip configuration LAST_UPDATE_FAILED - Need to track the items that failed during last + * update LOAD_FAILURE - ??? Need to determine what information is sent and how 2. Configuration 3. Status return + * the StdPDPStatus object in the Response content + * + * + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")) { + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)"); + } + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); + + XACMLRest.dumpRequest(request); + + String pathInfo = request.getRequestURI(); + if (pathInfo != null) { + // health check from Global Site Selector (iDNS). + // DO NOT do a im.startTransaction for the test request + if (pathInfo.equals("/pdp/test")) { + loggingContext.setServiceName("iDNS:PDP.test"); + try { + im.evaluateSanity(); + // If we make it this far, all is well + String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK"; + PolicyLogger.debug(message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Success"); + response.setStatus(HttpServletResponse.SC_OK); + return; + } catch (ForwardProgressException fpe) { + // No forward progress is being made + String message = "GET:/pdp/test called and PDP " + pdpResourceName + + " is not making forward progress." + " Exception Message: " + fpe.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } catch (AdministrativeStateException ase) { + // Administrative State is locked + String message = "GET:/pdp/test called and PDP " + pdpResourceName + + " Administrative State is LOCKED " + " Exception Message: " + ase.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + ase); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } catch (StandbyStatusException sse) { + // Administrative State is locked + String message = "GET:/pdp/test called and PDP " + pdpResourceName + + " Standby Status is NOT PROVIDING SERVICE " + " Exception Message: " + sse.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + sse); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } catch (Exception e) { + // A subsystem is not making progress or is not responding + String eMsg = e.getMessage(); + if (eMsg == null) { + eMsg = "No Exception Message"; + } + String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure." + + " Exception Message: " + eMsg; + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + // Get the specific list of subsystems that failed + String failedNodeList = null; + for (String node : dependencyNodes) { + if (eMsg.contains(node)) { + if (failedNodeList == null) { + failedNodeList = node; + } else { + failedNodeList = failedNodeList.concat("," + node); + } + } + } + if (failedNodeList == null) { + failedNodeList = "UnknownSubSystem"; + } + response.addHeader("X-ONAP-SubsystemFailure", failedNodeList); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log" + e); + return; + } + } + } + + try { + im.startTransaction(); + } catch (IntegrityMonitorException e) { + String message = e.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log" + e); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } + // + // What are they requesting? + // + boolean returnHB = false; + response.setHeader("Cache-Control", "no-cache"); + String type = request.getParameter("type"); + // type might be null, so use equals on string constants + if ("config".equals(type)) { + loggingContext.setServiceName("PDP.getConfig"); + response.setContentType("text/x-java-properties"); + try { + String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); + lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n"; + try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes()); + InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); + OutputStream os = response.getOutputStream()) { + IOUtils.copy(listInputStream, os); + IOUtils.copy(pipInputStream, os); + } + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + response.setStatus(HttpServletResponse.SC_OK); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(400, "Failed to copy Property file"); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + } + + } else if ("hb".equals(type)) { + returnHB = true; + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + + } else if ("Status".equals(type)) { + loggingContext.setServiceName("PDP.getStatus"); + // convert response object to JSON and include in the response + synchronized (pdpStatusLock) { + ObjectMapper mapper = new ObjectMapper(); + try { + mapper.writeValue(response.getOutputStream(), status); + } catch (Exception e1) { + logger.error("Exception occured while writing output stream" + e1); + } + } + response.setStatus(HttpServletResponse.SC_OK); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + + } else { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + } + if (returnHB) { + synchronized (pdpStatusLock) { + response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString()); + } + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended"); + im.endTransaction(); + } /** - * PUT - The PAP engine sends configuration information using HTTP PUT request. - * - * One parameter is expected: - * - * config=[policy|pip|all] - * - * policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP should - * be using for PEP requests. - * - * Specifically should AT LEAST contain the following properties: - * xacml.rootPolicies - * xacml.referencedPolicies - * - * In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache. - * - * EXAMPLE: - * xacml.rootPolicies=PolicyA.1, PolicyB.1 - * - * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1 - * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1 - * - * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1 - * - * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1 - * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1 - * - * pip - Expect a properties file that contain PIP engine configuration properties. - * - * Specifically should AT LEAST the following property: - * xacml.pip.engines - * - * In addition, any relevant information needed by the PDP to load and configure the PIPs. - * - * EXAMPLE: - * xacml.pip.engines=foo,bar - * - * foo.classname=com.foo - * foo.sample=abc - * foo.example=xyz - * ...... - * - * bar.classname=com.bar - * ...... - * - * all - Expect ALL new configuration properties for the PDP - * - * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) - */ - @Override - protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)"); - } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); - // - // Dump our request out - // - if (logger.isDebugEnabled()) { - XACMLRest.dumpRequest(request); - } - - try { - im.startTransaction(); - } - catch (IntegrityMonitorException e) { - String message = e.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - // - // What is being PUT? - // - String cache = request.getParameter("cache"); - // - // Should be a list of policy and pip configurations in Java properties format - // - if (cache != null && request.getContentType().equals("text/x-java-properties")) { - loggingContext.setServiceName("PDP.putConfig"); - try{ - if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", DEFAULT_MAX_CONTENT_LENGTH))) { - String message = "Content-Length larger than server will accept."; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - loggingContext.transactionEnded(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - im.endTransaction(); - return; - } - logger.info("XACMLPdpServlet: calling doPutConfig to add properties to the queue"); - this.doPutConfig(cache, request, response, loggingContext); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction ended"); - - im.endTransaction(); - }catch(Exception e){ - logger.error("Exception Occured while getting Max Content lenght"+e); - } - } else { - String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'"; - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - } - - protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws ServletException, IOException { - try { - // prevent multiple configuration changes from stacking up - logger.info("XACMLPdpServlet: checking remainingCapacity of Queue."); - if (XACMLPdpServlet.queue.remainingCapacity() <= 0) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Queue capacity reached"); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Queue capacity reached"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing."); - return; - } - // - // Read the properties data into an object. - // - Properties newProperties = new Properties(); - newProperties.load(request.getInputStream()); - // should have something in the request - if (newProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); - return; - } - // - // Which set of properties are they sending us? Whatever they send gets - // put on the queue (if there is room). - // For audit logging purposes, we consider the transaction done once the - // the request gets put on the queue. - // - if (config.equals("policies")) { - newProperties = XACMLProperties.getPolicyProperties(newProperties, true); - if (newProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property"); - return; - } - logger.info("XACMLPdpServlet: offer policies to queue. No pip properties added."); - XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null)); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - } else if (config.equals("pips")) { - newProperties = XACMLProperties.getPipProperties(newProperties); - if (newProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property"); - return; - } - logger.info("XACMLPdpServlet: offer pips to queue. No policy properties added."); - XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties)); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - } else if (config.equals("all")) { - Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true); - if (newPolicyProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property"); - return; - } - Properties newPipProperties = XACMLProperties.getPipProperties(newProperties); - if (newPipProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property"); - return; - } - logger.info("XACMLPdpServlet: offer policies and pips to queue."); - XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties)); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - - } else { - // - // Invalid value - // - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid config value: " + config); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid config value: " + config); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'"); - return; - } - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to process new configuration.", e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to process new configuration"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - - } - - /** - * Parameters: type=hb|config|Status - * - * 1. HeartBeat Status - * HeartBeat - * OK - All Policies are Loaded, All PIPs are Loaded - * LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration - * LAST_UPDATE_FAILED - Need to track the items that failed during last update - * LOAD_FAILURE - ??? Need to determine what information is sent and how - * 2. Configuration - * 3. Status - * return the StdPDPStatus object in the Response content - * - * - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)"); - } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); - - XACMLRest.dumpRequest(request); - - String pathInfo = request.getRequestURI(); - if (pathInfo != null){ - // health check from Global Site Selector (iDNS). - // DO NOT do a im.startTransaction for the test request - if (pathInfo.equals("/pdp/test")) { - loggingContext.setServiceName("iDNS:PDP.test"); - try { - im.evaluateSanity(); - //If we make it this far, all is well - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK"; - PolicyLogger.debug(message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Success"); - response.setStatus(HttpServletResponse.SC_OK); - return; - } catch (ForwardProgressException fpe){ - //No forward progress is being made - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress." - + " Exception Message: " + fpe.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - }catch (AdministrativeStateException ase){ - //Administrative State is locked - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Administrative State is LOCKED " - + " Exception Message: " + ase.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + ase); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - }catch (StandbyStatusException sse){ - //Administrative State is locked - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Standby Status is NOT PROVIDING SERVICE " - + " Exception Message: " + sse.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + sse); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } catch (Exception e) { - //A subsystem is not making progress or is not responding - String eMsg = e.getMessage(); - if(eMsg == null){ - eMsg = "No Exception Message"; - } - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure." - + " Exception Message: " + eMsg; - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message ); - //Get the specific list of subsystems that failed - String failedNodeList = null; - for(String node : dependencyNodes){ - if(eMsg.contains(node)){ - if(failedNodeList == null){ - failedNodeList = node; - }else{ - failedNodeList = failedNodeList.concat(","+node); - } - } - } - if(failedNodeList == null){ - failedNodeList = "UnknownSubSystem"; - } - response.addHeader("X-ONAP-SubsystemFailure", failedNodeList); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log" + e); - return; - } - } - } - - try { - im.startTransaction(); - } - catch (IntegrityMonitorException e) { - String message = e.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log" +e); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - // - // What are they requesting? - // - boolean returnHB = false; - response.setHeader("Cache-Control", "no-cache"); - String type = request.getParameter("type"); - // type might be null, so use equals on string constants - if ("config".equals(type)) { - loggingContext.setServiceName("PDP.getConfig"); - response.setContentType("text/x-java-properties"); - try { - String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); - lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n"; - try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes()); - InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); - OutputStream os = response.getOutputStream()) { - IOUtils.copy(listInputStream, os); - IOUtils.copy(pipInputStream, os); - } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - response.setStatus(HttpServletResponse.SC_OK); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(400, "Failed to copy Property file"); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - } - - } else if ("hb".equals(type)) { - returnHB = true; - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - - } else if ("Status".equals(type)) { - loggingContext.setServiceName("PDP.getStatus"); - // convert response object to JSON and include in the response - synchronized(pdpStatusLock) { - ObjectMapper mapper = new ObjectMapper(); - try{ - mapper.writeValue(response.getOutputStream(), status); - }catch(Exception e1){ - logger.error("Exception occured while writing output stream" +e1); - } - } - response.setStatus(HttpServletResponse.SC_OK); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - - } else { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - } - if (returnHB) { - synchronized(pdpStatusLock) { - response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString()); - } - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended"); - im.endTransaction(); - - } - - /** - * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON according - * to the XACML 3.0 Specifications for both. - * - * - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - loggingContext.setServiceName("PDP.decide"); - if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)"); - } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); - monitor.pdpEvaluationAttempts(); - - try { - im.startTransaction(); - } - catch (IntegrityMonitorException e) { - String message = e.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - // - // no point in doing any work if we know from the get-go that we cannot do anything with the request - // - if (status.getLoadedRootPolicies().isEmpty()) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - - XACMLRest.dumpRequest(request); - // - // Set our no-cache header - // - response.setHeader("Cache-Control", "no-cache"); - // - // They must send a Content-Type - // - if (request.getContentType() == null) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Must specify a Content-Type"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Must specify a Content-Type"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given"); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // Limit the Content-Length to something reasonable - // - try{ - if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) { - String message = "Content-Length larger than server will accept."; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - im.endTransaction(); - return; - } - }catch(Exception e){ - logger.error("Exception occured while getting max content length"+e); - } - - if (request.getContentLength() <= 0) { - String message = "Content-Length is negative"; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - ContentType contentType = null; - try { - contentType = ContentType.parse(request.getContentType()); - } - catch (Exception e) { - String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage(); - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message, e); - loggingContext.transactionEnded(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, message); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // What exactly did they send us? - // - String incomingRequestString = null; - Request pdpRequest = null; - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) { - // - // Read in the string - // - StringBuilder buffer = new StringBuilder(); - BufferedReader reader = null; - try{ - reader = new BufferedReader(new InputStreamReader(request.getInputStream())); - }catch(IOException e){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error during reading input stream",e); - return; - } - String line; - try{ - while((line = reader.readLine()) != null){ - buffer.append(line); - } - }catch(Exception e){ - logger.error("Exception Occured while reading line"+e); - } - - incomingRequestString = buffer.toString(); - logger.info(incomingRequestString); - // - // Parse into a request - // - try { - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { - pdpRequest = JSONRequest.load(incomingRequestString); - } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { - pdpRequest = DOMRequest.load(incomingRequestString); - } - } - catch(Exception e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not parse request", e); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Could not parse request"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - } else { - String message = "unsupported content type" + request.getContentType(); - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // Did we successfully get and parse a request? - // - if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) { - String message = "Zero Attributes found in the request"; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // Run it - // - try { - // - // Authenticating the Request here. - // - if(!authorizeRequest(request)){ - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message ); - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - im.endTransaction(); - return; - } - // - // Get the pointer to the PDP Engine - // - PDPEngine myEngine = null; - synchronized(pdpEngineLock) { - myEngine = XACMLPdpServlet.pdpEngine; - } - if (myEngine == null) { - String message = "No engine loaded."; - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - im.endTransaction(); - return; - } - // - // Send the request and save the response - // - long lTimeStart; - long lTimeEnd; - Response pdpResponse = null; - - synchronized(pdpEngineLock) { - myEngine = XACMLPdpServlet.pdpEngine; - try { - PolicyList.clearPolicyList(); - lTimeStart = System.currentTimeMillis(); - pdpResponse = myEngine.decide(pdpRequest); - lTimeEnd = System.currentTimeMillis(); - } catch (PDPException e) { - String message = "Exception during decide: " + e.getMessage(); - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message +e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - } - monitor.computeLatency(lTimeEnd - lTimeStart); - requestLogger.info(lTimeStart + "=" + incomingRequestString); - for(String policy : PolicyList.getpolicyList()){ - monitor.policyCountAdd(policy, 1); - } - - - logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList()); - - //need to go through the list and find out if the value is unique and then add it other wise - // monitor.policyCountAdd(PolicyList.getpolicyList(), 1); - - if (logger.isDebugEnabled()) { - logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms"); - } - // - // Convert Response to appropriate Content-Type - // - if (pdpResponse == null) { - requestLogger.info(lTimeStart + "=" + "{}"); - try{ - throw new PDPException("Failed to get response from PDP engine."); - }catch(Exception e1){ - logger.error("Exception occured while throwing Exception" +e1); - } - } - // - // Set our content-type - // - response.setContentType(contentType.getMimeType()); - // - // Convert the PDP response object to a String to - // return to our caller as well as dump to our loggers. - // - String outgoingResponseString = ""; - try{ - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { - // - // Get it as a String. This is not very efficient but we need to log our - // results for auditing. - // - outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled()); - if (logger.isDebugEnabled()) { - logger.debug(outgoingResponseString); - // - // Get rid of whitespace - // - outgoingResponseString = JSONResponse.toString(pdpResponse, false); - } - } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { - // - // Get it as a String. This is not very efficient but we need to log our - // results for auditing. - // - outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled()); - if (logger.isDebugEnabled()) { - logger.debug(outgoingResponseString); - // - // Get rid of whitespace - // - outgoingResponseString = DOMResponse.toString(pdpResponse, false); - } - } - // adding the jmx values for NA, Permit and Deny - // - if (outgoingResponseString.contains("NotApplicable") || outgoingResponseString.contains("Decision not a Permit")){ - monitor.pdpEvaluationNA(); - } - - if (outgoingResponseString.contains("Permit") && !outgoingResponseString.contains("Decision not a Permit")){ - monitor.pdpEvaluationPermit(); - } - - if (outgoingResponseString.contains("Deny")){ - monitor.pdpEvaluationDeny(); - } - // - // lTimeStart is used as an ID within the requestLogger to match up - // request's with responses. - // - requestLogger.info(lTimeStart + "=" + outgoingResponseString); - response.getWriter().print(outgoingResponseString); - }catch(Exception e){ - logger.error("Exception Occured"+e ); - } - } - catch (Exception e) { - String message = "Exception executing request: " + e; - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message, e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - - monitor.pdpEvaluationSuccess(); - response.setStatus(HttpServletResponse.SC_OK); - - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - - } - - /* - * Added for Authorizing the PEP Requests for Environment check. - */ - private boolean authorizeRequest(HttpServletRequest request) { - // Get the client Credentials from the Request header. - HttpServletRequest httpServletRequest = request; - String clientCredentials = httpServletRequest.getHeader(ENVIORNMENT_HEADER); - if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ - return true; - }else{ - return false; - } - } - - @Override - public void run() { - // - // Keep running until we are told to terminate - // - try { - // variable not used, but constructor has needed side-effects so don't remove: - while (! XACMLPdpServlet.configThreadTerminate) { - logger.info("XACMLPdpServlet: Taking requests from the queue"); - PutRequest request = XACMLPdpServlet.queue.take(); - logger.info("XACMLPdpServlet: Taking requests from the queue COMPLETED"); - StdPDPStatus newStatus = new StdPDPStatus(); - - PDPEngine newEngine = null; - synchronized(pdpStatusLock) { - XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION); - - logger.info("created new PDPEngine"); - newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); - } - if (newEngine != null) { - logger.info("XACMLPdpServlet: newEngine created, assigning newEngine to the pdpEngine."); - synchronized(XACMLPdpServlet.pdpEngineLock) { - XACMLPdpServlet.pdpEngine = newEngine; - try { - logger.info("Saving configuration."); - if (request.policyProperties != null) { - logger.info("Saving configuration: Policy Properties: " + request.policyProperties); - try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPDPPolicyCache())) { - request.policyProperties.store(os, ""); - } - } - if (request.pipConfigProperties != null) { - logger.info("Saving configuration: PIP Properties: " + request.pipConfigProperties); - try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) { - request.pipConfigProperties.store(os, ""); - } - } - newStatus.setStatus(Status.UP_TO_DATE); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to store new properties."+e); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to store new properties"); - newStatus.setStatus(Status.LOAD_ERRORS); - newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage()); - } - } - } else { - newStatus.setStatus(Status.LAST_UPDATE_FAILED); - } - synchronized(pdpStatusLock) { - XACMLPdpServlet.status.set(newStatus); - } - logger.info("New PDP Servlet Status: " + newStatus.getStatus()); - if (Status.UP_TO_DATE.equals(newStatus.getStatus())) { - // Notification will be Sent Here. - XACMLPdpLoader.sendNotification(); - } - } - } catch (InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "interrupted"+e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "interrupted"); - Thread.currentThread().interrupt(); - } - } - - public static PDPEngine getPDPEngine(){ - PDPEngine myEngine = null; - synchronized(pdpEngineLock) { - myEngine = XACMLPdpServlet.pdpEngine; - } - return myEngine; - } - - public static Constructor getCreateUpdatePolicyConstructor(){ - return createUpdatePolicyConstructor; - } - - private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException{ - try{ - Class createUpdateclass = Class.forName(createUpdateResourceName); - createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init" +e); - throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage()); - } - } + * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON + * according to the XACML 3.0 Specifications for both. + * + * + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + loggingContext.setServiceName("PDP.decide"); + if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))) { + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)"); + } + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); + monitor.pdpEvaluationAttempts(); + + try { + im.startTransaction(); + } catch (IntegrityMonitorException e) { + String message = e.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } + // + // no point in doing any work if we know from the get-go that we cannot do anything with the request + // + if (status.getLoadedRootPolicies().isEmpty()) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Request from PEP at " + request.getRequestURI() + + " for service when PDP has No Root Policies loaded"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Request from PEP at " + request.getRequestURI() + + " for service when PDP has No Root Policies loaded"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + + XACMLRest.dumpRequest(request); + // + // Set our no-cache header + // + response.setHeader("Cache-Control", "no-cache"); + // + // They must send a Content-Type + // + if (request.getContentType() == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Must specify a Content-Type"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Must specify a Content-Type"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given"); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + // + // Limit the Content-Length to something reasonable + // + try { + if (request.getContentLength() > Integer + .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) { + String message = "Content-Length larger than server will accept."; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + im.endTransaction(); + return; + } + } catch (Exception e) { + logger.error("Exception occured while getting max content length" + e); + } + + if (request.getContentLength() <= 0) { + String message = "Content-Length is negative"; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + ContentType contentType = null; + try { + contentType = ContentType.parse(request.getContentType()); + } catch (Exception e) { + String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message, e); + loggingContext.transactionEnded(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, message); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + // + // What exactly did they send us? + // + String incomingRequestString = null; + Request pdpRequest = null; + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) + || contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) + || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { + // + // Read in the string + // + StringBuilder buffer = new StringBuilder(); + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(request.getInputStream())); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error during reading input stream", e); + return; + } + String line; + try { + while ((line = reader.readLine()) != null) { + buffer.append(line); + } + } catch (Exception e) { + logger.error("Exception Occured while reading line" + e); + } + + incomingRequestString = buffer.toString(); + logger.info(incomingRequestString); + // + // Parse into a request + // + try { + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + pdpRequest = JSONRequest.load(incomingRequestString); + } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) + || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { + pdpRequest = DOMRequest.load(incomingRequestString); + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not parse request", e); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Could not parse request"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + } else { + String message = "unsupported content type" + request.getContentType(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + // + // Did we successfully get and parse a request? + // + if (pdpRequest == null || pdpRequest.getRequestAttributes() == null + || pdpRequest.getRequestAttributes().size() <= 0) { + String message = "Zero Attributes found in the request"; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + // + // Run it + // + try { + // + // Authenticating the Request here. + // + if (!authorizeRequest(request)) { + String message = + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message); + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + im.endTransaction(); + return; + } + // + // Get the pointer to the PDP Engine + // + PDPEngine myEngine = null; + synchronized (pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + } + if (myEngine == null) { + String message = "No engine loaded."; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + im.endTransaction(); + return; + } + // + // Send the request and save the response + // + long lTimeStart; + long lTimeEnd; + Response pdpResponse = null; + + synchronized (pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + try { + PolicyList.clearPolicyList(); + lTimeStart = System.currentTimeMillis(); + pdpResponse = myEngine.decide(pdpRequest); + lTimeEnd = System.currentTimeMillis(); + } catch (PDPException e) { + String message = "Exception during decide: " + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + im.endTransaction(); + return; + } + } + monitor.computeLatency(lTimeEnd - lTimeStart); + requestLogger.info(lTimeStart + "=" + incomingRequestString); + for (String policy : PolicyList.getpolicyList()) { + monitor.policyCountAdd(policy, 1); + } + + + logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList()); + + // need to go through the list and find out if the value is unique and then add it other wise + // monitor.policyCountAdd(PolicyList.getpolicyList(), 1); + + if (logger.isDebugEnabled()) { + logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms"); + } + // + // Convert Response to appropriate Content-Type + // + if (pdpResponse == null) { + requestLogger.info(lTimeStart + "=" + "{}"); + try { + throw new PDPException("Failed to get response from PDP engine."); + } catch (Exception e1) { + logger.error("Exception occured while throwing Exception" + e1); + } + } + // + // Set our content-type + // + response.setContentType(contentType.getMimeType()); + // + // Convert the PDP response object to a String to + // return to our caller as well as dump to our loggers. + // + String outgoingResponseString = ""; + try { + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + // + // Get it as a String. This is not very efficient but we need to log our + // results for auditing. + // + outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled()); + if (logger.isDebugEnabled()) { + logger.debug(outgoingResponseString); + // + // Get rid of whitespace + // + outgoingResponseString = JSONResponse.toString(pdpResponse, false); + } + } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) + || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { + // + // Get it as a String. This is not very efficient but we need to log our + // results for auditing. + // + outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled()); + if (logger.isDebugEnabled()) { + logger.debug(outgoingResponseString); + // + // Get rid of whitespace + // + outgoingResponseString = DOMResponse.toString(pdpResponse, false); + } + } + // adding the jmx values for NA, Permit and Deny + // + if (outgoingResponseString.contains("NotApplicable") + || outgoingResponseString.contains("Decision not a Permit")) { + monitor.pdpEvaluationNA(); + } + + if (outgoingResponseString.contains("Permit") + && !outgoingResponseString.contains("Decision not a Permit")) { + monitor.pdpEvaluationPermit(); + } + + if (outgoingResponseString.contains("Deny")) { + monitor.pdpEvaluationDeny(); + } + // + // lTimeStart is used as an ID within the requestLogger to match up + // request's with responses. + // + requestLogger.info(lTimeStart + "=" + outgoingResponseString); + response.getWriter().print(outgoingResponseString); + } catch (Exception e) { + logger.error("Exception Occured" + e); + } + } catch (Exception e) { + String message = "Exception executing request: " + e; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message, e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } catch (Exception e1) { + logger.error("Exception occured while sending error in response" + e1); + } + return; + } + + monitor.pdpEvaluationSuccess(); + response.setStatus(HttpServletResponse.SC_OK); + + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + + } + + /* + * Added for Authorizing the PEP Requests for Environment check. + */ + private boolean authorizeRequest(HttpServletRequest request) { + // Get the client Credentials from the Request header. + HttpServletRequest httpServletRequest = request; + String clientCredentials = httpServletRequest.getHeader(ENVIORNMENT_HEADER); + if (clientCredentials != null && clientCredentials.equalsIgnoreCase(environment)) { + return true; + } else { + return false; + } + } + + @Override + public void run() { + // + // Keep running until we are told to terminate + // + try { + // variable not used, but constructor has needed side-effects so don't remove: + while (!XACMLPdpServlet.configThreadTerminate) { + logger.info("XACMLPdpServlet: Taking requests from the queue"); + PutRequest request = XACMLPdpServlet.queue.take(); + logger.info("XACMLPdpServlet: Taking requests from the queue COMPLETED"); + StdPDPStatus newStatus = new StdPDPStatus(); + + PDPEngine newEngine = null; + synchronized (pdpStatusLock) { + XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION); + + logger.info("created new PDPEngine"); + newEngine = + XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); + } + if (newEngine != null) { + logger.info("XACMLPdpServlet: newEngine created, assigning newEngine to the pdpEngine."); + synchronized (XACMLPdpServlet.pdpEngineLock) { + XACMLPdpServlet.pdpEngine = newEngine; + try { + logger.info("Saving configuration."); + if (request.policyProperties != null) { + logger.info("Saving configuration: Policy Properties: " + request.policyProperties); + try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPDPPolicyCache())) { + request.policyProperties.store(os, ""); + } + } + if (request.pipConfigProperties != null) { + logger.info("Saving configuration: PIP Properties: " + request.pipConfigProperties); + try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) { + request.pipConfigProperties.store(os, ""); + } + } + newStatus.setStatus(Status.UP_TO_DATE); + } catch (Exception e) { + logger.error( + XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to store new properties." + e); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to store new properties"); + newStatus.setStatus(Status.LOAD_ERRORS); + newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage()); + } + } + } else { + newStatus.setStatus(Status.LAST_UPDATE_FAILED); + } + synchronized (pdpStatusLock) { + XACMLPdpServlet.status.set(newStatus); + } + logger.info("New PDP Servlet Status: " + newStatus.getStatus()); + if (Status.UP_TO_DATE.equals(newStatus.getStatus())) { + // Notification will be Sent Here. + XACMLPdpLoader.sendNotification(); + } + } + } catch (InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "interrupted" + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "interrupted"); + Thread.currentThread().interrupt(); + } + } + + public static PDPEngine getPDPEngine() { + PDPEngine myEngine = null; + synchronized (pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + } + return myEngine; + } + + public static Constructor getCreateUpdatePolicyConstructor() { + return createUpdatePolicyConstructor; + } + + public static Object getPDPEngineLock() { + return pdpEngineLock; + } + + private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException { + try { + Class createUpdateclass = Class.forName(createUpdateResourceName); + createUpdatePolicyConstructor = + createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", + "xacml.pdp.init" + e); + throw new ServletException( + "Could not find the Class name : " + createUpdateResourceName + "\n" + e.getMessage()); + } + } } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java index 85e9c6ae5..88f27232f 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -114,6 +114,7 @@ public class DecisionPolicyService { .editPolicy(updateFlag) .domain(policyScope) .highestVersion(0) + .rawXacmlPolicy(policyParameters.getRawXacmlPolicy()) .build()); // Send JSON to PAP. response = (String) papServices.callPAP(newPAPPolicy, new String[]{"operation=" + operation, "apiflag=api", diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java index a74203cca..5b1b0ba88 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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,18 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pdp.rest.api.services; +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacml.std.dom.DOMResponse; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; - import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; - +import org.apache.commons.text.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.api.DecisionRequestParameters; import org.onap.policy.api.DecisionResponse; import org.onap.policy.api.PolicyDecision; @@ -40,60 +48,83 @@ import org.onap.policy.std.StdDecisionResponse; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; + + public class GetDecisionService { private static final Logger LOGGER = FlexLogger.getLogger(GetDecisionService.class.getName()); - + private DecisionResponse decisionResponse = null; private HttpStatus status = HttpStatus.BAD_REQUEST; private DecisionRequestParameters decisionRequestParameters = null; private String message = null; private String onapComponentName = null; - private Map decisionAttributes = null; - - public GetDecisionService( - DecisionRequestParameters decisionRequestParameters, - String requestID) { + private Map decisionAttributes = null; + private UUID requestUuid = null; + private String requestType = null; + + /** + * Instantiates a new gets the decision service. + * + * @param decisionRequestParameters the decision request parameters + * @param requestId the request id + */ + public GetDecisionService(DecisionRequestParameters decisionRequestParameters, String requestId) { this.decisionRequestParameters = decisionRequestParameters; - if(decisionRequestParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { + if (decisionRequestParameters.getRequestID() == null) { + if (!StringUtils.isBlank(requestId)) { try { - requestUUID = UUID.fromString(requestID); + requestUuid = UUID.fromString(requestId); } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); + requestUuid = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUuid.toString(), e); } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } else { + requestUuid = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUuid.toString()); } - this.decisionRequestParameters.setRequestID(requestUUID); + this.decisionRequestParameters.setRequestID(requestUuid); } - try{ + try { run(); - }catch(PolicyDecisionException e){ - StdDecisionResponse decisionResponse = new StdDecisionResponse(); - decisionResponse.setDecision(PolicyDecision.ERROR); - decisionResponse.setDetails(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - this.decisionResponse = decisionResponse; + } catch (PolicyDecisionException e) { + StdDecisionResponse decisionResp = new StdDecisionResponse(); + decisionResp.setDecision(PolicyDecision.ERROR); + decisionResp.setDetails(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + this.decisionResponse = decisionResp; status = HttpStatus.BAD_REQUEST; } } - private void run() throws PolicyDecisionException{ + private void run() throws PolicyDecisionException { // Get Validation. - if(!getValidation()){ + if (!getValidation()) { LOGGER.error(message); throw new PolicyDecisionException(message); } - // Generate Request. - String modelString = getModel().toString(); - LOGGER.debug("Generated JSON Request is: " + modelString); - // Process Result. + try { + // first check whether it is a raw xacml req + if (!StringUtils.isBlank(requestType) && PDPServices.DECISION_RAW_XACML.equals(requestType)) { + this.setRequestType(PDPServices.DECISION_RAW_XACML); + processRawXacmlReq(); + return; + } + + // Generate Request. + String modelString = getModel().toString(); + LOGGER.debug("Generated JSON Request is: " + modelString); + // Process Result. + PDPServices pdpServices = new PDPServices(); + if (modelString.contains(PDPServices.RAINYDAY_TYPE)) { + pdpServices.setRequestType(PDPServices.RAINYDAY_TYPE); + this.setRequestType(PDPServices.RAINYDAY_TYPE); + } else if (PDPServices.DECISION_MS_NAMING_TYPE.equals(requestType)) { + pdpServices.setRequestType(PDPServices.DECISION_MS_NAMING_TYPE); + } status = HttpStatus.OK; - decisionResponse = decisionResult(pdpServices.generateRequest(modelString, decisionRequestParameters.getRequestID(), false, true)); + decisionResponse = decisionResult( + pdpServices.generateRequest(modelString, decisionRequestParameters.getRequestID(), false, true)); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); status = HttpStatus.BAD_REQUEST; @@ -101,8 +132,65 @@ public class GetDecisionService { } } - private DecisionResponse decisionResult( - Collection generateRequest) { + private void processRawXacmlReq() throws PolicyDecisionException { + Request pdpRequest = null; + Response pdpResponse = null; + // Process Result. + try { + PDPServices pdpServices = new PDPServices(); + pdpServices.setRequestType(PDPServices.DECISION_RAW_XACML); + String rawXacmlReq = decisionAttributes.get(PDPServices.DECISION_RAW_XACML); + if (StringUtils.isBlank(rawXacmlReq)) { + LOGGER.error("Raw XACML request cannot be empty."); + throw new PolicyDecisionException( + "Raw XACML request cannot be empty. Please provide the XACML request in " + + PDPServices.DECISION_RAW_XACML); + } + String rawXacmlReqMode = decisionAttributes.get(PDPServices.DECISION_RAW_XACML_TYPE); + String reqType = PDPServices.DECISION_RAW_XACML_XML_TYPE; + if (!StringUtils.isBlank(rawXacmlReqMode) + && PDPServices.DECISION_RAW_XACML_JSON_TYPE.equalsIgnoreCase(rawXacmlReqMode.trim())) { + pdpRequest = JSONRequest.load(rawXacmlReq); + reqType = PDPServices.DECISION_RAW_XACML_JSON_TYPE; + } else { + pdpRequest = DOMRequest.load(StringEscapeUtils.unescapeXml(rawXacmlReq)); + pdpServices.setRequestFormat(PDPServices.DECISION_RAW_XACML_XML_TYPE); + } + + status = HttpStatus.OK; + pdpResponse = pdpServices.callPdp(pdpRequest, getRequestUuid()); + + String outgoingResponseString = null; + if (PDPServices.DECISION_RAW_XACML_JSON_TYPE.equalsIgnoreCase(reqType)) { + outgoingResponseString = JSONResponse.toString(pdpResponse, false); + } else { + outgoingResponseString = DOMResponse.toString(pdpResponse, false); + if (!StringUtils.isBlank(outgoingResponseString)) { + outgoingResponseString = StringEscapeUtils.escapeXml10(outgoingResponseString); + } + } + + LOGGER.info("processRawXacmlReq - Request - \n" + rawXacmlReq + "\n Reponse:\n" + outgoingResponseString); + StdDecisionResponse decisionResp = new StdDecisionResponse(); + if (!StringUtils.isBlank(outgoingResponseString) + && outgoingResponseString.contains(Decision.PERMIT.toString())) { + decisionResp.setDecision(PolicyDecision.PERMIT); + } else if (!StringUtils.isBlank(outgoingResponseString) + && outgoingResponseString.contains(Decision.DENY.toString())) { + decisionResp.setDecision(PolicyDecision.DENY); + } else { + decisionResp.setDecision(PolicyDecision.ERROR); + } + decisionResp.setDetails(outgoingResponseString); + this.decisionResponse = decisionResp; + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyDecisionException(e); + } + } + + private DecisionResponse decisionResult(Collection generateRequest) { StdDecisionResponse policyDecision = new StdDecisionResponse(); if (generateRequest == null) { return policyDecision; @@ -116,64 +204,70 @@ public class GetDecisionService { return policyDecision; } - private JsonObject getModel() throws PolicyDecisionException{ + private JsonObject getModel() throws PolicyDecisionException { JsonArrayBuilder resourceArray = Json.createArrayBuilder(); - for (Entry key : decisionAttributes.entrySet()) { - if (key.getKey().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; - LOGGER.error(message); - throw new PolicyDecisionException(message); + for (Entry entry : decisionAttributes.entrySet()) { + if (entry.getKey().isEmpty()) { + String msg = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(msg); + throw new PolicyDecisionException(msg); } + if (PDPServices.DECISION_MS_NAMING_TYPE.equalsIgnoreCase(entry.getKey().trim())) { + // this is used for only Model execution and not for identifying + // policy. It is input data for MS Naming model execution and + // will be parsed in the naming service. Skip here. + this.setRequestType(PDPServices.DECISION_MS_NAMING_TYPE); + continue; + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); - if (key.getValue().matches("[0-9]+")) { - - if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { - - resourceBuilder.add("Value", key.getValue()); - - } else { - - int val = Integer.parseInt(key.getValue()); + if (entry.getValue().matches("[0-9]+")) { + + if ((entry.getKey().equals("ErrorCode")) || (entry.getKey().equals("WorkStep"))) { + + resourceBuilder.add("Value", entry.getValue()); + + } else { + + int val = Integer.parseInt(entry.getValue()); resourceBuilder.add("Value", val); - - } - + + } + } else { - resourceBuilder.add("Value", key.getValue()); + resourceBuilder.add("Value", entry.getValue()); } - resourceBuilder.add("AttributeId", key.getKey()); + resourceBuilder.add("AttributeId", entry.getKey()); resourceArray.add(resourceBuilder); } - return Json.createObjectBuilder() - .add("Request", Json.createObjectBuilder() - .add("AccessSubject", Json.createObjectBuilder() - .add("Attribute", Json.createObjectBuilder() - .add("Value", onapComponentName) - .add("AttributeId", "ONAPName"))) - .add("Resource", Json.createObjectBuilder() - .add("Attribute", resourceArray)) - .add("Action", Json.createObjectBuilder() - .add("Attribute", Json.createObjectBuilder() - .add("Value", "DECIDE") - .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) + return Json.createObjectBuilder().add("Request", Json.createObjectBuilder().add("AccessSubject", + Json.createObjectBuilder().add("Attribute", + Json.createObjectBuilder().add("Value", onapComponentName).add("AttributeId", "ONAPName"))) + .add("Resource", Json.createObjectBuilder().add("Attribute", resourceArray)) + .add("Action", Json.createObjectBuilder().add("Attribute", Json.createObjectBuilder() + .add("Value", "DECIDE").add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) .build(); } private boolean getValidation() { - if(decisionRequestParameters==null){ + if (decisionRequestParameters == null) { message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Paramaters"; - return false; + return false; } onapComponentName = decisionRequestParameters.getOnapName(); decisionAttributes = decisionRequestParameters.getDecisionAttributes(); - if (onapComponentName == null || onapComponentName.isEmpty()) { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No onapComponentName given : " + onapComponentName; - return false; - } if (decisionAttributes == null || decisionAttributes.isEmpty()) { message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Attributes Given. "; return false; } + if (decisionAttributes.containsKey(PDPServices.DECISION_RAW_XACML)) { + // onapName not mandatory for raw requests + requestType = PDPServices.DECISION_RAW_XACML; + } else if (onapComponentName == null || onapComponentName.isEmpty()) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No onapComponentName given : " + onapComponentName; + return false; + } + return true; } @@ -185,5 +279,20 @@ public class GetDecisionService { return status; } -} + public UUID getRequestUuid() { + return requestUuid; + } + public void setRequestUuid(UUID requestId) { + this.requestUuid = requestId; + } + + public String getRequestType() { + return requestType; + } + + public void setRequestType(String requestType) { + this.requestType = requestType; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java index 6dae064a7..e61bbd3aa 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,21 +18,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pdp.rest.api.services; +import com.att.research.xacml.api.Advice; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Obligation; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPException; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacml.std.dom.DOMResponse; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Strings; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; - import javax.json.Json; import javax.json.JsonReader; import javax.xml.XMLConstants; @@ -43,7 +60,6 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; - import org.apache.commons.io.IOUtils; import org.onap.policy.api.PolicyConfigStatus; import org.onap.policy.api.PolicyDecision; @@ -59,42 +75,56 @@ import org.onap.policy.std.Matches; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.w3c.dom.Document; -import com.att.research.xacml.api.Advice; -import com.att.research.xacml.api.AttributeAssignment; -import com.att.research.xacml.api.Decision; -import com.att.research.xacml.api.Obligation; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.Result; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPException; -import com.att.research.xacml.std.json.JSONRequest; -import com.att.research.xacml.std.json.JSONResponse; -import com.att.research.xacml.util.XACMLProperties; public class PDPServices { private static final Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName()); - // Change the default Priority value here. + // Change the default Priority value here. private static final int DEFAULT_PRIORITY = 9999; private boolean unique = false; private Boolean decide = false; - private Request rainydayRequest = null; - - public Collection generateRequest(String jsonString, UUID requestID, boolean unique, boolean decide) throws PolicyException{ + private String requestType = null; + private String requestFormat = DECISION_RAW_XACML_JSON_TYPE; + private List policyList = null; + public static final String RAINYDAY_TYPE = "BB_ID"; + public static final String DECISION_MS_NAMING_TYPE = "main-resource-keys"; + public static final String DECISION_RAW_XACML = "raw-xacml-request"; + public static final String DECISION_RAW_XACML_TYPE = "raw-xacml-type"; + public static final String DECISION_RAW_XACML_XML_TYPE = "XML"; + public static final String DECISION_RAW_XACML_JSON_TYPE = "JSON"; + + /** + * Generate request. + * + * @param reqStr the json string + * @param requestId the request id + * @param unique the unique + * @param decide the decide + * @return the collection + * @throws PolicyException the policy exception + */ + public Collection generateRequest(String reqStr, UUID requestId, boolean unique, boolean decide) + throws PolicyException { this.unique = unique; this.decide = decide; Collection results = null; Response response = null; // Create Request. We need XACML API here. try { - Request request = JSONRequest.load(jsonString); - // Assign a rainy day treatment request to parse the decided treatment - if (jsonString.contains("BB_ID")) { - rainydayRequest = request; + Request request = null; + if (DECISION_RAW_XACML_JSON_TYPE.equals(requestFormat)) { + request = JSONRequest.load(reqStr); + LOGGER.info("--- Generating Request: ---" + requestId + "\n" + JSONRequest.toString(request)); + } else { + request = DOMRequest.load(reqStr); + LOGGER.info("--- Generating Request: ---" + requestId + "\n" + reqStr); } + // Call the PDP - LOGGER.info("--- Generating Request: ---\n" + JSONRequest.toString(request)); - response = callPDP(request, requestID); + response = callPdp(request, requestId); + if (response == null) { + response = callPdp(request, requestId); + } + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); PDPResponse pdpResponse = new PDPResponse(); @@ -105,8 +135,14 @@ public class PDPServices { results.add(pdpResponse); throw new PolicyException(e); } + if (response != null) { results = checkResponse(response); + if (policyList != null) { + for (String policy : policyList) { + XACMLPdpServlet.monitor.policyCountAdd(policy, 1); + } + } } else { LOGGER.info("No Response Received from PDP"); PDPResponse pdpResponse = new PDPResponse(); @@ -119,59 +155,39 @@ public class PDPServices { return results; } - private Collection checkResponse(Response response) throws PolicyException{ + private Collection checkResponse(Response response) throws PolicyException { String pdpConfigLocation = null; Collection combinedResult = new HashSet<>(); int priority = DEFAULT_PRIORITY; Map uniqueResult = new HashMap<>(); for (Result result : response.getResults()) { - if (!result.getDecision().equals(Decision.PERMIT)) { - LOGGER.info("Decision not a Permit. " + result.getDecision().toString()); - PDPResponse pdpResponse = new PDPResponse(); - if (decide) { - String indeterminatePropValue = XACMLProperties.getProperty("decision.indeterminate.response"); - if(result.getDecision().equals(Decision.INDETERMINATE)&& indeterminatePropValue != null){ - if("PERMIT".equalsIgnoreCase(indeterminatePropValue)){ - pdpResponse.setDecision(PolicyDecision.PERMIT); - }else{ - pdpResponse.setDecision(PolicyDecision.DENY); - } - }else{ - pdpResponse.setDecision(PolicyDecision.DENY); - } - for(Advice advice: result.getAssociatedAdvice()){ - for(AttributeAssignment attribute: advice.getAttributeAssignments()){ - pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString()); - break; - } - } + // Process the decision policies. We only return one back for + // decision + if (decide) { + PDPResponse pdpResponse = processDecisionResult(result); + if (pdpResponse != null) { combinedResult.add(pdpResponse); - return combinedResult; + } else { + LOGGER.info("processDecisionResult returned null"); } - pdpResponse.setStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",PolicyResponseStatus.NO_ACTION_REQUIRED,PolicyConfigStatus.CONFIG_NOT_FOUND); + return combinedResult; + } + if (!result.getDecision().equals(Decision.PERMIT)) { + LOGGER.info("Decision not a Permit. " + result.getDecision().toString()); + PDPResponse pdpResponse = new PDPResponse(); + pdpResponse.setStatus( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.", + PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_NOT_FOUND); combinedResult.add(pdpResponse); return combinedResult; } else { - if (decide) { - // check for Decision for decision based calls. - PDPResponse pdpResponse = new PDPResponse(); - pdpResponse.setDecision(PolicyDecision.PERMIT); - - //if this is a Rainy Day treatment decision we need to get the selected treatment - if(rainydayRequest!=null){ - pdpResponse.setDetails(getRainyDayTreatment(result)); - } else { - pdpResponse.setDetails("Decision Permit. OK!"); - } - combinedResult.add(pdpResponse); - return combinedResult; - } if (!result.getAssociatedAdvice().isEmpty()) { - // Configurations should be in advice. + // Configurations should be in advice. // Also PDP took actions could be here. for (Advice advice : result.getAssociatedAdvice()) { - int config = 0, uri = 0; - String configURL = null; + int config = 0; + int uri = 0; + String configUrl = null; String policyName = null; String policyVersion = null; Matches match = new Matches(); @@ -182,48 +198,60 @@ public class PDPServices { PDPResponse pdpResponse = new PDPResponse(); Map adviseAttributes = new HashMap<>(); for (AttributeAssignment attribute : advice.getAttributeAssignments()) { - adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + adviseAttributes.put(attribute.getAttributeId().stringValue(), + attribute.getAttributeValue().getValue().toString()); if ("CONFIGURATION".equalsIgnoreCase(attribute.getAttributeValue().getValue().toString())) { config++; } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) { uri++; if (uri == 1) { - configURL = attribute.getAttributeValue().getValue().toString(); - pdpConfigLocation = configURL.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)); + configUrl = attribute.getAttributeValue().getValue().toString(); + pdpConfigLocation = configUrl.replace("$URL", + XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)); } else { if (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) { - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy"); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Error having multiple URI in the Policy"); } } } else if ("PolicyName".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { policyName = attribute.getAttributeValue().getValue().toString(); + policyList.add(policyName); } else if ("VersionNumber".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { policyVersion = attribute.getAttributeValue().getValue().toString(); - } else if ("Priority".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ - try{ + } else if ("Priority".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { + try { priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString()); - } catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value",e); + } catch (Exception e) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + + "Unable to Parse Integer for Priority. Setting to default value", + e); priority = DEFAULT_PRIORITY; } } else if (attribute.getAttributeId().stringValue().startsWith("matching")) { - matchingConditions.put(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); - if ("ONAPName".equals(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""))) { + matchingConditions.put( + attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""), + attribute.getAttributeValue().getValue().toString()); + if ("ONAPName".equals( + attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""))) { match.setOnapName(attribute.getAttributeValue().getValue().toString()); - } else if ("ConfigName".equals(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""))) { + matchingConditions.put("ECOMPName", + attribute.getAttributeValue().getValue().toString()); + } else if ("ConfigName".equals( + attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""))) { match.setConfigName(attribute.getAttributeValue().getValue().toString()); } else { - configAttributes.put(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); + configAttributes.put( + attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""), + attribute.getAttributeValue().getValue().toString()); } } else if (attribute.getAttributeId().stringValue().startsWith("key:")) { - responseAttributes.put(attribute.getAttributeId().stringValue().replaceFirst("(key).", ""), + responseAttributes.put( + attribute.getAttributeId().stringValue().replaceFirst("(key).", ""), attribute.getAttributeValue().getValue().toString()); } else if (attribute.getAttributeId().stringValue().startsWith("controller:")) { - responseAttributes.put("$"+ attribute.getAttributeId().stringValue(), + responseAttributes.put("$" + attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); } else if (attribute.getAttributeId().stringValue().startsWith("dependencies:")) { responseAttributes.put("$dependency$", @@ -236,41 +264,42 @@ public class PDPServices { if ((config == 1) && (uri == 1)) { // If there is a configuration. try { - LOGGER.debug("Configuration Call to : " + configURL); + LOGGER.debug("Configuration Call to : " + configUrl); pdpResponse = configCall(pdpConfigLocation); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ e); - pdpResponse.setStatus("Error in Calling the Configuration URL "+ e, - PolicyResponseStatus.NO_ACTION_REQUIRED, - PolicyConfigStatus.CONFIG_NOT_FOUND); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + pdpResponse.setStatus("Error in Calling the Configuration URL " + e, + PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_NOT_FOUND); } pdpResponse.setPolicyName(policyName); pdpResponse.setPolicyVersion(policyVersion); pdpResponse.setMatchingConditions(matchingConditions); pdpResponse.setResponseAttributes(responseAttributes); - if(!unique){ + if (!unique) { combinedResult.add(pdpResponse); - }else{ - if(!uniqueResult.isEmpty()){ - if(uniqueResult.containsKey(priority)){ - // Not any more unique, check the matching conditions size + } else { + if (!uniqueResult.isEmpty()) { + if (uniqueResult.containsKey(priority)) { + // Not any more unique, check the + // matching conditions size int oldSize = uniqueResult.get(priority).getMatchingConditions().size(); int newSize = matchingConditions.size(); - if(oldSize < newSize){ + if (oldSize < newSize) { uniqueResult.put(priority, pdpResponse); - }else if(oldSize == newSize){ + } else if (oldSize == newSize) { pdpResponse = new PDPResponse(); - pdpResponse.setStatus("Two/more Policies have Same Priority and matching conditions, Please correct your policies.", + pdpResponse.setStatus( + "Two/more Policies have Same Priority and matching conditions, Please correct your policies.", PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_NOT_FOUND); combinedResult.add(pdpResponse); unique = false; return combinedResult; } - }else{ + } else { uniqueResult.put(priority, pdpResponse); } - }else{ + } else { uniqueResult.put(priority, pdpResponse); } } @@ -303,11 +332,11 @@ public class PDPServices { } } } - if(unique){ - // Select Unique policy. + if (unique) { + // Select Unique policy. int minNum = DEFAULT_PRIORITY; - for(int num: uniqueResult.keySet()){ - if(num < minNum){ + for (int num : uniqueResult.keySet()) { + if (num < minNum) { minNum = num; } } @@ -315,19 +344,122 @@ public class PDPServices { // Turn off Unique unique = false; } - + return combinedResult; } - + + /** + * Process Decision Result. + * + * @param result input from Response. + * @return pdpResposne based on result. + */ + private PDPResponse processDecisionResult(Result result) { + PDPResponse pdpResponse = new PDPResponse(); + pdpResponse.setDecision(PolicyDecision.DENY); + + if (!result.getDecision().equals(Decision.PERMIT)) { + LOGGER.info("processDecisionResult: Decision not a Permit. " + result.getDecision().toString()); + String indeterminatePropValue = XACMLProperties.getProperty("decision.indeterminate.response"); + if (result.getDecision().equals(Decision.INDETERMINATE) && indeterminatePropValue != null) { + if ("PERMIT".equalsIgnoreCase(indeterminatePropValue)) { + pdpResponse.setDecision(PolicyDecision.PERMIT); + } else { + pdpResponse.setDecision(PolicyDecision.DENY); + } + } else { + pdpResponse.setDecision(PolicyDecision.DENY); + } + for (Advice advice : result.getAssociatedAdvice()) { + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString()); + break; + } + } + pdpResponse.setStatus( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.", + PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_NOT_FOUND); + } else { + checkDecision(pdpResponse, result); + } + return pdpResponse; + } + + + /** + * Check for Decision for decision based calls. + * + * @param pdpResponseInput pdpResponse. + * @param result result. + * @return pdpResponse. + */ + private PDPResponse checkDecision(PDPResponse pdpResponseInput, Result result) { + PDPResponse pdpResponse = pdpResponseInput; + // check for Decision for decision based calls. + pdpResponse.setDecision(PolicyDecision.PERMIT); + + // if this is a Rainy Day treatment decision we need to get + // the selected treatment + if (!Strings.isNullOrEmpty(requestType) && RAINYDAY_TYPE.equals(requestType)) { + pdpResponse.setDetails(getRainyDayTreatment(result)); + } else if (!Strings.isNullOrEmpty(requestType) && DECISION_MS_NAMING_TYPE.equals(requestType)) { + boolean configRetrieved = false; + for (Advice advice : result.getAssociatedAdvice()) { + configRetrieved = checkConfig(advice, configRetrieved, pdpResponse); + } + if (!configRetrieved) { + LOGGER.error(" Failed to retrieve Config data for " + DECISION_MS_NAMING_TYPE); + pdpResponse.setDetails("Error in retrieving Config Data"); + } + + } else { + pdpResponse.setDetails("Decision Permit. OK!"); + } + return pdpResponse; + } + + /** + * Check if there is a configuration. + * + * @param advice advice. + * @param configRetrieved boolean. + * @param pdpResponse pdpResposneInput. + * @return pdpResponse. + */ + private boolean checkConfig(Advice advice, boolean configRetrieved, PDPResponse pdpResponse) { + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) { + String configUrl = attribute.getAttributeValue().getValue().toString(); + String pdpConfigLocation = + configUrl.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)); + // If there is a configuration. + try { + LOGGER.debug("processDecisionResult: Configuration Call to : " + configUrl); + pdpResponse = configCall(pdpConfigLocation); + pdpResponse.setDecision(PolicyDecision.PERMIT); + pdpResponse.setDetails(pdpResponse.getConfig()); + configRetrieved = true; + break; + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + LOGGER.error(" Failed to retrieve Config data for " + configUrl); + pdpResponse.setDetails("Error in retrieving Config Data from the Configuration URL " + configUrl); + } + } + } + return configRetrieved; + } + private String getRainyDayTreatment(Result result) { String treatment = null; - if (rainydayRequest!=null&& !result.getAssociatedAdvice().isEmpty()) { + if (result != null && !result.getAssociatedAdvice().isEmpty()) { // Get the desired treatment for requested errorCode from the Advice for (Advice advice : result.getAssociatedAdvice()) { Map adviseAttributes = new HashMap<>(); for (AttributeAssignment attribute : advice.getAttributeAssignments()) { - adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); - if ("treatment".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ + adviseAttributes.put(attribute.getAttributeId().stringValue(), + attribute.getAttributeValue().getValue().toString()); + if ("treatment".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { treatment = attribute.getAttributeValue().getValue().toString(); } } @@ -336,16 +468,15 @@ public class PDPServices { return treatment; } - private PDPResponse configCall(String pdpConfigLocation) throws PDPException, IOException{ + private PDPResponse configCall(String pdpConfigLocation) throws PDPException, IOException { PDPResponse pdpResponse = new PDPResponse(); - if(pdpConfigLocation.contains("/")){ + if (pdpConfigLocation.contains("/")) { pdpConfigLocation = pdpConfigLocation.replace("/", File.separator); } - - try(InputStream inputStream = new FileInputStream(new File(pdpConfigLocation))) { + try (InputStream inputStream = new FileInputStream(new File(pdpConfigLocation))) { if (pdpConfigLocation.endsWith("json")) { pdpResponse.setType(PolicyType.JSON); - try(JsonReader jsonReader = Json.createReader(inputStream);) { + try (JsonReader jsonReader = Json.createReader(inputStream)) { pdpResponse.setConfig(jsonReader.readObject().toString()); } } else if (pdpConfigLocation.endsWith("xml")) { @@ -366,15 +497,16 @@ public class PDPServices { transformer.transform(domSource, result); pdpResponse.setConfig(writer.toString()); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e); - throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e); + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); + throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the XML config", + e); } } else if (pdpConfigLocation.endsWith("properties")) { pdpResponse.setType(PolicyType.PROPERTIES); Properties configProp = new Properties(); configProp.load(inputStream); Map propVal = new HashMap<>(); - for(String name: configProp.stringPropertyNames()) { + for (String name : configProp.stringPropertyNames()) { propVal.put(name, configProp.getProperty(name)); } pdpResponse.setProperty(propVal); @@ -387,11 +519,11 @@ public class PDPServices { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found"); pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found."); + inputStream.close(); return pdpResponse; } LOGGER.info("config Retrieved " + pdpConfigLocation); - pdpResponse.setStatus("Config Retrieved! ", - PolicyResponseStatus.NO_ACTION_REQUIRED, + pdpResponse.setStatus("Config Retrieved! ", PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_RETRIEVED); return pdpResponse; } catch (FileNotFoundException e) { @@ -399,35 +531,104 @@ public class PDPServices { throw new PDPException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e); } catch (IOException | ParserConfigurationException e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW + - "Cannot open a connection to the configURL", e); + throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Cannot open a connection to the configURL", + e); } } - private Response callPDP(Request request, UUID requestID){ + /** + * Call pdp. + * + * @param request the request + * @param requestIdParam the request id param + * @return the response + */ + public Response callPdp(Request request, UUID requestIdParam) { + policyList = new ArrayList<>(); Response response = null; // Get the PDPEngine - if (requestID == null) { - requestID = UUID.randomUUID(); - LOGGER.debug("No request ID provided, sending generated ID: " + requestID.toString()); + if (requestIdParam == null) { + requestIdParam = UUID.randomUUID(); + LOGGER.debug("No request ID provided, sending generated ID: " + requestIdParam.toString()); } else { - LOGGER.debug("Using provided request ID: " + requestID.toString()); + LOGGER.debug("Using provided request ID: " + requestIdParam.toString()); } PDPEngine pdpEngine = XACMLPdpServlet.getPDPEngine(); if (pdpEngine == null) { String message = "PDPEngine not loaded."; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message + "\n RequestId : " + requestIdParam); return response; } + XACMLPdpServlet.monitor.pdpEvaluationAttempts(); // call the PDPEngine to decide and give the response on the Request. + long timeStart; + long timeEnd; try { - response = pdpEngine.decide(request); - LOGGER.info("Response from the PDP is: \n" + JSONResponse.toString(response)); + synchronized (XACMLPdpServlet.getPDPEngineLock()) { + timeStart = System.currentTimeMillis(); + response = pdpEngine.decide(request); + timeEnd = System.currentTimeMillis(); + } + + String outgoingResponseString = null; + if (DECISION_RAW_XACML_JSON_TYPE.equalsIgnoreCase(requestFormat)) { + outgoingResponseString = JSONResponse.toString(response); + LOGGER.info("Response from the PDP is : \n" + JSONResponse.toString(response, true) + "\n RequestId : " + + requestIdParam + " pdpEngine : " + pdpEngine); + } else { + outgoingResponseString = DOMResponse.toString(response); + LOGGER.info("Response from the PDP is : \n" + DOMResponse.toString(response, true) + "\n RequestId : " + + requestIdParam + " pdpEngine : " + pdpEngine); + } + + XACMLPdpServlet.monitor.computeLatency(timeEnd - timeStart); + + // adding the jmx values for NA, Permit and Deny + // + if (outgoingResponseString.contains("NotApplicable") + || outgoingResponseString.contains("Decision not a Permit")) { + XACMLPdpServlet.monitor.pdpEvaluationNA(); + } + + if (outgoingResponseString.contains("Permit") + && !outgoingResponseString.contains("Decision not a Permit")) { + XACMLPdpServlet.monitor.pdpEvaluationPermit(); + } + + if (outgoingResponseString.contains("Deny")) { + XACMLPdpServlet.monitor.pdpEvaluationDeny(); + } } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e + "\n RequestId : " + requestIdParam); return null; } return response; } + public String getRequestType() { + return requestType; + } + + public void setRequestType(String requestType) { + this.requestType = requestType; + } + + /** + * Returns the requestFormat. + * + * @return the requestFormat. + */ + public String getRequestFormat() { + return requestFormat; + } + + /** + * Set the Request Format. + * + * @param requestMode to set requestFormat. + */ + public void setRequestFormat(String requestMode) { + this.requestFormat = requestMode; + } + } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java index dc1819ff0..edadf53de 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java @@ -23,22 +23,19 @@ package org.onap.policy.rest.adapter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import javax.persistence.EntityManagerFactory; - import org.onap.policy.rest.jpa.OnapName; public class PolicyRestAdapter { /* - * + * * Note : Make Sure if any variables are added in PolicyRestAdapter.java, add them to PolicyElasticData.java file - * - * - * */ - + * + * + */ - //Common + // Common private Object data; private String policyName = null; private String configBodyData = null; @@ -77,7 +74,7 @@ public class PolicyRestAdapter { private String clWarning = null; private String newCLName = null; private String existingCLName = null; - //Used by GUI + // Used by GUI private OnapName onapNameField; private Object jsonBodyData; private String dirPath; @@ -87,30 +84,30 @@ public class PolicyRestAdapter { private List ruleAlgorithmschoices; private Map serviceTypePolicyName; - + private Map verticaMetrics; private Map description; private Map attributeFields; - - //ClosedLoop + + // ClosedLoop private String clearTimeOut; private String trapMaxAge; private String verificationclearTimeOut; - private Map dynamicLayoutMap; + private Map dynamicLayoutMap; private ClosedLoopFaultTrapDatas trapDatas; private ClosedLoopFaultTrapDatas faultDatas; - //FireWall + // FireWall private String fwPolicyType; private List fwattributes; private String parentForChild; private String securityZone; - //Action & Decision + // Action & Decision private String ruleCombiningAlgId = null; - private Map dynamicFieldConfigAttributes; - private Map dynamicSettingsMap; - private Map dropDownMap; + private Map dynamicFieldConfigAttributes; + private Map dynamicSettingsMap; + private Map dropDownMap; private String actionPerformer = null; private String actionAttribute = null; private List dynamicRuleAlgorithmLabels; @@ -130,38 +127,47 @@ public class PolicyRestAdapter { private List blackListEntries; private List appendBlackListEntries; private String blackListEntryType; + private String rawXacmlPolicy; + + public String getRawXacmlPolicy() { + return rawXacmlPolicy; + } - //Rainy Day Decision + public void setRawXacmlPolicy(String rawXacmlPolicy) { + this.rawXacmlPolicy = rawXacmlPolicy; + } + + // Rainy Day Decision private RainyDayParams rainyday; - private Map rainydayMap; + private Map rainydayMap; private List errorCodeList; private List treatmentList; - //MicroSerice + // MicroSerice private String serviceType = null; private String uuid = null; private String location = null; private String priority = null; private String msLocation = null; private Object policyJSON = null; - - //BRMS Policies + + // BRMS Policies private String ruleName; - private Map brmsParamBody=null; + private Map brmsParamBody = null; private String brmsController = null; private List brmsDependency = null; - private LinkedHashMap ruleData; - private LinkedHashMap ruleListData; - private Map drlRuleAndUIParams=null; - - //Safe Policy + private LinkedHashMap ruleData; + private LinkedHashMap ruleListData; + private Map drlRuleAndUIParams = null; + + // Safe Policy private String policyScope; private String providerComboBox = null; private String riskType; private String riskLevel; private String guard = null; private String ttlDate; - private Map matching; + private Map matching; private List triggerSignatures; private List symptomSignatures; @@ -169,35 +175,43 @@ public class PolicyRestAdapter { private String policyStatus; private String gocServerScope; private String supressionType; - - + public List getTriggerSignatures() { return triggerSignatures; } + public void setTriggerSignatures(List triggerSignatures) { this.triggerSignatures = triggerSignatures; } + public List getSymptomSignatures() { return symptomSignatures; } + public void setSymptomSignatures(List symptomSignatures) { this.symptomSignatures = symptomSignatures; } + public String getLogicalConnector() { return logicalConnector; } + public void setLogicalConnector(String logicalConnector) { this.logicalConnector = logicalConnector; } + public String getPolicyStatus() { return policyStatus; } + public void setPolicyStatus(String policyStatus) { this.policyStatus = policyStatus; } + public String getGocServerScope() { return gocServerScope; } + public void setGocServerScope(String gocServerScope) { this.gocServerScope = gocServerScope; } @@ -205,692 +219,886 @@ public class PolicyRestAdapter { public String getSupressionType() { return supressionType; } + public void setSupressionType(String supressionType) { this.supressionType = supressionType; } /********************************************************************************/ - - public String getComboPolicyType() { return comboPolicyType; } + public void setComboPolicyType(String comboPolicyType) { this.comboPolicyType = comboPolicyType; } + public String getGitPath() { return gitPath; } + public void setGitPath(String gitPath) { this.gitPath = gitPath; } + public String getOldPolicyFileName() { return oldPolicyFileName; } + public void setOldPolicyFileName(String oldPolicyFileName) { this.oldPolicyFileName = oldPolicyFileName; } + public String getDomainDir() { return domain; } + public void setDomainDir(String domain) { this.domain = domain; } + public Integer getHighestVersion() { return highestVersion; } + public void setHighestVersion(Integer highestVersion) { this.highestVersion = highestVersion; } + public Object getData() { return data; } + public void setData(Object data) { this.data = data; } + public String getPolicyName() { return policyName; } + public void setPolicyName(String policyName) { this.policyName = policyName; } + public String getConfigBodyData() { return configBodyData; } + public void setConfigBodyData(String configBodyData) { this.configBodyData = configBodyData; } + public String getConfigType() { return configType; } + public void setConfigType(String configType) { this.configType = configType; } + public String getPolicyID() { return policyID; } + public void setPolicyID(String policyID) { this.policyID = policyID; } + public String getPolicyType() { return policyType; } + public void setPolicyType(String policyType) { this.policyType = policyType; } + public String getPolicyDescription() { return policyDescription; } + public void setPolicyDescription(String policyDescription) { this.policyDescription = policyDescription; } + public String getOnapName() { return onapName; } + public void setOnapName(String onapName) { this.onapName = onapName; } + public String getConfigName() { return configName; } + public void setConfigName(String configName) { this.configName = configName; } + public String getRuleID() { return ruleID; } + public void setRuleID(String ruleID) { this.ruleID = ruleID; } + public String getRuleCombiningAlgId() { return ruleCombiningAlgId; } + public void setRuleCombiningAlgId(String ruleCombiningAlgId) { this.ruleCombiningAlgId = ruleCombiningAlgId; } - public Map getDynamicFieldConfigAttributes() { + + public Map getDynamicFieldConfigAttributes() { return dynamicFieldConfigAttributes; } - public void setDynamicFieldConfigAttributes( - Map dynamicFieldConfigAttributes) { + + public void setDynamicFieldConfigAttributes(Map dynamicFieldConfigAttributes) { this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; } + public String getParentPath() { return parentPath; } + public void setParentPath(String parentPath) { this.parentPath = parentPath; } + public boolean isEditPolicy() { return isEditPolicy; } + public void setEditPolicy(boolean isEditPolicy) { this.isEditPolicy = isEditPolicy; } + public boolean isViewPolicy() { return isViewPolicy; } + public void setViewPolicy(boolean isViewPolicy) { this.isViewPolicy = isViewPolicy; } + public Object getPolicyData() { return policyData; } + public void setPolicyData(Object policyData) { this.policyData = policyData; } + public boolean isReadOnly() { return readOnly; } + public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } + public boolean isValidData() { return isValidData; } + public void setValidData(boolean isValidData) { this.isValidData = isValidData; } + public String getAdminNotification() { return adminNotification; } + public void setAdminNotification(String adminNotification) { this.adminNotification = adminNotification; } + public String getConfigHome() { return configHome; } + public void setConfigHome(String configHome) { this.configHome = configHome; } + public String getConfigUrl() { return configUrl; } + public void setConfigUrl(String configUrl) { this.configUrl = configUrl; } + public String getFinalPolicyPath() { return finalPolicyPath; } + public void setFinalPolicyPath(String finalPolicyPath) { this.finalPolicyPath = finalPolicyPath; } + public String getVersion() { return version; } + public void setVersion(String version) { this.version = version; } + public String getJsonBody() { return jsonBody; } + public void setJsonBody(String jsonBody) { this.jsonBody = jsonBody; } + public String getPrevJsonBody() { return prevJsonBody; } + public void setPrevJsonBody(String prevJsonBody) { this.prevJsonBody = prevJsonBody; } + public String getApiflag() { return apiflag; } + public void setApiflag(String apiflag) { this.apiflag = apiflag; } + /** * @return the actionPerformer */ public String getActionPerformer() { return actionPerformer; } + /** * @param actionPerformer the actionPerformer to set */ public void setActionPerformer(String actionPerformer) { this.actionPerformer = actionPerformer; } + /** * @return the actionAttribute */ public String getActionAttribute() { return actionAttribute; } + /** * @param actionAttribute the actionAttribute to set */ public void setActionAttribute(String actionAttribute) { this.actionAttribute = actionAttribute; } + /** * @return the dynamicRuleAlgorithmLabels */ public List getDynamicRuleAlgorithmLabels() { return dynamicRuleAlgorithmLabels; } + /** * @param dynamicRuleAlgorithmLabels the dynamicRuleAlgorithmLabels to set */ - public void setDynamicRuleAlgorithmLabels( - List dynamicRuleAlgorithmLabels) { + public void setDynamicRuleAlgorithmLabels(List dynamicRuleAlgorithmLabels) { this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; } + /** * @return the dynamicRuleAlgorithmCombo */ public List getDynamicRuleAlgorithmCombo() { return dynamicRuleAlgorithmCombo; } + /** * @param dynamicRuleAlgorithmCombo the dynamicRuleAlgorithmCombo to set */ public void setDynamicRuleAlgorithmCombo(List dynamicRuleAlgorithmCombo) { this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; } + /** * @return the dynamicRuleAlgorithmField1 */ public List getDynamicRuleAlgorithmField1() { return dynamicRuleAlgorithmField1; } + /** * @param dynamicRuleAlgorithmField1 the dynamicRuleAlgorithmField1 to set */ - public void setDynamicRuleAlgorithmField1( - List dynamicRuleAlgorithmField1) { + public void setDynamicRuleAlgorithmField1(List dynamicRuleAlgorithmField1) { this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; } + /** * @return the dynamicRuleAlgorithmField2 */ public List getDynamicRuleAlgorithmField2() { return dynamicRuleAlgorithmField2; } + /** * @param dynamicRuleAlgorithmField2 the dynamicRuleAlgorithmField2 to set */ - public void setDynamicRuleAlgorithmField2( - List dynamicRuleAlgorithmField2) { + public void setDynamicRuleAlgorithmField2(List dynamicRuleAlgorithmField2) { this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; } - public Map getDropDownMap() { + + public Map getDropDownMap() { return dropDownMap; } - public void setDropDownMap(Map dropDownMap) { + + public void setDropDownMap(Map dropDownMap) { this.dropDownMap = dropDownMap; } - public Map getDynamicSettingsMap() { + public Map getDynamicSettingsMap() { return dynamicSettingsMap; } - public void setDynamicSettingsMap(Map dynamicSettingsMap) { + + public void setDynamicSettingsMap(Map dynamicSettingsMap) { this.dynamicSettingsMap = dynamicSettingsMap; } + public List getDynamicVariableList() { return dynamicVariableList; } + public void setDynamicVariableList(List dynamicVariableList) { this.dynamicVariableList = dynamicVariableList; } + public List getDataTypeList() { return dataTypeList; } + public void setDataTypeList(List dataTypeList) { this.dataTypeList = dataTypeList; } + public boolean isDraft() { return isDraft; } + public void setDraft(boolean isDraft) { this.isDraft = isDraft; } + public String getConfigPolicyType() { return configPolicyType; } + public void setConfigPolicyType(String configPolicyType) { this.configPolicyType = configPolicyType; } + public String getServiceType() { return serviceType; } + public void setServiceType(String serviceType) { this.serviceType = serviceType; } + public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } + public String getLocation() { return location; } + public void setLocation(String location) { this.location = location; } + public String getPriority() { return priority; } + public void setPriority(String priority) { this.priority = priority; } + public Map getBrmsParamBody() { return brmsParamBody; } + public void setBrmsParamBody(Map brmsParamBody) { this.brmsParamBody = brmsParamBody; } + public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } + public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } + /** * @return the policyExists */ public Boolean getPolicyExists() { return policyExists; } + /** * @param policyExists the policyExists to set */ public void setPolicyExists(Boolean policyExists) { this.policyExists = policyExists; } + public String getPolicyScope() { return policyScope; } public void setPolicyScope(String domainDir) { - this. policyScope=domainDir; + this.policyScope = domainDir; } + public String getProviderComboBox() { return providerComboBox; } + public void setProviderComboBox(String providerComboBox) { this.providerComboBox = providerComboBox; } + public String getRiskType() { return riskType; } + public void setRiskType(String riskType) { this.riskType = riskType; } + public String getGuard() { return guard; } + public void setGuard(String guard) { this.guard = guard; } + public String getRiskLevel() { return riskLevel; } + public void setRiskLevel(String riskLevel) { this.riskLevel = riskLevel; } + public String getTtlDate() { return ttlDate; } + public void setTtlDate(String ttlDate) { this.ttlDate = ttlDate; } + public String getBrmsController() { return brmsController; } + public void setBrmsController(String brmsController) { this.brmsController = brmsController; } + public List getBrmsDependency() { return brmsDependency; } + public void setBrmsDependency(List brmsDependency) { this.brmsDependency = brmsDependency; } + public Map getMatching() { return matching; } + public void setMatching(Map matching) { this.matching = matching; } + public String getUserId() { return userId; } + public void setUserId(String userId) { this.userId = userId; } + public String getNewFileName() { return newFileName; } + public void setNewFileName(String newFileName) { this.newFileName = newFileName; } + public OnapName getOnapNameField() { return onapNameField; } + public void setOnapNameField(OnapName onapNameField) { this.onapNameField = onapNameField; } + public Object getJsonBodyData() { return jsonBodyData; } + public void setJsonBodyData(Object jsonBodyData) { this.jsonBodyData = jsonBodyData; } + public String getDirPath() { return dirPath; } + public void setDirPath(String dirPath) { this.dirPath = dirPath; } + public String getConfigBodyPath() { return configBodyPath; } + public void setConfigBodyPath(String configBodyPath) { this.configBodyPath = configBodyPath; } + public List getAttributes() { return attributes; } + public void setAttributes(List attributes) { this.attributes = attributes; } + public List getSettings() { return settings; } + public void setSettings(List settings) { this.settings = settings; } + public List getRuleAlgorithmschoices() { return ruleAlgorithmschoices; } + public void setRuleAlgorithmschoices(List ruleAlgorithmschoices) { this.ruleAlgorithmschoices = ruleAlgorithmschoices; } + public Map getServiceTypePolicyName() { return serviceTypePolicyName; } + public void setServiceTypePolicyName(Map serviceTypePolicyName) { this.serviceTypePolicyName = serviceTypePolicyName; } + public Map getVerticaMetrics() { return verticaMetrics; } + public void setVerticaMetrics(Map verticaMetrics) { this.verticaMetrics = verticaMetrics; } + public Map getDescription() { return description; } + public void setDescription(LinkedHashMap description) { this.description = description; } + public Map getAttributeFields() { return attributeFields; } + public void setAttributeFields(LinkedHashMap attributeFields) { this.attributeFields = attributeFields; } + public String getClearTimeOut() { return clearTimeOut; } + public void setClearTimeOut(String clearTimeOut) { this.clearTimeOut = clearTimeOut; } + public String getTrapMaxAge() { return trapMaxAge; } + public void setTrapMaxAge(String trapMaxAge) { this.trapMaxAge = trapMaxAge; } + public String getVerificationclearTimeOut() { return verificationclearTimeOut; } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { this.verificationclearTimeOut = verificationclearTimeOut; } + public Map getDynamicLayoutMap() { return dynamicLayoutMap; } + public void setDynamicLayoutMap(Map dynamicLayoutMap) { this.dynamicLayoutMap = dynamicLayoutMap; } + public String getFwPolicyType() { return fwPolicyType; } + public void setFwPolicyType(String fwPolicyType) { this.fwPolicyType = fwPolicyType; } + public List getFwattributes() { return fwattributes; } + public void setFwattributes(List fwattributes) { this.fwattributes = fwattributes; } + public String getParentForChild() { return parentForChild; } + public void setParentForChild(String parentForChild) { this.parentForChild = parentForChild; } + public String getRuleName() { return ruleName; } + public void setRuleName(String ruleName) { this.ruleName = ruleName; } + public LinkedHashMap getRuleData() { return ruleData; } + public void setRuleData(LinkedHashMap ruleData) { this.ruleData = ruleData; } + public LinkedHashMap getRuleListData() { return ruleListData; } + public void setRuleListData(LinkedHashMap ruleListData) { this.ruleListData = ruleListData; } + public String getSecurityZone() { return securityZone; } + public void setSecurityZone(String securityZone) { this.securityZone = securityZone; } + public String getActionAttributeValue() { return actionAttributeValue; } + public void setActionAttributeValue(String actionAttributeValue) { this.actionAttributeValue = actionAttributeValue; } + public String getRuleProvider() { return ruleProvider; } + public void setRuleProvider(String ruleProvider) { this.ruleProvider = ruleProvider; } + public String getMsLocation() { return msLocation; } + public void setMsLocation(String msLocation) { this.msLocation = msLocation; } - public Map getDrlRuleAndUIParams() { + + public Map getDrlRuleAndUIParams() { return drlRuleAndUIParams; } - public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { + + public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { this.drlRuleAndUIParams = drlRuleAndUIParams; } + public String getActionBody() { return actionBody; } + public void setActionBody(String actionBody) { this.actionBody = actionBody; } + public String getActionDictHeader() { return actionDictHeader; } + public void setActionDictHeader(String actionDictHeader) { this.actionDictHeader = actionDictHeader; } + public String getActionDictType() { return actionDictType; } + public void setActionDictType(String actionDictType) { this.actionDictType = actionDictType; } + public String getActionDictUrl() { return actionDictUrl; } + public void setActionDictUrl(String actionDictUrl) { this.actionDictUrl = actionDictUrl; } + public String getActionDictMethod() { return actionDictMethod; } + public void setActionDictMethod(String actionDictMethod) { this.actionDictMethod = actionDictMethod; } + public String getClWarning() { return clWarning; } + public void setClWarning(String clWarning) { this.clWarning = clWarning; } + public String getNewCLName() { return newCLName; } + public void setNewCLName(String newCLName) { this.newCLName = newCLName; } + public String getExistingCLName() { return existingCLName; } + public void setExistingCLName(String existingCLName) { this.existingCLName = existingCLName; } + public YAMLParams getYamlparams() { return yamlparams; } + public void setYamlparams(YAMLParams yamlparams) { this.yamlparams = yamlparams; } + /** * @return the rainyday */ public RainyDayParams getRainyday() { return rainyday; } + /** * @param rainyday the rainyday to set */ public void setRainyday(RainyDayParams rainyday) { this.rainyday = rainyday; } + /** * @return the errorCodeList */ public List getErrorCodeList() { return errorCodeList; } + /** * @param errorCodeList the errorCodeList to set */ public void setErrorCodeList(List errorCodeList) { this.errorCodeList = errorCodeList; } + /** * @return the treatmentList */ public List getTreatmentList() { return treatmentList; } + /** * @param treatmentList the treatmentList to set */ public void setTreatmentList(List treatmentList) { this.treatmentList = treatmentList; } + /** * @return the rainydayMap */ - public Map getRainydayMap() { + public Map getRainydayMap() { return rainydayMap; } + /** * @param rainydayMap the rainydayMap to set */ - public void setRainydayMap(Map rainydayMap) { + public void setRainydayMap(Map rainydayMap) { this.rainydayMap = rainydayMap; } + /** * @return the policyJSON */ public Object getPolicyJSON() { return policyJSON; } + /** * @param policyJSON the policyJSON to set */ @@ -901,30 +1109,39 @@ public class PolicyRestAdapter { public ClosedLoopFaultTrapDatas getTrapDatas() { return trapDatas; } + public void setTrapDatas(ClosedLoopFaultTrapDatas trapDatas) { this.trapDatas = trapDatas; } + public ClosedLoopFaultTrapDatas getFaultDatas() { return faultDatas; } + public void setFaultDatas(ClosedLoopFaultTrapDatas faultDatas) { this.faultDatas = faultDatas; } + public List getAppendBlackListEntries() { return appendBlackListEntries; } + public void setAppendBlackListEntries(List appendBlackListEntries) { this.appendBlackListEntries = appendBlackListEntries; } + public List getBlackListEntries() { return blackListEntries; } + public void setBlackListEntries(List blackListEntries) { this.blackListEntries = blackListEntries; } + public String getBlackListEntryType() { return blackListEntryType; } + public void setBlackListEntryType(String blackListEntryType) { this.blackListEntryType = blackListEntryType; } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java index 185175907..2f752a0aa 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java @@ -81,7 +81,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { private String guard = null; private String riskLevel; private String ttlDate = null; - + private String rawXacmlPolicy = null; public StdPAPPolicy() { // @@ -155,7 +155,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { this.dictionaryType = stdPAPPolicyParams.getDictionaryType(); this.dictionary = stdPAPPolicyParams.getDictionary(); this.dictionaryFields = stdPAPPolicyParams.getDictionaryFields(); - + this.rawXacmlPolicy = stdPAPPolicyParams.getRawXacmlPolicy(); } @Override @@ -638,4 +638,12 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { public void setTreatments(Map treatments) { this.treatments = treatments; } + + public String getRawXacmlPolicy() { + return rawXacmlPolicy; + } + + public void setRawXacmlPolicy(String rawXacmlPolicy) { + this.rawXacmlPolicy = rawXacmlPolicy; + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java index 780decd88..1780dfc96 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java @@ -3,6 +3,7 @@ * ONAP-XACML * ================================================================================ * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,6 +72,7 @@ public class StdPAPPolicyParams { private String dictionaryType; private String dictionary; private String dictionaryFields; + private String rawXacmlPolicy = null; /** @@ -236,18 +238,10 @@ public class StdPAPPolicyParams { return uuid; } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getMsLocation() { return msLocation; } - public void setMsLocation(String msLocation) { - this.msLocation = msLocation; - } - public String getPriority() { return priority; } @@ -260,34 +254,21 @@ public class StdPAPPolicyParams { return deleteCondition; } - public void setDeleteCondition(String deleteCondition) { - this.deleteCondition = deleteCondition; - } - public String getDictionaryType() { return dictionaryType; } - public void setDictionaryType(String dictionaryType) { - this.dictionaryType = dictionaryType; - } - public String getDictionary() { return dictionary; } - public void setDictionary(String dictionary) { - this.dictionary = dictionary; - } - public String getDictionaryFields() { return dictionaryFields; } - public void setDictionaryFields(String dictionaryFields) { - this.dictionaryFields = dictionaryFields; + public String getRawXacmlPolicy() { + return rawXacmlPolicy; } - /** * Builder class for the Policy parameters */ @@ -518,5 +499,10 @@ public class StdPAPPolicyParams { m.dictionaryFields = dictionaryFields; return this; } + + public StdPAPPolicyParamsBuilder rawXacmlPolicy(String rawXacmlPolicy) { + m.rawXacmlPolicy = rawXacmlPolicy; + return this; + } } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java index 928165909..e1d0223f6 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java @@ -137,11 +137,28 @@ public class XACMLPolicyWriter { * * */ - public static InputStream getXmlAsInputStream(PolicyType policy) { - JAXBElement policyElement = new ObjectFactory().createPolicy(policy); + public static InputStream getXmlAsInputStream(Object policy) { + JAXBElement policyElement; + if (policy instanceof PolicyType) { + policyElement = new ObjectFactory().createPolicy((PolicyType) policy); + return getByteArrayInputStream(policyElement, PolicyType.class); + } else if (policy instanceof PolicyType) { + policyElement = new ObjectFactory().createPolicySet((PolicySetType) policy); + return getByteArrayInputStream(policyElement, PolicySetType.class); + } + return null; + } + + /** + * Helper static class that reads the JAXB element and return policy input stream. + * @param policyElement + * @param className (PolicyType or PolicySetType ?). + * @return ByteArrayInputStream. + */ + public static InputStream getByteArrayInputStream(JAXBElement policyElement, Class className) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - JAXBContext context = JAXBContext.newInstance(PolicyType.class); + JAXBContext context = JAXBContext.newInstance(className); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(policyElement, byteArrayOutputStream); @@ -149,7 +166,7 @@ public class XACMLPolicyWriter { } catch (JAXBException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); throw new IllegalArgumentException("XACMLPolicyWriter writePolicyFile failed", e); - } + } } /** * Helper static class that does the work to write a policy set to an output stream. diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java index 5ff20b6fc..fdbee2a99 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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.controller; +import java.io.IOException; +import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -28,19 +30,19 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; - import javax.xml.bind.JAXBElement; - +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; 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.rest.adapter.RainyDayParams; import org.onap.policy.rest.adapter.YAMLParams; import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.xacml.util.XACMLPolicyWriter; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; - 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; @@ -50,6 +52,7 @@ 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.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; @@ -59,308 +62,366 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; @Controller @RequestMapping("/") public class DecisionPolicyController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class); - - public DecisionPolicyController(){ - // This constructor is empty - } + private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class); + + public DecisionPolicyController() { + // This constructor is empty + } + + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + private ArrayList decisionList; + private ArrayList ruleAlgorithmList; + private ArrayList treatmentList = null; + protected LinkedList ruleAlgoirthmTracker; + public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; + private static final String blEntry = "@blEntry@"; + private static final String decisionRawType = "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; + + public void rawXACMLPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) { + String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_"); + policyAdapter.setPolicyName(name.substring(0, name.indexOf('.'))); + policyAdapter.setRuleProvider("Raw"); + policyAdapter.setRawXacmlPolicy(IOUtils.toString(policyXmlStream).replaceAll(decisionRawType, "")); + } catch (IOException e) { + policyLogger.error("Exception Occured while setting XACML Raw Object" + e); + } + } - protected PolicyRestAdapter policyAdapter = null; - private ArrayList attributeList; - private ArrayList decisionList; - private ArrayList ruleAlgorithmList; - private ArrayList treatmentList = null; - protected LinkedList ruleAlgoirthmTracker; - public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; + @SuppressWarnings("unchecked") + public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + decisionList = new ArrayList<>(); + ruleAlgorithmList = new ArrayList<>(); + treatmentList = new ArrayList<>(); - @SuppressWarnings("unchecked") - public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); - decisionList = new ArrayList<>(); - ruleAlgorithmList = new ArrayList<>(); - treatmentList = new ArrayList<>(); - - if (policyAdapter.getPolicyData() instanceof PolicyType) { - RainyDayParams rainydayParams = new RainyDayParams(); - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - policyLogger.info("General error", e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. - TargetType target = policy.getTarget(); - if (target != null) { - // under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AntOfType we have AllOfType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOfType we have Mathch. - List matchList = allOf.getMatch(); - int index = 0; - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - if(value!=null){ + boolean rawPolicyCheck = false; + if (policyAdapter.getPolicyData() instanceof PolicySetType) { + rawPolicyCheck = ((PolicySetType) policyAdapter.getPolicyData()).getDescription().contains(decisionRawType); + } else { + rawPolicyCheck = ((PolicyType) policyAdapter.getPolicyData()).getDescription().contains(decisionRawType); + } + + if (rawPolicyCheck) { + rawXACMLPolicy(policyAdapter, entity); + } else { + RainyDayParams rainydayParams = new RainyDayParams(); + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + + policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_")); + String description = ""; + String blackListEntryType = "Use Manual Entry"; + try { + if (policy.getDescription().contains(blEntry)) { + blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(blEntry) + 9, + policy.getDescription().lastIndexOf(blEntry)); + } + policyAdapter.setBlackListEntryType(blackListEntryType); + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + + } catch (Exception e) { + policyLogger.info("General error", e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List matchList = allOf.getMatch(); + int index = 0; + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + if (value != null) { value = value.replaceAll("\\(\\?i\\)", ""); } - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - if (index >= 1) { - Map attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - index++; - } - } - policyAdapter.setAttributes(attributeList); - } - } - } - // Setting rainy day attributes to the parameters object if they exist - boolean rainy = false; - if(!attributeList.isEmpty()) { - for(int i=0; i map = (Map)attributeList.get(i); - if("WorkStep".equals(map.get("key"))){ - rainydayParams.setWorkstep(map.get("value")); - rainy=true; - }else if("BB_ID".equals(map.get("key"))){ - rainydayParams.setBbid(map.get("value")); - rainy=true; - }else if("ServiceType".equals(map.get("key"))){ - rainydayParams.setServiceType(map.get("value")); - rainy=true; - }else if("VNFType".equals(map.get("key"))){ - rainydayParams.setVnfType(map.get("value")); - rainy=true; - } - } - } - if(rainy){ - policyAdapter.setRuleProvider("Rainy_Day"); - } - } + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if ("ONAPName".equals(attributeId)) { + policyAdapter.setOnapName(value); + } + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + if (index >= 1) { + Map attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + } + index++; + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + // Setting rainy day attributes to the parameters object if they exist + boolean rainy = false; + if (!attributeList.isEmpty()) { + for (int i = 0; i < attributeList.size(); i++) { + Map map = (Map) attributeList.get(i); + if ("WorkStep".equals(map.get("key"))) { + rainydayParams.setWorkstep(map.get("value")); + rainy = true; + } else if ("BB_ID".equals(map.get("key"))) { + rainydayParams.setBbid(map.get("value")); + rainy = true; + } else if ("ServiceType".equals(map.get("key"))) { + rainydayParams.setServiceType(map.get("value")); + rainy = true; + } else if ("VNFType".equals(map.get("key"))) { + rainydayParams.setVnfType(map.get("value")); + rainy = true; + } + } + } + if (rainy) { + policyAdapter.setRuleProvider("Rainy_Day"); + } + } + + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + int index = 0; + for (Object object : ruleList) { + if (object instanceof VariableDefinitionType) { + VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; + Map settings = new HashMap<>(); + settings.put("key", variableDefinitionType.getVariableId()); + JAXBElement attributeValueTypeElement = + (JAXBElement) variableDefinitionType.getExpression(); + if (attributeValueTypeElement != null) { + AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); + settings.put("value", attributeValueType.getContent().get(0).toString()); + } + decisionList.add(settings); + } else if (object instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + if (((RuleType) object).getEffect().equals(EffectType.DENY)) { + if (((RuleType) object).getAdviceExpressions() != null) { + if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider("AAF"); + break; + } else if ("GUARD_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider("GUARD_YAML"); + } else if ("GUARD_BL_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider("GUARD_BL_YAML"); + } + } else { + policyAdapter.setRuleProvider("Custom"); + } + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); + ruleAlgoirthmTracker = new LinkedList<>(); + if (policyAdapter.getRuleProvider() != null + && ("GUARD_YAML".equals(policyAdapter.getRuleProvider()) + || ("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())))) { + YAMLParams yamlParams = new YAMLParams(); + for (int i = 0; i < attributeList.size(); i++) { + Map map = (Map) attributeList.get(i); + if ("actor".equals(map.get("key"))) { + yamlParams.setActor(map.get("value")); + } else if ("recipe".equals(map.get("key"))) { + yamlParams.setRecipe(map.get("value")); + } else if ("target".equals(map.get("key"))) { + yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); + } else if ("clname".equals(map.get("key"))) { + yamlParams.setClname(map.get("value")); + } + } + ApplyType apply = + (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue()) + .getExpression().get(0).getValue(); + yamlParams.setGuardActiveStart( + ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent() + .get(0).toString()); + yamlParams.setGuardActiveEnd( + ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent() + .get(0).toString()); + if ("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())) { + apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression() + .get(0).getValue()).getExpression().get(1).getValue()).getExpression() + .get(2).getValue(); + Iterator> attributes = apply.getExpression().iterator(); + List blackList = new ArrayList<>(); + while (attributes.hasNext()) { + blackList.add(((AttributeValueType) attributes.next().getValue()) + .getContent().get(0).toString()); + } + yamlParams.setBlackList(blackList); + if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) { + policyAdapter.setBlackListEntries(blackList); + } + } else { + ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply + .getExpression().get(0).getValue()).getExpression().get(1).getValue(); + yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression() + .get(1).getValue()).getContent().get(0).toString()); + String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection + .getExpression().get(0).getValue()).getExpression().get(0).getValue()) + .getIssuer(); + yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1)); + yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4, + timeWindow.lastIndexOf(':'))); + } + policyAdapter.setYamlparams(yamlParams); + policyAdapter.setAttributes(new ArrayList()); + policyAdapter.setRuleAlgorithmschoices(new ArrayList()); + break; + } + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + } else if (policyAdapter.getRuleProvider() != null + && "Rainy_Day".equals(policyAdapter.getRuleProvider()) + && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { + + TargetType ruleTarget = ((RuleType) object).getTarget(); + AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions(); + + String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1) + .getAttributeValue().getContent().get(0).toString(); + JAXBElement tempTreatmentObj = + (JAXBElement) adviceExpression.getAdviceExpression().get(0) + .getAttributeAssignmentExpression().get(0).getExpression(); + String treatment = tempTreatmentObj.getValue().getContent().get(0).toString(); + + prePopulateRainyDayTreatments(errorcode, treatment); + + } + } + } + } + + rainydayParams.setTreatmentTableChoices(treatmentList); + policyAdapter.setRainyday(rainydayParams); + policyAdapter.setSettings(decisionList); + } + + } + + private void prePopulateRainyDayTreatments(String errorcode, String treatment) { + Map ruleMap = new HashMap<>(); - List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - int index = 0; - for (Object object : ruleList) { - if (object instanceof VariableDefinitionType) { - VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; - Map settings = new HashMap<>(); - settings.put("key", variableDefinitionType.getVariableId()); - JAXBElement attributeValueTypeElement = (JAXBElement) variableDefinitionType.getExpression(); - if (attributeValueTypeElement != null) { - AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); - settings.put("value", attributeValueType.getContent().get(0).toString()); - } - decisionList.add(settings); - } else if (object instanceof RuleType) { - // get the condition data under the rule for rule Algorithms. - if(((RuleType) object).getEffect().equals(EffectType.DENY)) { - if(((RuleType) object).getAdviceExpressions()!=null){ - if("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){ - policyAdapter.setRuleProvider("AAF"); - break; - }else if("GUARD_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){ - policyAdapter.setRuleProvider("GUARD_YAML"); - }else if("GUARD_BL_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){ - policyAdapter.setRuleProvider("GUARD_BL_YAML"); - } - }else{ - policyAdapter.setRuleProvider("Custom"); - } - ConditionType condition = ((RuleType) object).getCondition(); - if (condition != null) { - ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); - decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - if(policyAdapter.getRuleProvider()!=null && ("GUARD_YAML".equals(policyAdapter.getRuleProvider())||("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())))){ - YAMLParams yamlParams = new YAMLParams(); - for(int i=0; i map = (Map)attributeList.get(i); - if("actor".equals(map.get("key"))){ - yamlParams.setActor(map.get("value")); - }else if("recipe".equals(map.get("key"))){ - yamlParams.setRecipe(map.get("value")); - }else if("target".equals(map.get("key"))){ - yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); - }else if("clname".equals(map.get("key"))){ - yamlParams.setClname(map.get("value")); - } - } - ApplyType apply = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue(); - yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString()); - yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString()); - if("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())){ - apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue(); - Iterator> attributes = apply.getExpression().iterator(); - List blackList = new ArrayList<>(); - while(attributes.hasNext()){ - blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString()); - } - yamlParams.setBlackList(blackList); - }else{ - ApplyType timeWindowSection = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue(); - yamlParams.setLimit(((AttributeValueType)timeWindowSection.getExpression().get(1).getValue()).getContent().get(0).toString()); - String timeWindow = ((AttributeDesignatorType)((ApplyType)timeWindowSection.getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); - yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':')+1)); - yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:")+4,timeWindow.lastIndexOf(':'))); - } - policyAdapter.setYamlparams(yamlParams); - policyAdapter.setAttributes(new ArrayList()); - policyAdapter.setRuleAlgorithmschoices(new ArrayList()); - break; - } - // Populating Rule Algorithms starting from compound. - prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - } - } else if(policyAdapter.getRuleProvider()!=null && "Rainy_Day".equals(policyAdapter.getRuleProvider())&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { - - TargetType ruleTarget = ((RuleType) object).getTarget(); - AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions(); - - String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch(). - get(1).getAttributeValue().getContent().get(0).toString(); - JAXBElement tempTreatmentObj = (JAXBElement) adviceExpression.getAdviceExpression(). - get(0).getAttributeAssignmentExpression().get(0).getExpression(); - String treatment = tempTreatmentObj.getValue().getContent().get(0).toString(); - - prePopulateRainyDayTreatments(errorcode, treatment); + ruleMap.put("errorcode", errorcode); + ruleMap.put("treatment", treatment); + treatmentList.add(ruleMap); - } - } - } - } - - rainydayParams.setTreatmentTableChoices(treatmentList); - policyAdapter.setRainyday(rainydayParams); - policyAdapter.setSettings(decisionList); - } + } - } + private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, + List> jaxbDecisionTypes) { + Map ruleMap = new HashMap<>(); + ruleMap.put("id", "A" + (index + 1)); + Map dropDownMap = PolicyController.getDropDownMap(); + for (Entry entry : dropDownMap.entrySet()) { + if (entry.getValue().equals(decisionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey()); + } + } + // Populate the key and value fields + if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) { + ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue(); + List> jaxbInnerDecisionTypes = innerDecisionApply.getExpression(); + if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) { + AttributeDesignatorType attributeDesignator = + (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); - private void prePopulateRainyDayTreatments(String errorcode, String treatment) { - Map ruleMap = new HashMap<>(); - - ruleMap.put("errorcode", errorcode); - ruleMap.put("treatment", treatment); - treatmentList.add(ruleMap); - - } - - private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List> jaxbDecisionTypes) { - Map ruleMap = new HashMap<>(); - ruleMap.put("id", "A" + (index +1)); - Map dropDownMap = PolicyController.getDropDownMap(); - for (Entry entry : dropDownMap.entrySet()) { - if (entry.getValue().equals(decisionApply.getFunctionId())) { - ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey()); - } - } - // Populate the key and value fields - if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) { - ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue(); - List> jaxbInnerDecisionTypes = innerDecisionApply.getExpression(); - if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) { - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = + (AttributeValueType) jaxbDecisionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) { + VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId()); - // Get from Attribute Value - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - } - } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) { - VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId()); + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + ruleAlgorithmList.add(ruleMap); + } - // Get from Attribute Value - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - } - ruleAlgorithmList.add(ruleMap); - } + private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) { + boolean isCompoundRule = true; + List> jaxbDecisionTypes = decisionApply.getExpression(); + for (JAXBElement jaxbElement : jaxbDecisionTypes) { + // If There is Attribute Value under Decision Type that means we came to the final child + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if (jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement jaxbElement : jaxbDecisionTypes) { + ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); + } + // Populate combo box + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating Compound rule algorithm: " + index); + } + Map rule = new HashMap<>(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + break; + } + } - private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) { - boolean isCompoundRule = true; - List> jaxbDecisionTypes = decisionApply.getExpression(); - for (JAXBElement jaxbElement : jaxbDecisionTypes) { - // If There is Attribute Value under Decision Type that means we came to the final child - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating rule algoirthm: " + index); - } - // Check to see if Attribute Value exists, if yes then it is not a compound rule - if(jaxbElement.getValue() instanceof AttributeValueType) { - prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes); - ruleAlgoirthmTracker.addLast(index); - isCompoundRule = false; - index++; - } - } - if (isCompoundRule) { - // As it's compound rule, Get the Apply types - for (JAXBElement jaxbElement : jaxbDecisionTypes) { - ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); - index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); - } - // Populate combo box - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating Compound rule algorithm: " + index); - } - Map rule = new HashMap<>(); - for (String key : PolicyController.getDropDownMap().keySet()) { - String keyValue = PolicyController.getDropDownMap().get(key); - if (keyValue.equals(decisionApply.getFunctionId())) { - rule.put("dynamicRuleAlgorithmCombo", key); - break; - } - } + rule.put("id", "A" + (index + 1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } - rule.put("id", "A" + (index +1)); - // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); - ruleAlgorithmList.add(rule); - index++; - } - - return index; - } + return index; + } } diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js index f560f4d58..ba9e44868 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js @@ -17,414 +17,444 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module('abs').controller('decisionPolicyController', ['$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', '$http', function ($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification, $http) { - $("#dialog").hide(); - - $scope.policyNavigator; - $scope.savebutton = true; - $scope.refreshCheck = false; - $scope.disableOnCreate = false; - - if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){ - $scope.disableOnCreate = true; - $scope.temp.policy = { - policyType : "Decision" - } - }; - - $scope.refresh = function(){ - if($scope.refreshCheck){ - $scope.policyNavigator.refresh(); - } - $scope.modal('createNewPolicy', true); - $scope.temp.policy = ""; - }; - - $scope.modal = function(id, hide) { - return $('#' + id).modal(hide ? 'hide' : 'show'); - }; - - if($scope.temp.policy.ruleProvider==undefined){ - $scope.temp.policy.ruleProvider="Custom"; +angular.module('abs').controller('decisionPolicyController', [ '$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', '$http', function($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification, $http) { + $("#dialog").hide(); + + $scope.policyNavigator; + $scope.savebutton = true; + $scope.refreshCheck = false; + $scope.disableOnCreate = false; + $scope.notRawPolicy = true; + + if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) { + $scope.disableOnCreate = true; + $scope.temp.policy = { + policyType : "Decision" + } } - - if($scope.temp.policy.blackListEntryType==undefined){ - $scope.temp.policy.blackListEntryType="Use Manual Entry"; + ; + + $scope.refresh = function() { + if ($scope.refreshCheck) { + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + $scope.temp.policy = ""; + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; + + if ($scope.temp.policy.ruleProvider == undefined) { + $scope.temp.policy.ruleProvider = "Custom"; + } + + if ($scope.temp.policy.blackListEntryType == undefined) { + $scope.temp.policy.blackListEntryType = "Use Manual Entry"; } - - PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) { + + PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) { var j = data; $scope.data = JSON.parse(j.data); console.log($scope.data); $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas); console.log($scope.onapNameDictionaryDatas); - }, function (error) { + }, function(error) { console.log("failed"); }); - PolicyAppService.getData('getDictionary/get_SettingsDictionaryDataByName').then(function (data) { + PolicyAppService.getData('getDictionary/get_SettingsDictionaryDataByName').then(function(data) { var j = data; $scope.data = JSON.parse(j.data); console.log($scope.data); $scope.settingsDictionaryDatas = JSON.parse($scope.data.settingsDictionaryDatas); console.log($scope.settingsDictionaryDatas); - }, function (error) { + }, function(error) { console.log("failed"); }); - PolicyAppService.getData('get_FunctionDefinitionDataByName').then(function (data) { + PolicyAppService.getData('get_FunctionDefinitionDataByName').then(function(data) { var j = data; $scope.data = JSON.parse(j.data); console.log($scope.data); $scope.functionDefinitionDatas = JSON.parse($scope.data.functionDefinitionDatas); console.log($scope.functionDefinitionDatas); - }, function (error) { + }, function(error) { console.log("failed"); }); - PolicyAppService.getData('getDictionary/get_AttributeDatabyAttributeName').then(function (data) { + PolicyAppService.getData('getDictionary/get_AttributeDatabyAttributeName').then(function(data) { var j = data; $scope.data = JSON.parse(j.data); console.log($scope.data); $scope.attributeDictionaryDatas = JSON.parse($scope.data.attributeDictionaryDatas); console.log($scope.attributeDictionaryDatas); - }, function (error) { + }, function(error) { console.log("failed"); }); - PolicyAppService.getData('getDictionary/get_RainyDayDictionaryDataByName').then(function (data) { + PolicyAppService.getData('getDictionary/get_RainyDayDictionaryDataByName').then(function(data) { var j = data; $scope.data = JSON.parse(j.data); console.log($scope.data); - $scope.rainyDayDictionaryDatas = JSON.parse($scope.data.rainyDayDictionaryDatas); + $scope.rainyDayDictionaryDatas = JSON.parse($scope.data.rainyDayDictionaryDatas); console.log($scope.rainyDayDictionaryDatas); - }, function (error) { + }, function(error) { console.log("failed"); }); - - PolicyAppService.getData('getDictionary/get_RainyDayDictionaryData').then(function (data) { - var j = data; - $scope.data = JSON.parse(j.data); - console.log($scope.data); - $scope.rainyDayDictionaryDataEntity = JSON.parse($scope.data.rainyDayDictionaryDatas); - console.log($scope.rainyDayDictionaryDatasEntity); - }, function (error) { - console.log("failed"); - }); - - function extend(obj, src) { - for (var key in src) { - if (src.hasOwnProperty(key)) obj[key] = src[key]; - } - return obj; - } - - $scope.saveDecisionPolicy = function(policy){ - if(policy.itemContent != undefined){ - $scope.refreshCheck = true; - $scope.policyNavigator = policy.itemContent; - policy.itemContent = ""; - } - $scope.savebutton = false; - console.log(policy); - var uuu = "policycreation/save_policy"; - var postData={policyData: policy}; + + PolicyAppService.getData('getDictionary/get_RainyDayDictionaryData').then(function(data) { + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.rainyDayDictionaryDataEntity = JSON.parse($scope.data.rainyDayDictionaryDatas); + console.log($scope.rainyDayDictionaryDatasEntity); + }, function(error) { + console.log("failed"); + }); + + function extend(obj, src) { + for (var key in src) { + if (src.hasOwnProperty(key)) + obj[key] = src[key]; + } + return obj; + } + + $scope.saveDecisionPolicy = function(policy) { + if (policy.itemContent != undefined) { + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } + $scope.savebutton = false; + console.log(policy); + var uuu = "policycreation/save_policy"; + var postData = { + policyData : policy + }; $.ajax({ type : 'POST', url : uuu, - dataType: 'json', - contentType: 'application/json', - data: JSON.stringify(postData), - success : function(data){ - $scope.$apply(function(){ - $scope.data=data.policyData; - if($scope.data == 'success'){ + dataType : 'json', + contentType : 'application/json', + data : JSON.stringify(postData), + success : function(data) { + $scope.$apply(function() { + $scope.data = data.policyData; + if ($scope.data == 'success') { $scope.temp.policy.readOnly = 'true'; - Notification.success("Policy Saved Successfully."); - }else if ($scope.data == 'PolicyExists'){ + Notification.success("Policy Saved Successfully."); + } else if ($scope.data == 'PolicyExists') { $scope.savebutton = true; Notification.error("Policy Already Exists with Same Name in Scope."); - } + } }); console.log($scope.data); - + }, - error : function(data){ + error : function(data) { Notification.error("Error Occured while saving Policy."); } }); - }; - - $scope.validatePolicy = function(policy){ - console.log(policy); - document.getElementById("validate").innerHTML = ""; - var uuu = "policyController/validate_policy.htm"; - var postData={policyData: policy}; - $.ajax({ - type : 'POST', - url : uuu, - dataType: 'json', - contentType: 'application/json', - data: JSON.stringify(postData), - success : function(data){ - $scope.$apply(function(){ - $scope.validateData = data.data.replace(/\"/g, ""); - $scope.data=data.data; - if($scope.data == '"success"'){ - Notification.success("Validation Success."); - $scope.savebutton = false; - }else{ - Notification.error("Validation Failed."); - document.getElementById("validate").innerHTML = $scope.validateData; - document.getElementById("validate").style.color = "white"; - document.getElementById("validate").style.backgroundColor = "red"; - $scope.savebutton = true; - } - - }); - console.log($scope.data); - }, - error : function(data){ - Notification.error("Validation Failed."); - $scope.savebutton = true; - } - }); - }; - - if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){ - $scope.temp.policy.attributes = []; - $scope.temp.policy.settings = []; - $scope.temp.policy.ruleAlgorithmschoices = []; - if(!$scope.temp.policy.yamlparams){ - $scope.temp.policy.yamlparams = {}; - } - if(!$scope.temp.policy.yamlparams.targets){ - $scope.temp.policy.yamlparams.targets = []; - } - if(!$scope.temp.policy.yamlparams.blackList){ - $scope.temp.policy.yamlparams.blackList = []; - } - if(!$scope.temp.policy.rainyday){ - $scope.temp.policy.rainyday = {}; - } - if(!$scope.temp.policy.rainyday.treatmentTableChoices){ - $scope.temp.policy.rainyday.treatmentTableChoices = []; - } - - }else if($scope.temp.policy.ruleProvider=="Custom"){ - if($scope.temp.policy.attributes.length == 0){ - $scope.temp.policy.attributes = []; - } - if($scope.temp.policy.settings.length == 0){ - $scope.temp.policy.settings = []; - } - if($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0){ - $scope.temp.policy.ruleAlgorithmschoices = []; - } - }else if($scope.temp.policy.ruleProvider=="GUARD_BL_YAML"){ - if($scope.temp.policy.yamlparams.blackList == null || $scope.temp.policy.yamlparams.blackList.length==0){ - $scope.temp.policy.yamlparams.blackList = []; - } - if($scope.temp.policy.blackListEntries == null || $scope.temp.policy.blackListEntries.length==0){ - $scope.temp.policy.blackListEntries = []; - } - $scope.blackListEntries = []; - $scope.temp.policy.appendBlackListEntries = []; - $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList)); - }else if($scope.temp.policy.ruleProvider=="GUARD_YAML"){ - if($scope.temp.policy.yamlparams.targets.length==0){ - $scope.temp.policy.yamlparams.targets = []; - } - }else if($scope.temp.policy.ruleProvider=="Rainy_Day"){ - if($scope.temp.policy.rainyday.treatmentTableChoices == null || $scope.temp.policy.rainyday.treatmentTableChoices.length == 0){ - $scope.temp.policy.rainyday.treatmentTableChoices = []; - } - } - $scope.attributeDatas = [{"attributes" : $scope.temp.policy.attributes}]; - $scope.addNewChoice = function() { - var newItemNo = $scope.temp.policy.attributes.length+1; - $scope.temp.policy.attributes.push({'id':'choice'+newItemNo}); - }; - $scope.removeChoice = function() { - var lastItem = $scope.temp.policy.attributes.length-1; - $scope.temp.policy.attributes.splice(lastItem); - }; - - $scope.settingsDatas = [{"settings" : $scope.temp.policy.settings}]; - $scope.addNewSettingsChoice = function() { - var newItemNo = $scope.temp.policy.settings.length+1; - $scope.temp.policy.settings.push({'id':'choice'+newItemNo}); - }; - $scope.removeSettingsChoice = function() { - var lastItem = $scope.temp.policy.settings.length-1; - $scope.temp.policy.settings.splice(lastItem); - }; - - $scope.addNewTarget = function(){ - $scope.temp.policy.yamlparams.targets.push(''); - }; - $scope.removeTarget = function(){ - var lastItem = $scope.temp.policy.yamlparams.targets.length-1; - $scope.temp.policy.yamlparams.targets.splice(lastItem); - }; - - $scope.addNewBL = function() { - $scope.temp.policy.yamlparams.blackList.push(''); - }; - - $scope.removeBL = function(id) { - $scope.temp.policy.yamlparams.blackList = $scope.temp.policy.yamlparams.blackList.filter(function (obj){ + }; + + $scope.validatePolicy = function(policy) { + console.log(policy); + document.getElementById("validate").innerHTML = ""; + var uuu = "policyController/validate_policy.htm"; + var postData = { + policyData : policy + }; + $.ajax({ + type : 'POST', + url : uuu, + dataType : 'json', + contentType : 'application/json', + data : JSON.stringify(postData), + success : function(data) { + $scope.$apply(function() { + $scope.validateData = data.data.replace(/\"/g, ""); + $scope.data = data.data; + if ($scope.data == '"success"') { + Notification.success("Validation Success."); + $scope.savebutton = false; + } else { + Notification.error("Validation Failed."); + document.getElementById("validate").innerHTML = $scope.validateData; + document.getElementById("validate").style.color = "white"; + document.getElementById("validate").style.backgroundColor = "red"; + $scope.savebutton = true; + } + + }); + console.log($scope.data); + }, + error : function(data) { + Notification.error("Validation Failed."); + $scope.savebutton = true; + } + }); + }; + + if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) { + $scope.temp.policy.attributes = []; + $scope.temp.policy.settings = []; + $scope.temp.policy.ruleAlgorithmschoices = []; + if (!$scope.temp.policy.yamlparams) { + $scope.temp.policy.yamlparams = {}; + } + if (!$scope.temp.policy.yamlparams.targets) { + $scope.temp.policy.yamlparams.targets = []; + } + if (!$scope.temp.policy.yamlparams.blackList) { + $scope.temp.policy.yamlparams.blackList = []; + } + if (!$scope.temp.policy.rainyday) { + $scope.temp.policy.rainyday = {}; + } + if (!$scope.temp.policy.rainyday.treatmentTableChoices) { + $scope.temp.policy.rainyday.treatmentTableChoices = []; + } + + } else if ($scope.temp.policy.ruleProvider == "Custom") { + if ($scope.temp.policy.attributes.length == 0) { + $scope.temp.policy.attributes = []; + } + if ($scope.temp.policy.settings.length == 0) { + $scope.temp.policy.settings = []; + } + if ($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0) { + $scope.temp.policy.ruleAlgorithmschoices = []; + } + } else if ($scope.temp.policy.ruleProvider == "GUARD_BL_YAML") { + if ($scope.temp.policy.yamlparams.blackList == null || $scope.temp.policy.yamlparams.blackList.length == 0) { + $scope.temp.policy.yamlparams.blackList = []; + } + if ($scope.temp.policy.blackListEntries == null || $scope.temp.policy.blackListEntries.length == 0) { + $scope.temp.policy.blackListEntries = []; + } + $scope.blackListEntries = []; + $scope.temp.policy.appendBlackListEntries = []; + $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList)); + } else if ($scope.temp.policy.ruleProvider == "GUARD_YAML") { + if ($scope.temp.policy.yamlparams.targets.length == 0) { + $scope.temp.policy.yamlparams.targets = []; + } + } else if ($scope.temp.policy.ruleProvider == "Rainy_Day") { + if ($scope.temp.policy.rainyday.treatmentTableChoices == null || $scope.temp.policy.rainyday.treatmentTableChoices.length == 0) { + $scope.temp.policy.rainyday.treatmentTableChoices = []; + } + } + $scope.attributeDatas = [ { + "attributes" : $scope.temp.policy.attributes + } ]; + $scope.addNewChoice = function() { + var newItemNo = $scope.temp.policy.attributes.length + 1; + $scope.temp.policy.attributes.push({ + 'id' : 'choice' + newItemNo + }); + }; + $scope.removeChoice = function() { + var lastItem = $scope.temp.policy.attributes.length - 1; + $scope.temp.policy.attributes.splice(lastItem); + }; + + $scope.settingsDatas = [ { + "settings" : $scope.temp.policy.settings + } ]; + $scope.addNewSettingsChoice = function() { + var newItemNo = $scope.temp.policy.settings.length + 1; + $scope.temp.policy.settings.push({ + 'id' : 'choice' + newItemNo + }); + }; + $scope.removeSettingsChoice = function() { + var lastItem = $scope.temp.policy.settings.length - 1; + $scope.temp.policy.settings.splice(lastItem); + }; + + $scope.addNewTarget = function() { + $scope.temp.policy.yamlparams.targets.push(''); + }; + $scope.removeTarget = function() { + var lastItem = $scope.temp.policy.yamlparams.targets.length - 1; + $scope.temp.policy.yamlparams.targets.splice(lastItem); + }; + + $scope.addNewBL = function() { + $scope.temp.policy.yamlparams.blackList.push(''); + }; + + $scope.removeBL = function(id) { + $scope.temp.policy.yamlparams.blackList = $scope.temp.policy.yamlparams.blackList.filter(function(obj) { return obj !== id; }); - }; - - $scope.treatmentDatas = [{"treatmentValues" : $scope.temp.policy.rainyday.treatmentTableChoices}]; - $scope.addNewTreatment = function() { - $scope.temp.policy.rainyday.treatmentTableChoices.push({}); - }; - $scope.removeTreatment = function() { - var lastItem = $scope.temp.policy.rainyday.treatmentTableChoices.length-1; - $scope.temp.policy.rainyday.treatmentTableChoices.splice(lastItem); - }; - + }; + + $scope.treatmentDatas = [ { + "treatmentValues" : $scope.temp.policy.rainyday.treatmentTableChoices + } ]; + $scope.addNewTreatment = function() { + $scope.temp.policy.rainyday.treatmentTableChoices.push({}); + }; + $scope.removeTreatment = function() { + var lastItem = $scope.temp.policy.rainyday.treatmentTableChoices.length - 1; + $scope.temp.policy.rainyday.treatmentTableChoices.splice(lastItem); + }; + $scope.workstepDictionaryDatas = []; - $scope.getWorkstepValues = function(bbidValue){ + $scope.getWorkstepValues = function(bbidValue) { for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) { - var obj = $scope.rainyDayDictionaryDataEntity[i]; - if (obj.bbid == bbidValue){ - $scope.workstepDictionaryDatas.push(obj.workstep); - } - } + var obj = $scope.rainyDayDictionaryDataEntity[i]; + if (obj.bbid == bbidValue) { + $scope.workstepDictionaryDatas.push(obj.workstep); + } + } }; - + $scope.allowedTreatmentsDatas = []; - $scope.getTreatmentValues = function(bbidValue, workstepValue){ + $scope.getTreatmentValues = function(bbidValue, workstepValue) { for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) { - var obj = $scope.rainyDayDictionaryDataEntity[i]; - if (obj.bbid == bbidValue && obj.workstep == workstepValue){ - var splitAlarm = obj.treatments.split(','); - for (var j = 0; j < splitAlarm.length; ++j) { - $scope.allowedTreatmentsDatas.push(splitAlarm[j]); - } - } - } + var obj = $scope.rainyDayDictionaryDataEntity[i]; + if (obj.bbid == bbidValue && obj.workstep == workstepValue) { + var splitAlarm = obj.treatments.split(','); + for (var j = 0; j < splitAlarm.length; ++j) { + $scope.allowedTreatmentsDatas.push(splitAlarm[j]); + } + } + } + }; + + $scope.ItemNo = 0; + $scope.ruleAlgorithmDatas = [ { + "ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices + } ]; + + $scope.addNewRuleAlgorithm = function() { + if ($scope.temp.policy.ruleAlgorithmschoices != null) { + var newItemNo = $scope.temp.policy.ruleAlgorithmschoices.length + 1; + } else { + var newItemNo = 1; + } + if (newItemNo > 1) { + var value = newItemNo - 1; + $scope.attributeDictionaryDatas.push('A' + value); + } + $scope.temp.policy.ruleAlgorithmschoices.push({ + 'id' : 'A' + newItemNo + }); + }; + + $scope.removeRuleAlgorithm = function() { + var lastItem = $scope.temp.policy.ruleAlgorithmschoices.length - 1; + $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem); + }; + + $scope.providerListener = function(ruleProvider) { + if (ruleProvider != "Custom") { + $scope.temp.policy.ruleAlgorithmschoices = []; + $scope.temp.policy.settings = []; + $scope.temp.policy.attributes = []; + } + if (ruleProvider === "Raw") { + $scope.notRawPolicy = false; + } }; - - $scope.ItemNo = 0; - $scope.ruleAlgorithmDatas = [{"ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices }]; - - $scope.addNewRuleAlgorithm = function() { - if($scope.temp.policy.ruleAlgorithmschoices != null){ - var newItemNo = $scope.temp.policy.ruleAlgorithmschoices.length+1; - }else{ - var newItemNo = 1; - } - if(newItemNo > 1){ - var value = newItemNo-1; - $scope.attributeDictionaryDatas.push('A'+value); - } - $scope.temp.policy.ruleAlgorithmschoices.push({'id':'A'+newItemNo}); - }; - - $scope.removeRuleAlgorithm = function() { - var lastItem = $scope.temp.policy.ruleAlgorithmschoices.length-1; - $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem); - }; - - $scope.providerListener = function(ruleProvider) { - if (ruleProvider!="Custom"){ - $scope.temp.policy.ruleAlgorithmschoices = []; - $scope.temp.policy.settings = []; - $scope.temp.policy.attributes = []; - } - }; - - $scope.importButton = true; - var fd; + + $scope.importButton = true; + var fd; $scope.uploadBLFile = function(files) { fd = new FormData(); fd.append("file", files[0]); var fileExtension = files[0].name.split(".")[1]; - if(fileExtension == "xls"){ + if (fileExtension == "xls") { $scope.importButton = false; $scope.$apply(); - }else{ + } else { Notification.error("Upload the BlackList file which extends with .xls format."); } }; - + function arrayUnique(array) { - var a = array.concat(); - for(var i=0; i -
+
-
+
+
+
+
+
+ + +
+
+
+
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyParameters.java b/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyParameters.java index 2a8175f00..fb166d401 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyParameters.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyParameters.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PolicyEngineAPI * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -58,6 +58,7 @@ public class PolicyParameters { private String riskLevel = "5"; private String riskType = "default"; private String extendedOption; + private String rawXacmlPolicy; /** * Sets Config Policy Parameters. @@ -575,6 +576,14 @@ public class PolicyParameters { public void setTreatments(Map treatments) { this.treatments = treatments; } + + public String getRawXacmlPolicy() { + return rawXacmlPolicy; + } + + public void setRawXacmlPolicy(String rawXacmlPolicy) { + this.rawXacmlPolicy = rawXacmlPolicy; + } @Override public String toString() { diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/api/RuleProvider.java b/PolicyEngineAPI/src/main/java/org/onap/policy/api/RuleProvider.java index 913f32517..24d0bcd2c 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/api/RuleProvider.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/api/RuleProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PolicyEngineAPI * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -48,7 +48,11 @@ public enum RuleProvider { /** * Indicates Guard BLACKLIST YAML */ - RAINY_DAY("Rainy_Day"); + RAINY_DAY("Rainy_Day"), + /** + * Indicates Raw + */ + RAW("Raw"); private final String name; diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java new file mode 100644 index 000000000..5f0e74fc6 --- /dev/null +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineClient + * ================================================================================ + * Copyright (C) 2018 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policyengine; + +import java.util.UUID; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.RuleProvider; + +public class RawDecisionPolicyClient { + /* + * + * To Create a Decision Policy Use case. User need provide valid PolicySet or Policy Type xacml. On Setting below + * required attributes the Decision Raw policy will be created successfully. + * + */ + static Boolean isEdit = true; + + /** + * Sample code to create Decison Raw Policy. + * @param args with policy parameters + */ + public static void main(String[] args) { + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + PolicyParameters policyParameters = new PolicyParameters(); + // Set Policy Type + policyParameters.setPolicyClass(PolicyClass.Decision); // required + policyParameters.setPolicyName("com.testRawDecision"); // required + policyParameters.setRuleProvider(RuleProvider.RAW);// required + // required - The Raw XACML Policy Set or Policy and escape xml and remove line breaks. + policyParameters.setRawXacmlPolicy(""); + policyParameters.setRequestID(UUID.randomUUID()); + + // API method to create Policy or update policy + PolicyChangeResponse response = null; + if (!isEdit) { + response = policyEngine.createPolicy(policyParameters); + } else { + response = policyEngine.updatePolicy(policyParameters); + } + + if (response.getResponseCode() == 200) { + System.out.println(response.getResponseMessage()); + System.out.println("Policy Created Successfully!"); + } else { + System.out.println("Error! " + response.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } + +}