From: Pamela Dragosh Date: Mon, 14 Oct 2019 15:39:45 +0000 (-0400) Subject: Sonar cleanup in controllers etc X-Git-Tag: 1.6.0~66 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=commitdiff_plain;h=0950d79047d3404c15b4dd30cffeb81346565f64 Sonar cleanup in controllers etc Variable renaming of consecutive capital letters. Adding Javadoc Missing curly braces Re-writing some methods to reduce cyclomatic complexity Combining while's into a simple for statement. Addressing previous review comments No real effort on code coverage in this one. Issue-ID: POLICY-2133 Change-Id: I4afb3030203e1dbc743507e037ca3d57faf41f1d Signed-off-by: Pamela Dragosh --- diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java index 9d6210039..ed1266cfb 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java @@ -413,8 +413,8 @@ public class PolicyManagerServlet extends HttpServlet { String userId = UserUtils.getUserSession(request).getOrgUserId(); List userRoles = controller.getRoles(userId); Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - List roles = pair.u; - Set scopes = pair.t; + List roles = pair.second; + Set scopes = pair.first; if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) { if (scopes.isEmpty()) { return false; @@ -646,8 +646,8 @@ public class PolicyManagerServlet extends HttpServlet { String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); List userRoles = getPolicyControllerInstance().getRoles(userId); Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - List roles = pair.u; - Set scopes = pair.t; + List roles = pair.second; + Set scopes = pair.first; Map roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles); List resultList = new ArrayList<>(); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java index 60029f8d7..f2c3a5d7a 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java @@ -8,9 +8,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -106,9 +106,16 @@ public class HumanPolicyComponent { // Default Constructor } + /** + * DescribePolicy. + * + * @param policyFile File + * @return JSONObject + */ public static JSONObject DescribePolicy(final File policyFile) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } HumanPolicyComponent.policyFile = policyFile; return humanPolicyLayout(); @@ -116,8 +123,9 @@ public class HumanPolicyComponent { } private static JSONObject humanPolicyLayout() { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } try { String html = processPolicy(); @@ -137,8 +145,9 @@ public class HumanPolicyComponent { } try (FileInputStream pIS = new FileInputStream(policyFile)) { Object policy = XACMLPolicyScanner.readPolicy(pIS); - if (policy == null) + if (policy == null) { throw new IllegalArgumentException("Policy File " + policyFile.getName() + " cannot be unmarshalled"); + } HumanPolicyComponent.htmlProcessor = new HtmlProcessor(HumanPolicyComponent.policyFile, policy); @@ -146,8 +155,9 @@ public class HumanPolicyComponent { XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor); xacmlScanner.scan(); String html = htmlProcessor.html(); - if (LOGGER.isDebugEnabled()) + if (LOGGER.isDebugEnabled()) { LOGGER.debug(policyPath + System.lineSeparator() + html); + } return html; @@ -167,6 +177,7 @@ class HtmlProcessor extends SimpleCallback { private static final String ENTER = "ENTER"; private static Map function2human; + static { function2human = new HashMap<>(); function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal"); @@ -177,6 +188,7 @@ class HtmlProcessor extends SimpleCallback { } private static Map combiningAlgo2human; + static { combiningAlgo2human = new HashMap<>(); combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); @@ -205,8 +217,9 @@ class HtmlProcessor extends SimpleCallback { private final Object rootPolicyObject; public HtmlProcessor(File policyFile, Object policyObject) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } if (policyFile == null) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File"); @@ -261,6 +274,8 @@ class HtmlProcessor extends SimpleCallback { } /** + * getAttributeIdentifiersMap. + * * @return the attributeIdentifiersMap */ public Map getAttributeIdentifiersMap() { @@ -269,8 +284,9 @@ class HtmlProcessor extends SimpleCallback { @Override public void onFinishScan(Object root) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } if (rootPolicyObject instanceof PolicySetType) { htmlOut.println(""); @@ -308,43 +324,52 @@ class HtmlProcessor extends SimpleCallback { @Override public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } String description = policySet.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) + if (description != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription()); + } - if (parent == null) // root + if (parent == null) { // root policySet(policySet, "dl"); - else + } else { policySet(policySet, "li"); + } - if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) + if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) { htmlOut.println("
    "); + } return super.onPreVisitPolicySet(parent, policySet); } @Override public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } String description = policySet.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) + if (description != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription()); + } - if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) + if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) { htmlOut.println("
"); + } htmlOut.println("

"); @@ -352,21 +377,25 @@ class HtmlProcessor extends SimpleCallback { } public void policySet(PolicySetType policySet, String htmlListElement) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId()); + } String combiningAlgorithm = "-"; String id = "-"; String version = "-"; - if (policySet.getPolicyCombiningAlgId() != null) + if (policySet.getPolicyCombiningAlgId() != null) { combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); + } - if (policySet.getPolicySetId() != null) + if (policySet.getPolicySetId() != null) { id = extractLastIdentifier(policySet.getPolicySetId(), ":"); + } - if (policySet.getVersion() != null) + if (policySet.getVersion() != null) { version = policySet.getVersion(); + } htmlOut.println("<" + htmlListElement + ">Policy Set ID: " + id + " (v" + version + ") " + ""); @@ -378,8 +407,7 @@ class HtmlProcessor extends SimpleCallback { htmlOut.print("

"); htmlOut.print("This policy set applies to requests with attributes "); - List anyOf_s = policySet.getTarget().getAnyOf(); - target(anyOf_s); + target(policySet.getTarget().getAnyOf()); htmlOut.println(".

"); } @@ -398,57 +426,68 @@ class HtmlProcessor extends SimpleCallback { @Override public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } String description = policy.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) + if (description != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Description: " + policy.getDescription()); + } policy(policy); - if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) + if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) { htmlOut.println("
    "); + } return super.onPreVisitPolicy(parent, policy); } @Override public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } - if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) + if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) { htmlOut.println("
"); + } htmlOut.println("

"); return super.onPostVisitPolicy(parent, policy); } public void policy(PolicyType policy) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Policy: " + policy.getPolicyId()); + } String combiningAlgorithm = "-"; String id = "-"; String version = "-"; - if (policy.getRuleCombiningAlgId() != null) + if (policy.getRuleCombiningAlgId() != null) { combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); + } - if (policy.getPolicyId() != null) + if (policy.getPolicyId() != null) { id = extractLastIdentifier(policy.getPolicyId(), ":"); + } - if (policy.getVersion() != null) + if (policy.getVersion() != null) { version = policy.getVersion(); + } htmlOut.println("
  • Policy ID: " + id + " (v" + version + ") " + "
  • "); @@ -459,8 +498,7 @@ class HtmlProcessor extends SimpleCallback { htmlOut.print("

    "); htmlOut.print("This policy applies to requests with attributes "); - List anyOf_s = policy.getTarget().getAnyOf(); - target(anyOf_s); + target(policy.getTarget().getAnyOf()); htmlOut.println(".

    "); } @@ -478,11 +516,13 @@ class HtmlProcessor extends SimpleCallback { @Override public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Rule: " + rule.getRuleId()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + } String description = rule.getDescription(); if (description != null && LOGGER.isTraceEnabled()) { @@ -496,23 +536,21 @@ class HtmlProcessor extends SimpleCallback { @Override public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Rule: " + rule.getRuleId()); - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + } return super.onPostVisitRule(parent, rule); } public void rule(RuleType rule) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Rule: " + rule.getRuleId()); String id = "-"; - if (rule.getRuleId() != null) + if (rule.getRuleId() != null) { id = extractLastIdentifier(rule.getRuleId(), ":"); + } htmlOut.println("
  • Rule ID: " + id + "
  • "); @@ -524,9 +562,8 @@ class HtmlProcessor extends SimpleCallback { if (rule.getTarget() == null || rule.getTarget().getAnyOf() == null || rule.getTarget().getAnyOf().isEmpty()) { htmlOut.print(" for all requests"); } else { - List anyOf_s = rule.getTarget().getAnyOf(); htmlOut.print(" for requests with attributes "); - target(anyOf_s); + target(rule.getTarget().getAnyOf()); } if (rule.getCondition() != null) { @@ -538,8 +575,9 @@ class HtmlProcessor extends SimpleCallback { if (rule.getAdviceExpressions() != null) { advice(rule.getAdviceExpressions()); - if (rule.getObligationExpressions() != null) + if (rule.getObligationExpressions() != null) { htmlOut.println(" and "); + } } if (rule.getObligationExpressions() != null) { @@ -550,8 +588,9 @@ class HtmlProcessor extends SimpleCallback { } private void advice(AdviceExpressionsType adviceExpressions) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } List ae = adviceExpressions.getAdviceExpression(); for (AdviceExpressionType expression : ae) { @@ -567,8 +606,9 @@ class HtmlProcessor extends SimpleCallback { } private void obligation(ObligationExpressionsType obligationExpressions) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } List oe = obligationExpressions.getObligationExpression(); for (ObligationExpressionType expression : oe) { @@ -584,11 +624,14 @@ class HtmlProcessor extends SimpleCallback { } /** - * @param assignments + * processAttributeAssignments. + * + * @param assignments List of AttributeAssignmentExpressionType */ private void processAttributeAssignments(List assignments) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } for (AttributeAssignmentExpressionType assignment : assignments) { String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + ":" @@ -618,8 +661,9 @@ class HtmlProcessor extends SimpleCallback { for (Object c : avt.getContent()) { countContent++; htmlOut.print("" + c + ""); - if (countContent < numContent) + if (countContent < numContent) { htmlOut.print(" or "); + } } htmlOut.println(""); } else if (assignmentObject instanceof AttributeDesignatorType @@ -632,118 +676,118 @@ class HtmlProcessor extends SimpleCallback { } /** - * - * @param anyOfList + * target. + * + * @param anyOfList List of AnyOfType's */ public void target(List anyOfList) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - StringBuilder targetInHuman = new StringBuilder(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - if (matchList.size() > 1) - targetInHuman.append("("); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Finally down to the actual attribute - // - StdAttribute attribute = null; - AttributeValueType value = match.getAttributeValue(); - String attributeDataType; - if (match.getAttributeDesignator() != null && value != null) { - AttributeDesignatorType designator = match.getAttributeDesignator(); - attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), - new IdentifierImpl(designator.getAttributeId()), - new StdAttributeValue>(new IdentifierImpl(value.getDataType()), - value.getContent()), - designator.getIssuer(), false); - attributeDataType = designator.getDataType(); - } else if (match.getAttributeSelector() != null && value != null) { - AttributeSelectorType selector = match.getAttributeSelector(); - attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), - new IdentifierImpl(selector.getContextSelectorId()), - new StdAttributeValue>(new IdentifierImpl(value.getDataType()), - value.getContent()), - null, false); - attributeDataType = selector.getDataType(); - } else { - LOGGER.warn("NULL designator/selector or value for match."); - attributeDataType = "NA"; - } + if (anyOfList == null) { + return; + } + Iterator iterAnyOf = anyOfList.iterator(); + StringBuilder targetInHuman = new StringBuilder(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + List allOfList = anyOf.getAllOf(); + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + List matchList = allOf.getMatch(); + Iterator iterMatch = matchList.iterator(); + if (matchList.size() > 1) { + targetInHuman.append("("); + } + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + String attributeDataType; + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), + value.getContent()), + designator.getIssuer(), false); + attributeDataType = designator.getDataType(); + } else if (match.getAttributeSelector() != null && value != null) { + AttributeSelectorType selector = match.getAttributeSelector(); + attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), + new IdentifierImpl(selector.getContextSelectorId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), + value.getContent()), + null, false); + attributeDataType = selector.getDataType(); + } else { + LOGGER.warn("NULL designator/selector or value for match."); + attributeDataType = "NA"; + } - String functionName = getHumanFunction(match.getMatchId()); - if (attribute != null) { - String succintIdentifier = extractLastIdentifier( - attribute.getCategory().stringValue(), ":") + ":" - + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); - AttributeIdentifiers ai = - new AttributeIdentifiers(attribute.getCategory().stringValue(), - attributeDataType, attribute.getAttributeId().stringValue()); - this.attributeIdentifiersMap.put(succintIdentifier, ai); - - targetInHuman.append("" - + succintIdentifier + " " + functionName + " "); - - int numAttributes = attribute.getValues().size(); - int count = 0; - for (AttributeValue v : attribute.getValues()) { - count++; - if (v.getValue() instanceof Collection) { - Collection value_s = (Collection) v.getValue(); - int numValues = value_s.size(); - int countValues = 0; - for (Object o : value_s) { - countValues++; - targetInHuman.append(" " + o + ""); - if (countValues < numValues) { - targetInHuman.append(", or"); - } - } - } else { - targetInHuman.append(" " + v.getValue() + ""); - if (count < numAttributes) { - targetInHuman.append(", or "); - } - } + String functionName = getHumanFunction(match.getMatchId()); + if (attribute != null) { + String succintIdentifier = extractLastIdentifier( + attribute.getCategory().stringValue(), ":") + ":" + + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); + AttributeIdentifiers ai = + new AttributeIdentifiers(attribute.getCategory().stringValue(), + attributeDataType, attribute.getAttributeId().stringValue()); + this.attributeIdentifiersMap.put(succintIdentifier, ai); + + targetInHuman.append("" + + succintIdentifier + " " + functionName + " "); + + int numAttributes = attribute.getValues().size(); + int count = 0; + for (AttributeValue v : attribute.getValues()) { + count++; + if (v.getValue() instanceof Collection) { + Collection collectionValues = (Collection) v.getValue(); + int numValues = collectionValues.size(); + int countValues = 0; + for (Object o : collectionValues) { + countValues++; + targetInHuman.append(" " + o + ""); + if (countValues < numValues) { + targetInHuman.append(", or"); } } - - if (iterMatch.hasNext()) { - targetInHuman.append(" and "); + } else { + targetInHuman.append(" " + v.getValue() + ""); + if (count < numAttributes) { + targetInHuman.append(", or "); } - } // end iterMatch - if (matchList.size() > 1) { - targetInHuman.append(")"); } } - if (iterAllOf.hasNext()) { - targetInHuman.append(" or "); - } - } // end iterAllOf - } - if (iterAnyOf.hasNext()) { - targetInHuman = new StringBuilder(); - targetInHuman.append("(" + targetInHuman + ")" + " or "); - } else { - if (anyOfList.size() > 1) { - targetInHuman.append(")"); } + + if (iterMatch.hasNext()) { + targetInHuman.append(" and "); + } + } // end iterMatch + if (matchList.size() > 1) { + targetInHuman.append(")"); } - } // end iterAnyOf - htmlOut.println(targetInHuman); + } + if (iterAllOf.hasNext()) { + targetInHuman.append(" or "); + } + } // end iterAllOf + if (iterAnyOf.hasNext()) { + targetInHuman = new StringBuilder(); + targetInHuman.append("(" + targetInHuman + ")" + " or "); + } else { + if (anyOfList.size() > 1) { + targetInHuman.append(")"); + } } + htmlOut.println(targetInHuman); } private String getHumanFunction(String matchId) { @@ -813,12 +857,12 @@ class HtmlProcessor extends SimpleCallback { } else { StringBuilder forResult = new StringBuilder(); for (JAXBElement e : exps) { - Object v = e.getValue(); + Object theValue = e.getValue(); if (LOGGER.isDebugEnabled()) { - LOGGER.debug("one-and-only children: " + v); + LOGGER.debug("one-and-only children: " + theValue); } - if (v != null) { - forResult.append(stringifyExpression(v)); + if (theValue != null) { + forResult.append(stringifyExpression(theValue)); } } return forResult.toString(); @@ -838,8 +882,8 @@ class HtmlProcessor extends SimpleCallback { } StringBuilder applySubresult = new StringBuilder(); for (JAXBElement e : apply.getExpression()) { - Object v = e.getValue(); - if (v != null) { + Object theValue = e.getValue(); + if (theValue != null) { applySubresult.append(this.stringifyExpression(e.getValue())); } } @@ -904,11 +948,12 @@ class HtmlProcessor extends SimpleCallback { if (expression instanceof AttributeValueType) { AttributeValueType avt = (AttributeValueType) expression; List content = avt.getContent(); - StringBuilder value_s = new StringBuilder(); + StringBuilder stringValue = new StringBuilder(" "); for (Object o : content) { - value_s.append(" " + o.toString()); + stringValue.append(" "); + stringValue.append(o.toString()); } - return " " + value_s.toString(); + return stringValue.toString(); } if (expression instanceof VariableReferenceType) { // diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java index 98a479f81..666923b43 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java @@ -34,6 +34,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; @@ -71,36 +72,37 @@ public class ActionPolicyController extends RestrictedBaseController { performer.put("PDP", "PDPAction"); performer.put("PEP", "PEPAction"); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - // 1. Set policy-name, policy-filename and description to Policy Adapter - setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy); + // 1. Set policy-name, policy-filename and description to Policy Adapter + setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy); - // 2a. Get the target data under policy for Action. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } + // 2a. Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } - // 2b. Set attributes to Policy Adapter - setPolicyAdapterAttributes(policyAdapter, target.getAnyOf()); + // 2b. Set attributes to Policy Adapter + setPolicyAdapterAttributes(policyAdapter, target.getAnyOf()); - List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - // Under rule we have Condition and obligation. - for (Object o : ruleList) { - if (!(o instanceof RuleType)) { - continue; - } - // 3. Set rule-algorithm choices to Policy Adapter - setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o); + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (!(o instanceof RuleType)) { + continue; + } + // 3. Set rule-algorithm choices to Policy Adapter + setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o); - // 4a. Get the Obligation data under the rule for Form elements. - ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + // 4a. Get the Obligation data under the rule for Form elements. + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); - // 4b. Set action attribute-value and action-performer to Policy Adapter - setPolicyAdapterActionData(policyAdapter, obligations); - } + // 4b. Set action attribute-value and action-performer to Policy Adapter + setPolicyAdapterActionData(policyAdapter, obligations); } } @@ -194,7 +196,7 @@ public class ActionPolicyController extends RestrictedBaseController { // // 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. - allOfType.getMatch().forEach(match -> { + for (MatchType match : allOfType.getMatch()) { AttributeValueType attributeValue = match.getAttributeValue(); String value = (String) attributeValue.getContent().get(0); AttributeDesignatorType designator = match.getAttributeDesignator(); @@ -203,7 +205,7 @@ public class ActionPolicyController extends RestrictedBaseController { attribute.put("key", attributeId); attribute.put("value", value); attributeList.add(attribute); - }); + } policyAdapter.setAttributes(attributeList); } } @@ -226,34 +228,33 @@ public class ActionPolicyController extends RestrictedBaseController { index++; } } - if (isCompoundRule) { - // As it's compound rule, Get the Apply types - for (JAXBElement jaxbElement : jaxbActionTypes) { - ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); - index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); - } - // Populate combo box - if (LOGGER.isDebugEnabled()) { - LOGGER.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(actionApply.getFunctionId())) { - rule.put("dynamicRuleAlgorithmCombo", key); - } + if (!isCompoundRule) { + return index; + } + // As it's compound rule, Get the Apply types + for (JAXBElement jaxbElement : jaxbActionTypes) { + ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); + } + // Populate combo box + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Prepopulating Compound rule algorithm: " + index); + } + Map rule = new HashMap<>(); + for ( Entry entrySet : PolicyController.getDropDownMap().entrySet()) { + if (entrySet.getValue().equals(actionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", entrySet.getKey()); } - rule.put("id", "A" + (index + 1)); - // Populate Key and values for Compound Rule - rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1)); - ruleAlgorithmTracker.removeLast(); - rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1)); - ruleAlgorithmTracker.removeLast(); - ruleAlgorithmTracker.addLast(index); - ruleAlgorithmList.add(rule); - index++; } - return index; + rule.put("id", "A" + (index + 1)); + // Populate Key and values for Compound Rule + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + ruleAlgorithmTracker.addLast(index); + ruleAlgorithmList.add(rule); + return ++index; } private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List> jaxbActionTypes) { @@ -295,9 +296,11 @@ public class ActionPolicyController extends RestrictedBaseController { if (jaxbActionTypes.size() > 1) { ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); List> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = + if (! jaxbInnerActionTypes.isEmpty()) { + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); - ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); + } } } ruleAlgorithmList.add(ruleMap); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index f97a131a0..b5e17f2e0 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -31,7 +31,6 @@ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -339,15 +338,9 @@ public class AutoPushController extends RestrictedBaseController { response.setContentType("application / json"); request.setCharacterEncoding(UTF8); - PrintWriter out = response.getWriter(); refreshGroups(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - out.write(new JSONObject(msg).toString()); - // - // Why is this here? This defeats the purpose of the loop?? - // Sonar says to remove it or make it conditional - // - return null; + response.getWriter().write(new JSONObject( + new JsonMessage(mapper.writeValueAsString(groups))).toString()); } } catch (Exception e) { response.setCharacterEncoding(UTF8); @@ -401,10 +394,8 @@ public class AutoPushController extends RestrictedBaseController { response.setContentType("application / json"); request.setCharacterEncoding(UTF8); - PrintWriter out = response.getWriter(); refreshGroups(); - out.write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); - return null; + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); } catch (Exception e) { response.setCharacterEncoding(UTF8); request.setCharacterEncoding(UTF8); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java index fa515b202..1adeb6d96 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java @@ -251,48 +251,49 @@ public class CreateBRMSParamController extends RestrictedBaseController { */ public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { dynamicLayoutMap = new HashMap<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // policy name value is the policy name without any prefix and - // Extensions. - String policyNameValue = - policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); - if (policyLogger.isDebugEnabled()) { - policyLogger - .debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); - } - policyAdapter.setPolicyName(policyNameValue); - String description; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - policyLogger.info("Error getting description: " + e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - setDataAdapterFromAdviceExpressions(policy, policyAdapter); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); + if (policyLogger.isDebugEnabled()) { + policyLogger + .debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + policyLogger.info("Error getting description: " + e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + setDataAdapterFromAdviceExpressions(policy, policyAdapter); - // Generate Param UI - try { - paramUiGenerate(policyAdapter, entity); - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); - } + // Generate Param UI + try { + paramUiGenerate(policyAdapter, entity); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } - // Get the target data under policy. - policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); - if (policyAdapter.getDynamicLayoutMap().size() > 0) { - LinkedHashMap drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream() - .collect(Collectors.toMap(String::toString, - keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b, - LinkedHashMap::new)); - policyAdapter.setRuleData(drlRule); - } - TargetType target = policy.getTarget(); - if (target != null) { - setDataToAdapterFromTarget(target, policyAdapter); - } + // Get the target data under policy. + policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); + if (policyAdapter.getDynamicLayoutMap().size() > 0) { + LinkedHashMap drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream() + .collect(Collectors.toMap(String::toString, + keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b, + LinkedHashMap::new)); + policyAdapter.setRuleData(drlRule); + } + TargetType target = policy.getTarget(); + if (target != null) { + setDataToAdapterFromTarget(target, policyAdapter); } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java index 081b33cc0..214cb3244 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java @@ -55,36 +55,37 @@ public class CreateBRMSRawController { public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - - // Set PolicyAdapter name value - setPolicyAdapterNameValue(policyAdapter); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // Set PolicyAdapter description. - setPolicyAdapterDescription(policyAdapter, policy); + // Set PolicyAdapter name value + setPolicyAdapterNameValue(policyAdapter); - // Set PolicyAdapter attributes. - setPolicyAdapterAttributes(policyAdapter, policy); + // Set PolicyAdapter description. + setPolicyAdapterDescription(policyAdapter, policy); - // Set PolicyAdapter configBodyData - policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); + // Set PolicyAdapter attributes. + setPolicyAdapterAttributes(policyAdapter, policy); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } + // Set PolicyAdapter configBodyData + policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); - // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes - setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf()); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList == null) { + return; } + + // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes + setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf()); } private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List anyOfList) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java index 062ed2afa..9f19e4c71 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java @@ -485,30 +485,25 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { * @param entity PolicyEntity */ public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - - // Set PolicyAdapter policyName, description - setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy); - - // Set PolicyAdapter JsonBodyData, timeout settings - setClosedLoopJsonFile(policyAdapter, entity); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } + // Set PolicyAdapter policyName, description + setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy); - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } + // Set PolicyAdapter JsonBodyData, timeout settings + setClosedLoopJsonFile(policyAdapter, entity); - // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes - setPolicyAdapterMatchAttributes(policyAdapter, anyOfList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; } + + // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes + setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf()); } private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List anyOfList) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java index 1ca027b9c..8d47be76c 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java @@ -53,32 +53,28 @@ public class CreateClosedLoopPMController { protected PolicyRestAdapter policyAdapter = null; public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; - // Set oldPolicyFileName to PolicyAdapter - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // Set oldPolicyFileName to PolicyAdapter + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // Set policyNameValue and description to PolicyAdapter - setPolicyAdapterNameValueAndDescription(policyAdapter, policy); + // Set policyNameValue and description to PolicyAdapter + setPolicyAdapterNameValueAndDescription(policyAdapter, policy); - // Set PolicyAdapter JsonBodyData - setClosedLoopJsonFile(policyAdapter, entity); + // Set PolicyAdapter JsonBodyData + setClosedLoopJsonFile(policyAdapter, entity); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } - // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes - setPolicyAdapterMatchAttributes(policyAdapter, anyOfList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; } + // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes + setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf()); } private void setPolicyAdapterNameValueAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java index c5e29e422..2549e2167 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -37,7 +37,6 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.io.PrintWriter; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.Path; @@ -347,39 +346,39 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { // for Triggers ObjectMapper mapper = new ObjectMapper(); JsonNode tempJsonNode = mapper.readTree(cleanJson); - if (ruleCheck) { - ObjectNode finalJson = (ObjectNode) tempJsonNode; - JsonNode object = tempJsonNode.get("content"); - String primaryKey1 = model.getRuleFormation(); - String[] primaryKeyForSignatures = primaryKey1.split("@"); - for (String primaryKeyForSignature : primaryKeyForSignatures) { - String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.')); - JsonNode triggerSig = object.get(primarykeyAlarm); - sigRules = new HashMap<>(); - String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1); - StringBuilder sb = null; - if (triggerSig instanceof ArrayNode) { - for (int i = 0; i < triggerSig.size(); i++) { - sb = new StringBuilder(); - parseData(triggerSig.get(i), parseKey); - sb.append("("); - List keyList = new ArrayList<>(sigRules.keySet()); - for (int j = keyList.size() - 1; j >= 0; j--) { - String key = (String) keyList.get(j); - String jsonNode = sigRules.get(key); - constructRule(sb, jsonNode, sigRules); - } - sb.append(")").toString(); - putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm); - sigRules = new HashMap<>(); - } - } else { + if (! ruleCheck) { + return policyAdapter; + } + ObjectNode finalJson = (ObjectNode) tempJsonNode; + JsonNode object = tempJsonNode.get("content"); + String primaryKey1 = model.getRuleFormation(); + String[] primaryKeyForSignatures = primaryKey1.split("@"); + for (String primaryKeyForSignature : primaryKeyForSignatures) { + String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.')); + JsonNode triggerSig = object.get(primarykeyAlarm); + sigRules = new HashMap<>(); + String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1); + StringBuilder sb = null; + if (triggerSig instanceof ArrayNode) { + for (int i = 0; i < triggerSig.size(); i++) { sb = new StringBuilder(); - parseData(triggerSig, parseKey); + parseData(triggerSig.get(i), parseKey); + sb.append("("); + List keyList = new ArrayList<>(sigRules.keySet()); + for (int j = keyList.size() - 1; j >= 0; j--) { + String key = (String) keyList.get(j); + String jsonNode = sigRules.get(key); + constructRule(sb, jsonNode, sigRules); + } + sb.append(")").toString(); + putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm); + sigRules = new HashMap<>(); } + } else { + parseData(triggerSig, parseKey); } - policyAdapter.setJsonBody(finalJson.toString()); } + policyAdapter.setJsonBody(finalJson.toString()); return policyAdapter; } @@ -925,7 +924,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { allMnyTrueKeys = allkeys.toString(); } - String jsonModel = createMicroSeriveJson(returnModel, allkeys); + String jsonModel = createMicroSeriveJson(returnModel); JSONObject jsonObject = new JSONObject(jsonModel); @@ -983,7 +982,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } @SuppressWarnings({"unchecked", "rawtypes"}) - private String createMicroSeriveJson(MicroServiceModels returnModel, Set allkeys) { + private String createMicroSeriveJson(MicroServiceModels returnModel) { Map attributeMap = new HashMap<>(); Map refAttributeMap = new HashMap<>(); String attribute = returnModel.getAttributes(); @@ -1294,28 +1293,18 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { if (target == null) { return; } - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList == null) { - continue; - } - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { // Under AllOFType we have Match List matchList = allOf.getMatch(); if (matchList == null) { continue; } Iterator iterMatch = matchList.iterator(); + // + // Can someone please explain why the matchList MUST have + // more than 1 matches??? + // while (matchList.size() > 1 && iterMatch.hasNext()) { MatchType match = iterMatch.next(); // @@ -1329,28 +1318,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { // First match in the target is OnapName, so set that value. if ("ONAPName".equals(attributeId)) { policyAdapter.setOnapName(value); - } - if ("ConfigName".equals(attributeId)) { + } else if ("ConfigName".equals(attributeId)) { policyAdapter.setConfigName(value); - } - if ("uuid".equals(attributeId)) { + } else if ("uuid".equals(attributeId)) { policyAdapter.setUuid(value); - } - if ("location".equals(attributeId)) { + } else if ("location".equals(attributeId)) { policyAdapter.setLocation(value); - } - if ("RiskType".equals(attributeId)) { + } else if ("RiskType".equals(attributeId)) { policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)) { + } else if ("RiskLevel".equals(attributeId)) { policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)) { + } else if ("guard".equals(attributeId)) { policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); + } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + String newDate = new PolicyController().convertDate(value); policyAdapter.setTtlDate(newDate); } } @@ -1558,9 +1539,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - response.getWriter().write(j.toString()); + JSONObject json = new JSONObject(); + json.put("errorMsg", errorMsg); + response.getWriter().write(json.toString()); return; } @@ -1593,7 +1574,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { classMap = new LinkedHashMap<>(); for (File file : fileList) { if (!file.isDirectory() && file.getName().endsWith(".xmi")) { - retreiveDependency(file.toString(), true); + retrieveDependency(file.toString()); } } @@ -1657,7 +1638,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { */ @SuppressWarnings("rawtypes") private void extractFolder(String zipFile) { - int buffer = 2048; + final int buffer = 2048; File file = new File(zipFile); try (ZipFile zip = new ZipFile(file)) { @@ -1705,7 +1686,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } - private void retreiveDependency(String workingFile, Boolean modelClass) { + private void retrieveDependency(String workingFile) { MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); Map tempMap; @@ -1714,9 +1695,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { classMap.putAll(tempMap); LOGGER.info(tempMap); - - return; - } private List listModelFiles(String directoryName) { @@ -1798,7 +1776,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } - @Getter @Setter class DCAEMicroServiceObject { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java index 8aad4216d..0fbc34d71 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,13 +25,10 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -47,7 +44,7 @@ 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.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - +import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -91,11 +88,19 @@ public class CreateFirewallController extends RestrictedBaseController { private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class); private static final String ANY = "ANY"; private static final String GROUP = "Group_"; + private static CommonClassDao commonClassDao; + private List tagCollectorList; + private List termCollectorList; + + List expandablePrefixIpList = new ArrayList<>(); + List expandableServicesList = new ArrayList<>(); @Autowired SessionFactory sessionFactory; - private static CommonClassDao commonClassDao; + public CreateFirewallController() { + // Empty constructor + } public static CommonClassDao getCommonClassDao() { return commonClassDao; @@ -105,24 +110,18 @@ public class CreateFirewallController extends RestrictedBaseController { CreateFirewallController.commonClassDao = commonClassDao; } - private List tagCollectorList; - - List expandablePrefixIPList = new ArrayList<>(); - List expandableServicesList = new ArrayList<>(); - @Autowired private CreateFirewallController(CommonClassDao commonClassDao) { CreateFirewallController.commonClassDao = commonClassDao; } - public CreateFirewallController() { - // Empty constructor - } - - private List termCollectorList; - + /** + * setDataToPolicyRestAdapter. + * + * @param policyData PolicyRestAdapter + * @return PolicyRestAdapter + */ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData) { - String jsonBody; termCollectorList = new ArrayList<>(); tagCollectorList = new ArrayList<>(); if (!policyData.getAttributes().isEmpty()) { @@ -136,12 +135,15 @@ public class CreateFirewallController extends RestrictedBaseController { } } } - jsonBody = constructJson(policyData); - if (jsonBody != null && !"".equalsIgnoreCase(jsonBody)) { + String jsonBody = constructJson(policyData); + if (StringUtils.isBlank(jsonBody)) { policyData.setJsonBody(jsonBody); } else { policyData.setJsonBody("{}"); } + // + // Hmmm - seems to be overriding the previous if statement + // policyData.setJsonBody(jsonBody); return policyData; @@ -206,117 +208,109 @@ public class CreateFirewallController extends RestrictedBaseController { public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { ArrayList attributeList; attributeList = new ArrayList<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - // policy name value is the policy name without any prefix and Extensions. - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = - policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") + 3); - if (policyLogger.isDebugEnabled()) { - policyLogger - .debug("Prepopulating form data for Config Policy selected:" + policyAdapter.getPolicyName()); - } - 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); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + // policy name value is the policy name without any prefix and Extensions. + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") + 3); + if (policyLogger.isDebugEnabled()) { + policyLogger + .debug("Prepopulating form data for Config Policy selected:" + policyAdapter.getPolicyName()); + } + 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); - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); - TermCollector tc1 = null; - try { - // Json conversion. - String data; - SecurityZone jpaSecurityZone; - data = entity.getConfigurationData().getConfigBody(); - tc1 = mapper.readValue(data, TermCollector.class); - List securityZoneData = commonClassDao.getData(SecurityZone.class); - for (int i = 0; i < securityZoneData.size(); i++) { - jpaSecurityZone = (SecurityZone) securityZoneData.get(i); - if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())) { - policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); - break; - } + TermCollector tc1 = null; + try { + // Json conversion. + String data; + SecurityZone jpaSecurityZone; + data = entity.getConfigurationData().getConfigBody(); + tc1 = mapper.readValue(data, TermCollector.class); + List securityZoneData = commonClassDao.getData(SecurityZone.class); + for (int i = 0; i < securityZoneData.size(); i++) { + jpaSecurityZone = (SecurityZone) securityZoneData.get(i); + if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())) { + policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); + break; } - } catch (Exception e) { - policyLogger.error("Exception Caused while Retriving the JSON body data" + e); } + } catch (Exception e) { + policyLogger.error("Exception Caused while Retriving the JSON body data" + e); + } - Map termTagMap; - if (tc1 != null) { - for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) { - termTagMap = new HashMap<>(); - String ruleName = tc1.getFirewallRuleList().get(i).getRuleName(); - String tagPickerName = tc1.getRuleToTag().get(i).getTagPickerName(); - termTagMap.put("key", ruleName); - termTagMap.put("value", tagPickerName); - attributeList.add(termTagMap); - } + Map termTagMap; + if (tc1 != null) { + for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) { + termTagMap = new HashMap<>(); + String ruleName = tc1.getFirewallRuleList().get(i).getRuleName(); + String tagPickerName = tc1.getRuleToTag().get(i).getTagPickerName(); + termTagMap.put("key", ruleName); + termTagMap.put("value", tagPickerName); + attributeList.add(termTagMap); } - policyAdapter.setAttributes(attributeList); - // Get the target data under policy. - 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 AnyOFType 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 Match - List matchList = allOf.getMatch(); - if (matchList != null) { - - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - if (("ConfigName").equals(attributeId)) { - policyAdapter.setConfigName(value); - } - if (("RiskType").equals(attributeId)) { - policyAdapter.setRiskType(value); - } - if (("RiskLevel").equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } - if (("guard").equals(attributeId)) { - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - } - } - } - } + } + policyAdapter.setAttributes(attributeList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } + // Under target we have AnyOFType + // NOTE: target.getAnyOf() will never be null + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + for (MatchType match : allOf.getMatch()) { + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + if (("ConfigName").equals(attributeId)) { + policyAdapter.setConfigName(value); + } + if (("RiskType").equals(attributeId)) { + policyAdapter.setRiskType(value); + } + if (("RiskLevel").equals(attributeId)) { + policyAdapter.setRiskLevel(value); + } + if (("guard").equals(attributeId)) { + policyAdapter.setGuard(value); + } + if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); } } } } } + /** + * setFWViewRule. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + */ @RequestMapping( value = {"/policyController/ViewFWPolicyRule.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) @@ -467,10 +461,8 @@ public class CreateFirewallController extends RestrictedBaseController { response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); String responseString = mapper.writeValueAsString(displayString); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); + response.getWriter().write(new JSONObject("{policyData: " + responseString + "}").toString()); return null; } catch (Exception e) { policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); @@ -481,13 +473,13 @@ public class CreateFirewallController extends RestrictedBaseController { private String constructJson(PolicyRestAdapter policyData) { int ruleCount = 1; // Maps to assosciate the values read from the TermList dictionary - Map srcIP_map = null; - Map destIP_map = null; - Map srcPort_map = null; - Map destPort_map = null; - Map action_map = null; - Map fromZone_map = null; - Map toZone_map = null; + Map mapSrcIp = null; + Map mapDestIP = null; + Map mapSrcPort = null; + Map mapDestPort = null; + Map mapAction = null; + Map mapFromZone = null; + Map mapToZone = null; String ruleDesc = null; String ruleFromZone = null; @@ -513,7 +505,7 @@ public class CreateFirewallController extends RestrictedBaseController { List tagList = null; ServiceListJson targetSl = null; AddressMembers addressMembersJson = null; - int i = 0; + int intCounter = 0; try { String networkRole = ""; for (String tag : tagCollectorList) { @@ -542,10 +534,10 @@ public class CreateFirewallController extends RestrictedBaseController { } tags.setTags(tagList); tags.setTagPickerName(tag); - tags.setRuleName(termCollectorList.get(i)); + tags.setRuleName(termCollectorList.get(intCounter)); tags.setNetworkRole(networkRole); tagsList.add(tags); - i++; + intCounter++; } tc.setRuleToTag(tagsList); @@ -564,47 +556,47 @@ public class CreateFirewallController extends RestrictedBaseController { ruleFromZone = jpaTermList.getFromZone(); if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())) { - fromZone_map = new HashMap<>(); - fromZone_map.put(tl, ruleFromZone); + mapFromZone = new HashMap<>(); + mapFromZone.put(tl, ruleFromZone); } ruleToZone = jpaTermList.getToZone(); if ((ruleToZone != null) && (!ruleToZone.isEmpty())) { - toZone_map = new HashMap<>(); - toZone_map.put(tl, ruleToZone); + mapToZone = new HashMap<>(); + mapToZone.put(tl, ruleToZone); } ruleSrcPrefixList = jpaTermList.getSrcIPList(); if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())) { - srcIP_map = new HashMap<>(); - srcIP_map.put(tl, ruleSrcPrefixList); + mapSrcIp = new HashMap<>(); + mapSrcIp.put(tl, ruleSrcPrefixList); } ruleDestPrefixList = jpaTermList.getDestIPList(); if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())) { - destIP_map = new HashMap<>(); - destIP_map.put(tl, ruleDestPrefixList); + mapDestIP = new HashMap<>(); + mapDestIP.put(tl, ruleDestPrefixList); } ruleSrcPort = jpaTermList.getSrcPortList(); if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())) { - srcPort_map = new HashMap<>(); - srcPort_map.put(tl, ruleSrcPort); + mapSrcPort = new HashMap<>(); + mapSrcPort.put(tl, ruleSrcPort); } ruleDestPort = jpaTermList.getDestPortList(); if (ruleDestPort != null && (!jpaTermList.getDestPortList().isEmpty())) { - destPort_map = new HashMap<>(); - destPort_map.put(tl, ruleDestPort); + mapDestPort = new HashMap<>(); + mapDestPort.put(tl, ruleDestPort); } ruleAction = jpaTermList.getAction(); if ((ruleAction != null) && (!ruleAction.isEmpty())) { - action_map = new HashMap<>(); - action_map.put(tl, ruleAction); + mapAction = new HashMap<>(); + mapAction.put(tl, ruleAction); } } } @@ -613,32 +605,32 @@ public class CreateFirewallController extends RestrictedBaseController { targetTerm.setNegateSource(false); targetTerm.setNegateDestination(false); - if (action_map != null) { - targetTerm.setAction(action_map.get(tl)); + if (mapAction != null) { + targetTerm.setAction(mapAction.get(tl)); } // FromZone arrays - if (fromZone_map != null) { + if (mapFromZone != null) { List fromZone = new ArrayList<>(); - for (String fromZoneStr : fromZone_map.get(tl).split(",")) { + for (String fromZoneStr : mapFromZone.get(tl).split(",")) { fromZone.add(fromZoneStr); } targetTerm.setFromZones(fromZone); } // ToZone arrays - if (toZone_map != null) { + if (mapToZone != null) { List toZone = new ArrayList<>(); - for (String toZoneStr : toZone_map.get(tl).split(",")) { + for (String toZoneStr : mapToZone.get(tl).split(",")) { toZone.add(toZoneStr); } targetTerm.setToZones(toZone); } // Destination Services. - if (destPort_map != null) { + if (mapDestPort != null) { Set destServicesJsonList = new HashSet<>(); - for (String destServices : destPort_map.get(tl).split(",")) { + for (String destServices : mapDestPort.get(tl).split(",")) { ServicesJson destServicesJson = new ServicesJson(); destServicesJson.setType("REFERENCE"); if (destServices.equals(ANY)) { @@ -657,19 +649,19 @@ public class CreateFirewallController extends RestrictedBaseController { targetTerm.setDestServices(destServicesJsonList); } // ExpandableServicesList - if ((srcPort_map != null) && (destPort_map != null)) { - String servicesCollateString = srcPort_map.get(tl) + "," + destPort_map.get(tl); + if ((mapSrcPort != null) && (mapDestPort != null)) { + String servicesCollateString = mapSrcPort.get(tl) + "," + mapDestPort.get(tl); expandableServicesList.add(servicesCollateString); - } else if (srcPort_map != null) { - expandableServicesList.add(srcPort_map.get(tl)); - } else if (destPort_map != null) { - expandableServicesList.add(destPort_map.get(tl)); + } else if (mapSrcPort != null) { + expandableServicesList.add(mapSrcPort.get(tl)); + } else if (mapDestPort != null) { + expandableServicesList.add(mapDestPort.get(tl)); } - if (srcIP_map != null) { + if (mapSrcIp != null) { // Source List List sourceListArrayJson = new ArrayList<>(); - for (String srcList : srcIP_map.get(tl).split(",")) { + for (String srcList : mapSrcIp.get(tl).split(",")) { AddressJson srcListJson = new AddressJson(); if (srcList.equals(ANY)) { srcListJson.setType("any"); @@ -687,10 +679,10 @@ public class CreateFirewallController extends RestrictedBaseController { } targetTerm.setSourceList(sourceListArrayJson); } - if (destIP_map != null) { + if (mapDestIP != null) { // Destination List List destListArrayJson = new ArrayList<>(); - for (String destList : destIP_map.get(tl).split(",")) { + for (String destList : mapDestIP.get(tl).split(",")) { AddressJson destListJson = new AddressJson(); if (destList.equals(ANY)) { destListJson.setType("any"); @@ -709,13 +701,13 @@ public class CreateFirewallController extends RestrictedBaseController { targetTerm.setDestinationList(destListArrayJson); } // ExpandablePrefixIPList - if ((srcIP_map != null) && (destIP_map != null)) { - String collateString = srcIP_map.get(tl) + "," + destIP_map.get(tl); - expandablePrefixIPList.add(collateString); - } else if (srcIP_map != null) { - expandablePrefixIPList.add(srcIP_map.get(tl)); - } else if (destIP_map != null) { - expandablePrefixIPList.add(destIP_map.get(tl)); + if ((mapSrcIp != null) && (mapDestIP != null)) { + String collateString = mapSrcIp.get(tl) + "," + mapDestIP.get(tl); + expandablePrefixIpList.add(collateString); + } else if (mapSrcIp != null) { + expandablePrefixIpList.add(mapSrcIp.get(tl)); + } else if (mapDestIP != null) { + expandablePrefixIpList.add(mapDestIP.get(tl)); } termList.add(targetTerm); targetTerm.setPosition(Integer.toString(ruleCount++)); @@ -800,7 +792,7 @@ public class CreateFirewallController extends RestrictedBaseController { servListArray.add(targetAnyUdp); } - } else {// This is a group + } else { // This is a group GroupServiceList sg; targetSg = new ServiceGroupJson(); sg = mappingServiceGroup(t); @@ -835,15 +827,13 @@ public class CreateFirewallController extends RestrictedBaseController { } } - Set prefixIPList = new HashSet<>(); - for (String prefixList : expandablePrefixIPList) { + Set prefixIpList = new HashSet<>(); + for (String prefixList : expandablePrefixIpList) { for (String prefixIP : prefixList.split(",")) { if (!prefixIP.startsWith(GROUP)) { if (!prefixIP.equals(ANY)) { - List addMembersList = new ArrayList<>(); List valueDesc; PrefixIPList targetAddressList = new PrefixIPList(); - AddressMembers addressMembers = new AddressMembers(); targetAddressList.setName(prefixIP); policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:" + prefixIP); valueDesc = mapping(prefixIP); @@ -852,18 +842,18 @@ public class CreateFirewallController extends RestrictedBaseController { + valueDesc.get(1)); targetAddressList.setDescription(valueDesc.get(1)); } - + AddressMembers addressMembers = new AddressMembers(); addressMembers.setType("SUBNET"); if (!valueDesc.isEmpty()) { addressMembers.setValue(valueDesc.get(0)); } - + List addMembersList = new ArrayList<>(); addMembersList.add(addressMembers); targetAddressList.setMembers(addMembersList); - prefixIPList.add(targetAddressList); + prefixIpList.add(targetAddressList); } - } else {// This is a group + } else { // This is a group AddressGroup ag; addressSg = new AddressGroupJson(); ag = mappingAddressGroup(prefixIP); @@ -874,14 +864,13 @@ public class CreateFirewallController extends RestrictedBaseController { List addrMembersList = new ArrayList<>(); for (String groupString : ag.getPrefixList().split(",")) { - List valueDesc; AddressMembersJson addressMembers = new AddressMembersJson(); addressMembers.setType("REFERENCES"); addressMembers.setName(groupString); addrMembersList.add(addressMembers); // Expand the group Name addressMembersJson = new AddressMembers(); - valueDesc = mapping(groupString); + List valueDesc = mapping(groupString); addressMembersJson.setName(groupString); addressMembersJson.setType("SUBNET"); @@ -909,7 +898,7 @@ public class CreateFirewallController extends RestrictedBaseController { Set addressGroup = new HashSet<>(); - for (Object addObj : prefixIPList) { + for (Object addObj : prefixIpList) { addressGroup.add(addObj); } @@ -925,9 +914,8 @@ public class CreateFirewallController extends RestrictedBaseController { tc.setAddressGroups(addressGroup); tc.setFirewallRuleList(termList); - ObjectWriter om = new ObjectMapper().writer(); try { - json = om.writeValueAsString(tc); + json = new ObjectMapper().writer().writeValueAsString(tc); } catch (JsonGenerationException e) { policyLogger.error("JsonGenerationException Ocured", e); } catch (JsonMappingException e) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java index 74a1ed016..afe2ce193 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java @@ -34,7 +34,6 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; @@ -144,6 +143,13 @@ public class CreateOptimizationController extends RestrictedBaseController { private Map> arrayTextList = new HashMap<>(); CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + /** + * setDataToPolicyRestAdapter. + * + * @param policyData PolicyRestAdapter + * @param root JsonNode + * @return PolicyRestAdapter + */ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { String jsonContent = null; try { @@ -559,30 +565,9 @@ public class CreateOptimizationController extends RestrictedBaseController { if (target == null) { return; } - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList == null) { - continue; - } - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList == null) { - continue; - } - Iterator iterMatch = matchList.iterator(); - while (matchList.size() > 1 && iterMatch.hasNext()) { - MatchType match = iterMatch.next(); + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + for (MatchType match : allOf.getMatch()) { // // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. @@ -843,9 +828,6 @@ public class CreateOptimizationController extends RestrictedBaseController { classMap.putAll(tempMap); LOGGER.info(tempMap); - - return; - } private List listModelFiles(String directoryName) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java index be9910c24..711228574 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java @@ -22,7 +22,6 @@ package org.onap.policy.controller; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -85,26 +84,17 @@ public class CreatePolicyController extends RestrictedBaseController { // if (target != null) { // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); + for (AnyOfType anyOf : target.getAnyOf()) { // Under AnyOFType we have AllOFType // // NOTE: anyOf.getAllOf() will NEVER return null // - List allOfList = anyOf.getAllOf(); - Iterator iterAllOf = allOfList.iterator(); int index = 0; - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); + for (AllOfType allOf : anyOf.getAllOf()) { // Under AllOFType we have Match // NOTE: allOf.getMatch() will NEVER be NULL // - List matchList = allOf.getMatch(); - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); + for (MatchType match : allOf.getMatch()) { // // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. @@ -149,10 +139,10 @@ public class CreatePolicyController extends RestrictedBaseController { policyAdapter.setAttributes(attributeList); } List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - for (Object o : ruleList) { - if (o instanceof RuleType) { + for (Object object : ruleList) { + if (object instanceof RuleType) { // get the condition data under the rule for rule Algorithms. - policyAdapter.setRuleID(((RuleType) o).getRuleId()); + policyAdapter.setRuleID(((RuleType) object).getRuleId()); } } } 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 d12cbb2d4..8ecf3692d 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 @@ -122,237 +122,223 @@ public class DecisionPolicyController extends RestrictedBaseController { 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:")); + return; + } + RainyDayParams rainydayParams = new RainyDayParams(); + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - } catch (Exception e) { - policyLogger.info("General error", e); - description = policy.getDescription(); + 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.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) { - continue; - } - 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); - } + 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) { + rainydayParams.setTreatmentTableChoices(treatmentList); + policyAdapter.setRainyday(rainydayParams); + policyAdapter.setSettings(decisionList); + return; + } + // under target we have AnyOFType + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + int index = 0; + for (MatchType match : allOf.getMatch()) { + // + // 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\\)", ""); } - // 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; - } - } + 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); } - if (rainy) { - policyAdapter.setRuleProvider("Rainy_Day"); + // 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); + String key = map.get("key"); + if ("WorkStep".equals(key)) { + rainydayParams.setWorkstep(map.get("value")); + rainy = true; + } else if ("BB_ID".equals(key)) { + rainydayParams.setBbid(map.get("value")); + rainy = true; + } else if ("ServiceType".equals(key)) { + rainydayParams.setServiceType(map.get("value")); + rainy = true; + } else if ("VNFType".equals(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()); + 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 if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider(GUARD_MIN_MAX); } - 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 if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() - .getAdviceExpression().get(0).getAdviceId())) { - policyAdapter.setRuleProvider(GUARD_MIN_MAX); + } 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())) + || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) { + YAMLParams yamlParams = new YAMLParams(); + for (int i = 0; i < attributeList.size(); i++) { + Map map = (Map) attributeList.get(i); + String key = map.get("key"); + if ("actor".equals(key)) { + yamlParams.setActor(map.get("value")); + } else if ("recipe".equals(key)) { + yamlParams.setRecipe(map.get("value")); + } else if ("target".equals(key)) { + yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); + } else if ("clname".equals(key)) { + yamlParams.setClname(map.get("value")); + } else if ("min".equals(key)) { + yamlParams.setMin(map.get("value")); + } else if ("max".equals(key)) { + yamlParams.setMax(map.get("value")); } - } 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())) - || (GUARD_MIN_MAX.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")); - } else if ("min".equals(map.get("key"))) { - yamlParams.setMin(map.get("value")); - } else if ("max".equals(map.get("key"))) { - yamlParams.setMax(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; + 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(); + List blackList = new ArrayList<>(); + for (JAXBElement attr : apply.getExpression()) { + blackList.add(((AttributeValueType) attr.getValue()) + .getContent().get(0).toString()); } - // Populating Rule Algorithms starting from compound. - prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + 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(':'))); } - } else if (policyAdapter.getRuleProvider() != null - && "Rainy_Day".equals(policyAdapter.getRuleProvider()) - && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { + 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(); + 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(); + 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); + prePopulateRainyDayTreatments(errorcode, treatment); - } - } } } - - rainydayParams.setTreatmentTableChoices(treatmentList); - policyAdapter.setRainyday(rainydayParams); - policyAdapter.setSettings(decisionList); } + rainydayParams.setTreatmentTableChoices(treatmentList); + policyAdapter.setRainyday(rainydayParams); + policyAdapter.setSettings(decisionList); } private void prePopulateRainyDayTreatments(String errorcode, String treatment) { @@ -417,36 +403,36 @@ public class DecisionPolicyController extends RestrictedBaseController { 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; - } + if (! isCompoundRule) { + return index; + } + // 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++; } - return 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); + + return ++index; } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java index 1cfdbb736..b50ca6d94 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -85,7 +85,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to Export the Black List entries data from Decision BlackList Guard YAML Policy. So, user can * update the file on adding or removing the entries, for updating the policies or using in other Environments. - * + * * @param request the request contains the policy data. So, based on that we can populate and read and write the * entries. * @param response after reading and writing the blacklist list entries to file, the file is copied to tmp directory @@ -118,7 +118,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /* * Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate. - * + * */ SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @@ -164,7 +164,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to import the BlackList excel file into the system. Which is used to create Decision * Blacklist Guard YAML Policy. - * + * * @param request the HTTP request contains file upload stream form GUI. * @param response the response is send to the GUI after reading the file input stream. */ @@ -182,9 +182,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr } else { readItems(items, errorLogs, model); } - JsonMessage msg = new JsonMessage(mapper.toJson(model)); - JSONObject jsonResposne = new JSONObject(msg); - response.getWriter().write(jsonResposne.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.toJson(model))).toString()); } catch (FileUploadException | IOException e) { policyLogger.error("Exception Occured while importing the BlackListEntry", e); } @@ -192,7 +190,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the first item, as we expect only one entry in the file upload. - * + * * @param items The file entries which were uploaded from GUI. * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. * @param model Map which stores key value (blacklist and append list data) @@ -219,7 +217,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the workbook in xls file item. - * + * * @param fileName fileName as input parameter * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. * @param model Map which stores key value (blacklist and append list data) @@ -247,7 +245,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read all the rows from imported Excel sheet and set to respective objects. - * + * * @param rowIterator Excel Sheet rows are passed as input parameters. * @param blackListEntries the data is set to this object, which is going to be added. * @param appendBlackListEntries the data is set to this object which is going to be removed. @@ -267,7 +265,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read all the cells in the row. - * + * * @param cellIterator iterating the cells and will parse based on the cell type. * @param blackListEntries the data is set to this object, which is going to be added. * @param appendBlackListEntries the data is set to this object which is going to be removed. @@ -301,7 +299,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the Action cell entry. - * + * * @param cell reading the action entry cell. * @param lineNo counts the number of the cell. * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. @@ -329,7 +327,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the BlackList cell entry. - * + * * @param cell reading the blacklist entry cell. * @param lineNo counts the number of the cell. * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. @@ -354,7 +352,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to add the data to blacklist and append list after parsing each and every row. - * + * * @param actionEntry it has the input to add or not and holds either 0 or 1. * @param blackListEntries list to add blacklist entries based on action entry = 1. * @param appendBlackListEntries list to add append list entries based on action entry = 0. @@ -371,7 +369,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to identify the header of the cell. - * + * * @param cell Excel sheet cell is passed as input parameter. * @return the column header name value */ diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java index 6c1969cdd..ae866c44a 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java @@ -47,7 +47,6 @@ import org.onap.policy.model.PDPGroupContainer; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.OnapPDPGroup; -import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import org.onap.policy.xacml.std.pap.StdPDP; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.portalsdk.core.controller.RestrictedBaseController; @@ -99,8 +98,8 @@ public class PDPController extends RestrictedBaseController { String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId(); List userRoles = controller.getRoles(userId); Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; - scopes = pair.t; + roles = pair.second; + scopes = pair.first; if (!junit && controller.getPapEngine() == null) { setPapEngine(request); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 40f6be8d7..7769ac7d0 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -435,7 +435,7 @@ public class PolicyController extends RestrictedBaseController { } else { userRoles = getRoles(userId); Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; + roles = pair.second; if (!roles.contains(filteredRole)) { savePolicyRoles(name, filteredRole, userId); } @@ -981,10 +981,10 @@ public class PolicyController extends RestrictedBaseController { * @return */ public String convertDate(String dateTimeToLive) { - String formateDate = null; + String formatDate = null; if (dateTimeToLive.contains("-")) { - formateDate = dateTimeToLive.replace("-", "/"); + formatDate = dateTimeToLive.replace("-", "/"); } - return formateDate; + return formatDate; } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java index 77deeb5f3..380341ffa 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java @@ -268,8 +268,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { // Check if the Role and Scope Size are Null get the values from db. List userRoles = controller.getRoles(userId); Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - List roles = pair.u; - Set scopes = pair.t; + List roles = pair.second; + Set scopes = pair.first; try (FileInputStream excelFile = new FileInputStream(new File(file)); HSSFWorkbook workbook = new HSSFWorkbook(excelFile)) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java index 4e16a0ab4..4fa848edd 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java @@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java index abd7f0e22..a4b2c88d2 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -221,8 +221,8 @@ public class CommonClassDaoImpl implements CommonClassDao { Transaction tx = session.beginTransaction(); List rolesData = null; try { - Criteria cr = session.createCriteria(PolicyRoles.class); - Disjunction disjunction = Restrictions.disjunction(); + final Criteria cr = session.createCriteria(PolicyRoles.class); + final Disjunction disjunction = Restrictions.disjunction(); Conjunction conjunction1 = Restrictions.conjunction(); conjunction1.add(Restrictions.eq("role", "admin")); Conjunction conjunction2 = Restrictions.conjunction(); @@ -318,10 +318,12 @@ public class CommonClassDaoImpl implements CommonClassDao { @Override public void updateClAlarms(String arg0, String arg1) { + // why is there no code here? } @Override public void updateClYaml(String arg0, String arg1) { + // why is there no code here? } @Override diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java index c02d3b1d6..6c4fd7e91 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java @@ -113,6 +113,9 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return itemId instanceof OnapPDPGroup; } + /** + * refreshGroups. + */ public synchronized void refreshGroups() { synchronized (this.groups) { this.groups.clear(); @@ -134,6 +137,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return Collections.unmodifiableList(this.groups); } + /** + * makeDefault. + * + * @param group OnapPDPGroup + */ public void makeDefault(OnapPDPGroup group) { try { this.papEngine.setDefaultGroup(group); @@ -144,6 +152,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return; } + /** + * removeGroup. + * + * @param group OnapPDPGroup + * @param newGroup OnapPDPGroup + * @throws PAPException PAPException + */ public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup); @@ -159,6 +174,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } } + /** + * removePDP. + * + * @param pdp OnapPDP + * @param group OnapPDPGroup + * @throws PAPException PAPException + */ public void removePDP(OnapPDP pdp, OnapPDPGroup group) throws PAPException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("removePDP: " + pdp + " from group: " + group); @@ -171,6 +193,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } } + /** + * updatePDP. + * + * @param pdp OnapPDP + */ public void updatePDP(OnapPDP pdp) { try { papEngine.updatePDP(pdp); @@ -179,6 +206,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } } + /** + * updateGroup. + * + * @param group OnapPDPGroup + */ public void updateGroup(OnapPDPGroup group) { try { papEngine.updateGroup(group); @@ -216,6 +248,17 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return Collections.unmodifiableCollection(items); } + @Override + public List getItemIds(int startIndex, int numberOfItems) { + synchronized (this.groups) { + int endIndex = startIndex + numberOfItems; + if (endIndex > this.groups.size()) { + endIndex = this.groups.size() - 1; + } + return this.groups.subList(startIndex, endIndex); + } + } + @Override public Class getType(Object propertyId) { if (propertyId.equals(PROPERTY_ID)) { @@ -269,6 +312,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier throw new UnsupportedOperationException("PDP Container cannot add a given item."); } + /** + * addNewGroup. + * + * @param name String + * @param description String + * @throws PAPException PAPException + */ public void addNewGroup(String name, String description) throws PAPException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("addNewGroup " + name + " " + description); @@ -276,6 +326,16 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier this.papEngine.newGroup(name, description); } + /** + * addNewPDP. + * + * @param id String + * @param group OnapPDPGroup + * @param name String + * @param description String + * @param jmxport int + * @throws PAPException PAPException + */ public void addNewPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException { if (LOGGER.isTraceEnabled()) { @@ -284,6 +344,12 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier this.papEngine.newPDP(id, group, name, description, jmxport); } + /** + * movePDP. + * + * @param pdp OnapPDP + * @param group OnapPDPGroup + */ public void movePDP(OnapPDP pdp, OnapPDPGroup group) { try { this.papEngine.movePDP(pdp, group); @@ -427,17 +493,6 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return this.groups.get(index); } - @Override - public List getItemIds(int startIndex, int numberOfItems) { - synchronized (this.groups) { - int endIndex = startIndex + numberOfItems; - if (endIndex > this.groups.size()) { - endIndex = this.groups.size() - 1; - } - return this.groups.subList(startIndex, endIndex); - } - } - @Override public Object addItemAt(int index) { throw new UnsupportedOperationException("Cannot addItemAt"); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java index 22c44863b..f9f93c0ff 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -36,18 +36,18 @@ public final class UserUtils { } public static class Pair { - public final T t; - public final U u; + public final T first; + public final U second; - public Pair(T t, U u) { - this.t = t; - this.u = u; + public Pair(T first, U second) { + this.first = first; + this.second = second; } } /** * Check Role and its Scopes. - * + * * @param userRoles list of UserRoles. * @return return role and scope from UserRole Object. */ @@ -76,7 +76,7 @@ public final class UserUtils { /** * Get Role by Scope based on UserRole Object. - * + * * @param userRoles list of UserRoles. * @return return the map. */ @@ -95,7 +95,7 @@ public final class UserUtils { /** * Read non super role scopes and add to map. - * + * * @param userRole Role Object. * @param rolesList roleList Object. * @return return the map. @@ -116,7 +116,7 @@ public final class UserUtils { /** * Trim Scope Value. - * + * * @param scope string scope name. * @return trim scope. */ diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java index 3bd48d67a..2f079f139 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java @@ -31,6 +31,10 @@ import org.mockito.Mockito; import org.onap.policy.controller.PolicyController; public class HibernateSessionTest { + + /** + * setup. + */ @Before public void setup() { PolicyController.setLogdbUrl("testURL"); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java index 3bc89c9d0..16c53841c 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java @@ -64,6 +64,11 @@ public class CommonClassDaoImplTest { Server server; CommonClassDaoImpl commonClassDao; + /** + * setUp. + * + * @throws Exception Exception + */ @Before public void setUp() throws Exception { try { @@ -148,17 +153,17 @@ public class CommonClassDaoImplTest { try { // Add data UserInfo userinfo = new UserInfo(); - String loginId_userName = "Test"; - userinfo.setUserLoginId(loginId_userName); - userinfo.setUserName(loginId_userName); + String loginIdUserName = "Test"; + userinfo.setUserLoginId(loginIdUserName); + userinfo.setUserName(loginIdUserName); commonClassDao.save(userinfo); List dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings()); assertEquals(1, dataCur.size()); UserInfo cur = (UserInfo) dataCur.get(0); - assertEquals(loginId_userName, cur.getUserLoginId()); - assertEquals(loginId_userName, cur.getUserName()); + assertEquals(loginIdUserName, cur.getUserLoginId()); + assertEquals(loginIdUserName, cur.getUserName()); assertFalse(dataCur.isEmpty()); @@ -190,7 +195,7 @@ public class CommonClassDaoImplTest { assertTrue(1 == dataCur.size()); assertTrue(dataCur.get(0) instanceof PolicyEntity); assertEquals(name, ((PolicyEntity) dataCur.get(0)).getPolicyName()); - assertEquals(pe, ((PolicyEntity) dataCur.get(0))); + assertEquals(pe, (dataCur.get(0))); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -229,7 +234,7 @@ public class CommonClassDaoImplTest { List dataCur = commonClassDao.getDataByQuery(query, params); assertTrue(1 == dataCur.size()); - assertEquals(pv, (PolicyVersion) dataCur.get(0)); + assertEquals(pv, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -244,11 +249,11 @@ public class CommonClassDaoImplTest { try { // Add data WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - String policyFileName = "banana"; watch.setLoginIds("Test"); watch.setPolicyName("bananaWatch"); commonClassDao.save(watch); + String policyFileName = "banana"; if (policyFileName.contains("/")) { policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); policyFileName = policyFileName.replace("/", File.separator); @@ -268,7 +273,7 @@ public class CommonClassDaoImplTest { // Assertions assertTrue(dataCur.size() == 1); assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); + assertEquals(watch, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -294,19 +299,19 @@ public class CommonClassDaoImplTest { commonClassDao.save(pe); String dbCheckName = "dummyScope:action"; - String[] splitDBCheckName = dbCheckName.split(":"); // Current Implementation String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; SimpleBindings params = new SimpleBindings(); - params.put("splitDBCheckName1", splitDBCheckName[1] + "%"); - params.put("splitDBCheckName0", splitDBCheckName[0]); + String[] splitDbCheckName = dbCheckName.split(":"); + params.put("splitDBCheckName1", splitDbCheckName[1] + "%"); + params.put("splitDBCheckName0", splitDbCheckName[0]); List dataCur = commonClassDao.getDataByQuery(query, params); // Assertions assertTrue(dataCur.size() == 1); assertTrue(dataCur.get(0) instanceof PolicyEntity); - assertEquals(pe, (PolicyEntity) dataCur.get(0)); + assertEquals(pe, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -337,7 +342,7 @@ public class CommonClassDaoImplTest { // Assertions assertTrue(dataCur.size() == 1); assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); + assertEquals(watch, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -381,8 +386,8 @@ public class CommonClassDaoImplTest { if (dataCur.size() >= 1) { assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); - assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); + assertFalse(watch.equals(dataCur.get(0))); + assertFalse(watch.equals(dataCur.get(0))); } } catch (Exception e) { logger.debug("Exception Occured" + e);