From 558b5a4779918ca76d6465754ae7650c6d9e2694 Mon Sep 17 00:00:00 2001 From: mmis Date: Mon, 12 Feb 2018 11:54:51 +0000 Subject: Fix technical debt/JUnit on policy-yaml Unit tests added and technical debt removed Issue-ID: POLICY-455 Change-Id: I31566f9386cb94d78e9af3d6261e31b9cad1cb53 Signed-off-by: mmis --- .../controlloop/compiler/ControlLoopCompiler.java | 450 ++++++++++++--------- .../guard/compiler/ControlLoopGuardCompiler.java | 19 +- .../policy/controlloop/policy/ControlLoop.java | 70 ++-- .../org/onap/policy/controlloop/policy/Policy.java | 187 +++------ .../policy/builder/ControlLoopPolicyBuilder.java | 3 +- .../builder/impl/ControlLoopPolicyBuilderImpl.java | 210 +++++----- .../policy/builder/impl/ResultsImpl.java | 2 +- .../controlloop/policy/guard/Constraint.java | 104 +++-- .../controlloop/policy/guard/GuardPolicy.java | 73 ++-- .../controlloop/policy/guard/MatchParameters.java | 33 +- .../guard/builder/ControlLoopGuardBuilder.java | 3 +- .../builder/impl/ControlLoopGuardBuilderImpl.java | 16 +- .../compiler/CompilerExceptionTest.java | 30 ++ .../compiler/ControlLoopCompilerTest.java | 167 ++++++-- .../policy/ControlLoopPolicyBuilderTest.java | 363 ++++++++++++++++- .../policy/controlloop/policy/ControlLoopTest.java | 171 ++++++++ .../policy/OperationsAccumulateParamsTest.java | 116 ++++++ .../controlloop/policy/guard/ConstraintTest.java | 249 ++++++++++++ .../policy/guard/ControlLoopGuardTest.java | 64 +++ .../controlloop/policy/guard/GuardPolicyTest.java | 267 ++++++++++++ .../bad_control_loop_no_control_loop_name.yaml | 23 ++ .../src/test/resources/v1.0.0/bad_policies_1.yaml | 25 -- ...policy_failure_connected_to_unknown_policy.yaml | 23 ++ ...lure_exception_connected_to_unknown_policy.yaml | 23 ++ ..._failure_guard_connected_to_unknown_policy.yaml | 23 ++ ...ailure_retries_connected_to_unknown_policy.yaml | 23 ++ ...ailure_timeout_connected_to_unknown_policy.yaml | 23 ++ ...policy_success_connected_to_unknown_policy.yaml | 23 ++ .../v1.0.0/bad_trigger_no_trigger_id.yaml | 21 + .../src/test/resources/v1.0.0/empty.yaml | 0 .../src/test/resources/v1.0.0/test.yaml | 273 +++++++++++-- 31 files changed, 2372 insertions(+), 705 deletions(-) create mode 100644 controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java create mode 100644 controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java create mode 100644 controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/OperationsAccumulateParamsTest.java create mode 100644 controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java create mode 100644 controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_control_loop_no_control_loop_name.yaml delete mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policies_1.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_connected_to_unknown_policy.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_exception_connected_to_unknown_policy.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_guard_connected_to_unknown_policy.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_retries_connected_to_unknown_policy.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_timeout_connected_to_unknown_policy.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_success_connected_to_unknown_policy.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_no_trigger_id.yaml create mode 100644 controlloop/common/policy-yaml/src/test/resources/v1.0.0/empty.yaml (limited to 'controlloop/common/policy-yaml/src') diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java index 710ca0165..0aa6f2a79 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java @@ -47,8 +47,9 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; public class ControlLoopCompiler implements Serializable{ - private static final long serialVersionUID = 1L; - private static Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName()); + private static final String OPERATION_POLICY = "Operation Policy "; + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName()); public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { // @@ -96,20 +97,10 @@ public class ControlLoopCompiler implements Serializable{ if (policy == null) { throw new CompilerException("policy cannot be null"); } - // - // verify controlLoop overall timeout should be no less than the sum of operational policy timeouts - // if (policy.getPolicies() == null) { callback.onWarning("controlLoop is an open loop."); } else{ - int sum = 0; - for (Policy operPolicy : policy.getPolicies()) { - sum += operPolicy.getTimeout().intValue(); - } - if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) { - callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); - } // // For this version we can use a directed multigraph, in the future we may not be able to // @@ -125,24 +116,11 @@ public class ControlLoopCompiler implements Serializable{ // Did this turn into a FinalResult object? // if (triggerResult != null) { - // - // Ensure they didn't use some other FinalResult code - // - if (triggerResult != FinalResult.FINAL_OPENLOOP) { - throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); - } - // - // They really shouldn't have any policies attached. - // - if ((policy.getPolicies() != null || policy.getPolicies().isEmpty())&& callback != null ) { - callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); - } + validateOpenLoopPolicy(policy, triggerResult, callback); return; // } else { - // - // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be. - // + validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(policy, callback); triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName()); } // @@ -167,34 +145,7 @@ public class ControlLoopCompiler implements Serializable{ // // Work through the policies and add them in as nodes. // - Map mapNodes = new HashMap<>(); - for (Policy operPolicy : policy.getPolicies()) { - // - // Is it still ok to add? - // - if (!okToAdd(operPolicy, callback)) { - // - // Do not add it in - // - continue; - } - // - // Create wrapper policy node and save it into our map so we can - // easily retrieve it. - // - PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); - mapNodes.put(operPolicy, node); - graph.addVertex(node); - // - // Is this the trigger policy? - // - if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) { - // - // Yes add an edge from our trigger event node to this policy - // - graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); - } - } + Map mapNodes = addPoliciesAsNodes(policy, graph, triggerNode, callback); // // last sweep to connect remaining edges for policy results // @@ -206,149 +157,204 @@ public class ControlLoopCompiler implements Serializable{ if (node == null) { continue; } - if (FinalResult.isResult(operPolicy.getSuccess(), FinalResult.FINAL_SUCCESS)) { - graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getSuccess()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " success is connected to unknown policy " + operPolicy.getSuccess()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS))); - } - } - if (FinalResult.isResult(operPolicy.getFailure(), FinalResult.FINAL_FAILURE)) { - graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure is connected to unknown policy " + operPolicy.getFailure()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_timeout(), FinalResult.FINAL_FAILURE_TIMEOUT)) { - graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_timeout()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_timeout is connected to unknown policy " + operPolicy.getFailure_timeout()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_retries(), FinalResult.FINAL_FAILURE_RETRIES)) { - graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_retries()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_retries is connected to unknown policy " + operPolicy.getFailure_retries()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_exception(), FinalResult.FINAL_FAILURE_EXCEPTION)) { - graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_exception()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_exception is connected to unknown policy " + operPolicy.getFailure_exception()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_guard(), FinalResult.FINAL_FAILURE_GUARD)) { - graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_guard()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_guard is connected to unknown policy " + operPolicy.getFailure_guard()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD))); - } - } - } - // - // Now validate all the nodes/edges - // - for (NodeWrapper node : graph.vertexSet()) { - if (node instanceof TriggerNodeWrapper) { - LOGGER.info("Trigger Node " + node.toString()); - if (graph.inDegreeOf(node) > 0 ) { - // - // Really should NEVER get here unless someone messed up the code above. - // - throw new CompilerException("No inputs to event trigger"); - } - // - // Should always be 1, except in the future we may support multiple events - // - if (graph.outDegreeOf(node) > 1) { - throw new CompilerException("The event trigger should only go to ONE node"); - } - } else if (node instanceof FinalResultNodeWrapper) { - LOGGER.info("FinalResult Node " + node.toString()); - // - // FinalResult nodes should NEVER have an out edge - // - if (graph.outDegreeOf(node) > 0) { - throw new CompilerException("FinalResult nodes should never have any out edges."); - } - } else if (node instanceof PolicyNodeWrapper) { - LOGGER.info("Policy Node " + node.toString()); - // - // All Policy Nodes should have the 5 out degrees defined. - // - if (graph.outDegreeOf(node) != 6) { - throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); - } - // - // All Policy Nodes should have at least 1 in degrees - // - if (graph.inDegreeOf(node) == 0 && callback != null) { - callback.onWarning("Policy " + node.getID() + " is not reachable."); - } - } - for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ - LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); - } + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess, PolicyResult.SUCCESS, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure, PolicyResult.FAILURE, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout, PolicyResult.FAILURE_TIMEOUT, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries, PolicyResult.FAILURE_RETRIES, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException, PolicyResult.FAILURE_EXCEPTION, node); + addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard, PolicyResult.FAILURE_GUARD, node); } + validateNodesAndEdges(graph, callback); } } - private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) { + private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult, ControlLoopCompilerCallback callback) throws CompilerException{ // - // Check the policy id and make sure its sane + // Ensure they didn't use some other FinalResult code // - boolean okToAdd = true; - if (operPolicy.getId() == null || operPolicy.getId().length() < 1) { - if (callback != null) { - callback.onError("Operational Policy has an bad ID"); - } - okToAdd = false; + if (triggerResult != FinalResult.FINAL_OPENLOOP) { + throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); } // - // Check if they decided to make the ID a result object + // They really shouldn't have any policies attached. // - if (PolicyResult.toResult(operPolicy.getId()) != null) { - if (callback != null) { - callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId()); + if ((policy.getPolicies() != null || policy.getPolicies().isEmpty())&& callback != null ) { + callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); + } + } + + private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException{ + int sum = 0; + boolean triggerPolicyFound = false; + for (Policy operPolicy : policy.getPolicies()) { + sum += operPolicy.getTimeout().intValue(); + if (policy.getControlLoop().getTrigger_policy().equals(operPolicy.getId())){ + triggerPolicyFound = true; } - okToAdd = false; } - if (FinalResult.toResult(operPolicy.getId()) != null) { - if (callback != null) { - callback.onError("Policy id is set to a FinalResult " + operPolicy.getId()); + if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) { + callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); + } + + if (!triggerPolicyFound){ + throw new CompilerException("Unexpected value for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); + } + } + + private static Map addPoliciesAsNodes(ControlLoopPolicy policy, + DirectedGraph graph, TriggerNodeWrapper triggerNode, ControlLoopCompilerCallback callback){ + Map mapNodes = new HashMap<>(); + for (Policy operPolicy : policy.getPolicies()) { + // + // Is it still ok to add? + // + if (!okToAdd(operPolicy, callback)) { + // + // Do not add it in + // + continue; + } + // + // Create wrapper policy node and save it into our map so we can + // easily retrieve it. + // + PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); + mapNodes.put(operPolicy, node); + graph.addVertex(node); + // + // Is this the trigger policy? + // + if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) { + // + // Yes add an edge from our trigger event node to this policy + // + graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); } - okToAdd = false; + } + return mapNodes; + } + + private static void addEdge(DirectedGraph graph, Map mapNodes, String policyId, String connectedPolicy, + FinalResultNodeWrapper finalResultNodeWrapper, PolicyResult policyResult, NodeWrapper node) throws CompilerException{ + FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getID()); + if (FinalResult.isResult(connectedPolicy, finalResult)) { + graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper, new FinalResultEdgeWrapper(finalResult))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy); + if (toNode == null) { + throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy " + connectedPolicy); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult))); + } + } + } + + private static void validateNodesAndEdges(DirectedGraph graph, ControlLoopCompilerCallback callback) throws CompilerException{ + for (NodeWrapper node : graph.vertexSet()) { + if (node instanceof TriggerNodeWrapper) { + validateTriggerNodeWrapper(graph, node); + } else if (node instanceof FinalResultNodeWrapper) { + validateFinalResultNodeWrapper(graph, node); + } else if (node instanceof PolicyNodeWrapper) { + validatePolicyNodeWrapper(graph, node, callback); + } + for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ + LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); + } + } + } + + private static void validateTriggerNodeWrapper(DirectedGraph graph, NodeWrapper node) throws CompilerException{ + if (LOGGER.isDebugEnabled()) { + LOGGER.info("Trigger Node {}", node.toString()); + } + if (graph.inDegreeOf(node) > 0 ) { + // + // Really should NEVER get here unless someone messed up the code above. + // + throw new CompilerException("No inputs to event trigger"); + } + // + // Should always be 1, except in the future we may support multiple events + // + if (graph.outDegreeOf(node) > 1) { + throw new CompilerException("The event trigger should only go to ONE node"); + } + } + + private static void validateFinalResultNodeWrapper(DirectedGraph graph, NodeWrapper node) throws CompilerException{ + if (LOGGER.isDebugEnabled()) { + LOGGER.info("FinalResult Node {}", node.toString()); + } + // + // FinalResult nodes should NEVER have an out edge + // + if (graph.outDegreeOf(node) > 0) { + throw new CompilerException("FinalResult nodes should never have any out edges."); + } + } + + private static void validatePolicyNodeWrapper(DirectedGraph graph, NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException{ + if (LOGGER.isDebugEnabled()) { + LOGGER.info("Policy Node {}", node.toString()); } // - // Check that the actor/recipe/target are valid + // All Policy Nodes should have the 5 out degrees defined. + // + if (graph.outDegreeOf(node) != 6) { + throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); + } + // + // All Policy Nodes should have at least 1 in degrees // + if (graph.inDegreeOf(node) == 0 && callback != null) { + callback.onWarning("Policy " + node.getID() + " is not reachable."); + } + } + + private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = isPolicyIdOk(operPolicy, callback); + isOk = isActorOk(operPolicy, callback) ? isOk : false; + isOk = isRecipeOk(operPolicy, callback) ? isOk : false; + isOk = isTargetOk(operPolicy, callback) ? isOk : false; + isOk = arePolicyResultsOk(operPolicy, callback) ? isOk : false; + return isOk; + } + + private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; + if (operPolicy.getId() == null || operPolicy.getId().length() < 1) { + if (callback != null) { + callback.onError("Operational Policy has an bad ID"); + } + isOk = false; + } else { + // + // Check if they decided to make the ID a result object + // + if (PolicyResult.toResult(operPolicy.getId()) != null) { + if (callback != null) { + callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId()); + } + isOk = false; + } + if (FinalResult.toResult(operPolicy.getId()) != null) { + if (callback != null) { + callback.onError("Policy id is set to a FinalResult " + operPolicy.getId()); + } + isOk = false; + } + } + return isOk; + } + + private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; if (operPolicy.getActor() == null) { if (callback != null) { callback.onError("Policy actor is null"); } - okToAdd = false; + isOk = false; } // // Construct a list for all valid actors @@ -359,13 +365,18 @@ public class ControlLoopCompiler implements Serializable{ if (callback != null) { callback.onError("Policy actor is invalid"); } - okToAdd = false; + isOk = false; } + return isOk; + } + + private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; if (operPolicy.getRecipe() == null) { if (callback != null) { callback.onError("Policy recipe is null"); } - okToAdd = false; + isOk = false; } // // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these) @@ -382,60 +393,105 @@ public class ControlLoopCompiler implements Serializable{ if (callback != null) { callback.onError("Policy recipe is invalid"); } - okToAdd = false; + isOk = false; } + return isOk; + } + + private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) { + boolean isOk = true; if (operPolicy.getTarget() == null) { if (callback != null) { callback.onError("Policy target is null"); } - okToAdd = false; + isOk = false; } if (operPolicy.getTarget() != null && operPolicy.getTarget().getType() != TargetType.VM && operPolicy.getTarget().getType() != TargetType.VFC && operPolicy.getTarget().getType() != TargetType.PNF) { if (callback != null) { callback.onError("Policy target is invalid"); } - okToAdd = false; + isOk = false; } + return isOk; + } + + private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) { // // Check that policy results are connected to either default final * or another policy // - if (FinalResult.toResult(operPolicy.getSuccess()) != null && operPolicy.getSuccess() != FinalResult.FINAL_SUCCESS.toString()) { + boolean isOk = isSuccessPolicyResultOk(operPolicy, callback); + isOk = isFailurePolicyResultOk(operPolicy, callback) ? isOk : false; + isOk = isFailureRetriesPolicyResultOk(operPolicy, callback) ? isOk : false; + isOk = isFailureTimeoutPolicyResultOk(operPolicy, callback) ? isOk : false; + isOk = isFailureExceptionPolicyResultOk(operPolicy, callback) ? isOk : false; + isOk = isFailureGuardPolicyResultOk(operPolicy, callback) ? isOk : false; + return isOk; + } + + private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){ + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getSuccess()) != null && !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) { if (callback != null) { callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); } - okToAdd = false; + isOk = false; } - if (FinalResult.toResult(operPolicy.getFailure()) != null && operPolicy.getFailure() != FinalResult.FINAL_FAILURE.toString()) { + return isOk; + } + + private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){ + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure()) != null && !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) { if (callback != null) { callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); } - okToAdd = false; + isOk = false; } - if (FinalResult.toResult(operPolicy.getFailure_retries()) != null && operPolicy.getFailure_retries() != FinalResult.FINAL_FAILURE_RETRIES.toString()) { + return isOk; + } + + private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){ + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_retries()) != null && !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) { if (callback != null) { callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); } - okToAdd = false; + isOk = false; } - if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null && operPolicy.getFailure_timeout() != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) { + return isOk; + } + + private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){ + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null && !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) { if (callback != null) { callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); } - okToAdd = false; + isOk = false; } - if (FinalResult.toResult(operPolicy.getFailure_exception()) != null && operPolicy.getFailure_exception() != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) { + return isOk; + } + + private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){ + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_exception()) != null && !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) { if (callback != null) { callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); } - okToAdd = false; + isOk = false; } - if (FinalResult.toResult(operPolicy.getFailure_guard()) != null && operPolicy.getFailure_guard() != FinalResult.FINAL_FAILURE_GUARD.toString()) { + return isOk; + } + + private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback){ + boolean isOk = true; + if (FinalResult.toResult(operPolicy.getFailure_guard()) != null && !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) { if (callback != null) { callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); } - okToAdd = false; + isOk = false; } - return okToAdd; + return isOk; } private static PolicyNodeWrapper findPolicyNode(Map mapNodes, String id) { diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java index 173e3e263..34c97e350 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java @@ -36,7 +36,10 @@ import org.yaml.snakeyaml.constructor.Constructor; public class ControlLoopGuardCompiler { - private ControlLoopGuardCompiler(){ + private static final String GUARD_POLICIES_SHOULD_NOT_BE_NULL = "Guard policies should not be null"; + private static final String GUARD_POLICY = "Guard policy "; + + private ControlLoopGuardCompiler(){ // Private Constructor } @@ -91,9 +94,9 @@ public class ControlLoopGuardCompiler { private static void validateGuardPolicies(List policies, ControlLoopCompilerCallback callback) throws CompilerException { if (policies == null) { if (callback != null) { - callback.onError("Guard policies should not be null"); + callback.onError(GUARD_POLICIES_SHOULD_NOT_BE_NULL); } - throw new CompilerException("Guard policies should not be null"); + throw new CompilerException(GUARD_POLICIES_SHOULD_NOT_BE_NULL); } // // Ensure all guard policies are unique @@ -108,9 +111,9 @@ public class ControlLoopGuardCompiler { for (GuardPolicy policy : policies) { if (policy.getLimit_constraints() == null || policy.getLimit_constraints().isEmpty()) { if (callback != null) { - callback.onError("Guard policy " + policy.getName() + " does not have any limit constraint"); + callback.onError(GUARD_POLICY + policy.getName() + " does not have any limit constraint"); } - throw new CompilerException("Guard policy " + policy.getName() + " does not have any limit constraint"); + throw new CompilerException(GUARD_POLICY + policy.getName() + " does not have any limit constraint"); } } } @@ -118,14 +121,14 @@ public class ControlLoopGuardCompiler { private static void validateConstraints(List policies, ControlLoopCompilerCallback callback) throws CompilerException { if (policies == null) { if (callback != null) { - callback.onError("Guard policies should not be null"); + callback.onError(GUARD_POLICIES_SHOULD_NOT_BE_NULL); } - throw new CompilerException("Guard policies should not be null"); + throw new CompilerException(GUARD_POLICIES_SHOULD_NOT_BE_NULL); } for (GuardPolicy policy : policies) { Set newSet = new HashSet<>(policy.getLimit_constraints()); if (newSet.size() != policy.getLimit_constraints().size() && callback != null) { - callback.onWarning("Guard policy " + policy.getName() + " has duplicate limit constraints"); + callback.onWarning(GUARD_POLICY + policy.getName() + " has duplicate limit constraints"); } } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java index 094e77891..ad6a58b74 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java @@ -29,14 +29,14 @@ import org.onap.policy.sdc.Service; public class ControlLoop { - private static String VERSION = "2.0.0"; + private static final String COMPILER_VERSION = "2.0.0"; private String controlLoopName; - private String version = VERSION; + private String version = COMPILER_VERSION; private List services; private List resources; private PNF pnf; - private String trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + private String triggerPolicy = FinalResult.FINAL_OPENLOOP.toString(); private Integer timeout; private Boolean abatement = false; @@ -45,7 +45,7 @@ public class ControlLoop { } public static String getVERSION(){ - return ControlLoop.VERSION; + return ControlLoop.COMPILER_VERSION; } public String getControlLoopName() { @@ -73,11 +73,11 @@ public class ControlLoop { } public String getTrigger_policy() { - return trigger_policy; + return triggerPolicy; } - public void setTrigger_policy(String trigger_policy) { - this.trigger_policy = trigger_policy; + public void setTrigger_policy(String triggerPolicy) { + this.triggerPolicy = triggerPolicy; } public Integer getTimeout() { @@ -126,14 +126,14 @@ public class ControlLoop { this.resources.add(resource); } } - this.trigger_policy = controlLoop.trigger_policy; + this.triggerPolicy = controlLoop.triggerPolicy; this.timeout = controlLoop.timeout; this.abatement = controlLoop.abatement; } @Override public String toString() { return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + ", services=" + services - + ", resources=" + resources + ", trigger_policy=" + trigger_policy + ", timeout=" + + ", resources=" + resources + ", trigger_policy=" + triggerPolicy + ", timeout=" + timeout + ", abatement=" + abatement + "]"; } @Override @@ -144,7 +144,7 @@ public class ControlLoop { result = prime * result + ((resources == null) ? 0 : resources.hashCode()); result = prime * result + ((services == null) ? 0 : services.hashCode()); result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); - result = prime * result + ((trigger_policy == null) ? 0 : trigger_policy.hashCode()); + result = prime * result + ((triggerPolicy == null) ? 0 : triggerPolicy.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); result = prime * result + ((abatement == null) ? 0 : abatement.hashCode()); return result; @@ -158,42 +158,20 @@ public class ControlLoop { if (getClass() != obj.getClass()) return false; ControlLoop other = (ControlLoop) obj; - if (controlLoopName == null) { - if (other.controlLoopName != null) - return false; - } else if (!controlLoopName.equals(other.controlLoopName)) - return false; - if (resources == null) { - if (other.resources != null) - return false; - } else if (!resources.equals(other.resources)) - return false; - if (services == null) { - if (other.services != null) - return false; - } else if (!services.equals(other.services)) - return false; - if (timeout == null) { - if (other.timeout != null) - return false; - } else if (!timeout.equals(other.timeout)) - return false; - if (trigger_policy == null) { - if (other.trigger_policy != null) - return false; - } else if (!trigger_policy.equals(other.trigger_policy)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - if (abatement == null) { - if (other.abatement != null) - return false; - } else if (!abatement.equals(other.abatement)) - return false; - return true; + return equalsMayBeNull(controlLoopName, other.controlLoopName) + && equalsMayBeNull(resources, other.resources) + && equalsMayBeNull(services, other.services) + && equalsMayBeNull(timeout, other.timeout) + && equalsMayBeNull(triggerPolicy, other.triggerPolicy) + && equalsMayBeNull(version, other.version) + && equalsMayBeNull(abatement, other.abatement); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2){ + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals(obj2); } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java index 03e3416b8..eed6c7c39 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java @@ -38,10 +38,10 @@ public class Policy { private Integer timeout = 300; private String success = FinalResult.FINAL_SUCCESS.toString(); private String failure = FinalResult.FINAL_FAILURE.toString(); - private String failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); - private String failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); - private String failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); - private String failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + private String failureRetries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + private String failureTimeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + private String failureException = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + private String failureGuard = FinalResult.FINAL_FAILURE_GUARD.toString(); public Policy() { @@ -145,35 +145,35 @@ public class Policy { } public String getFailure_retries() { - return failure_retries; + return failureRetries; } - public void setFailure_retries(String failure_retries) { - this.failure_retries = failure_retries; + public void setFailure_retries(String failureRetries) { + this.failureRetries = failureRetries; } public String getFailure_timeout() { - return failure_timeout; + return failureTimeout; } - public void setFailure_timeout(String failure_timeout) { - this.failure_timeout = failure_timeout; + public void setFailure_timeout(String failureTimeout) { + this.failureTimeout = failureTimeout; } public String getFailure_exception() { - return failure_exception; + return failureException; } - public void setFailure_exception(String failure_exception) { - this.failure_exception = failure_exception; + public void setFailure_exception(String failureException) { + this.failureException = failureException; } public String getFailure_guard() { - return failure_guard; + return failureGuard; } - public void setFailure_guard(String failure_guard) { - this.failure_guard = failure_guard; + public void setFailure_guard(String failureGuard) { + this.failureGuard = failureGuard; } public Policy(String id) { @@ -217,49 +217,50 @@ public class Policy { this.timeout = policy.timeout; this.success = policy.success; this.failure = policy.failure; - this.failure_exception = policy.failure_exception; - this.failure_guard = policy.failure_guard; - this.failure_retries = policy.failure_retries; - this.failure_timeout = policy.failure_timeout; + this.failureException = policy.failureException; + this.failureGuard = policy.failureGuard; + this.failureRetries = policy.failureRetries; + this.failureTimeout = policy.failureTimeout; } public boolean isValid() { - if(id==null || name==null || actor==null|| recipe==null || target==null){ - return false; - } - return true; + return id==null || name==null || actor==null|| recipe==null || target==null; } @Override public String toString() { return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams=" + operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout - + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failure_retries - + ", failure_timeout=" + failure_timeout + ", failure_exception=" + failure_exception + ", failure_guard=" + failure_guard + "]"; + + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failureRetries + + ", failure_timeout=" + failureTimeout + ", failure_exception=" + failureException + ", failure_guard=" + failureGuard + "]"; } @Override public int hashCode() { - final int prime = 31; int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((failure == null) ? 0 : failure.hashCode()); - result = prime * result + ((failure_exception == null) ? 0 : failure_exception.hashCode()); - result = prime * result + ((failure_guard == null) ? 0 : failure_guard.hashCode()); - result = prime * result + ((failure_retries == null) ? 0 : failure_retries.hashCode()); - result = prime * result + ((failure_timeout == null) ? 0 : failure_timeout.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((payload == null) ? 0 : payload.hashCode()); - result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); - result = prime * result + ((retry == null) ? 0 : retry.hashCode()); - result = prime * result + ((success == null) ? 0 : success.hashCode()); - result = prime * result + ((target == null) ? 0 : target.hashCode()); - result = prime * result + ((operationsAccumulateParams == null) ? 0 : operationsAccumulateParams.hashCode()); - result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + result = addHashCodeForField(result, actor); + result = addHashCodeForField(result, description); + result = addHashCodeForField(result, failure); + result = addHashCodeForField(result, failureException); + result = addHashCodeForField(result, failureGuard); + result = addHashCodeForField(result, failureRetries); + result = addHashCodeForField(result, failureTimeout); + result = addHashCodeForField(result, id); + result = addHashCodeForField(result, name); + result = addHashCodeForField(result, payload); + result = addHashCodeForField(result, recipe); + result = addHashCodeForField(result, retry); + result = addHashCodeForField(result, success); + result = addHashCodeForField(result, target); + result = addHashCodeForField(result, operationsAccumulateParams); + result = addHashCodeForField(result, timeout); return result; } + + private int addHashCodeForField(int hashCode, Object field){ + final int prime = 31; + return prime * hashCode + ((field == null) ? 0 : field.hashCode()); + } @Override public boolean equals(Object obj) { @@ -270,84 +271,28 @@ public class Policy { if (getClass() != obj.getClass()) return false; Policy other = (Policy) obj; - if (actor != other.actor) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (failure == null) { - if (other.failure != null) - return false; - } else if (!failure.equals(other.failure)) - return false; - if (failure_exception == null) { - if (other.failure_exception != null) - return false; - } else if (!failure_exception.equals(other.failure_exception)) - return false; - if (failure_guard == null) { - if (other.failure_guard != null) - return false; - } else if (!failure_guard.equals(other.failure_guard)) - return false; - if (failure_retries == null) { - if (other.failure_retries != null) - return false; - } else if (!failure_retries.equals(other.failure_retries)) - return false; - if (failure_timeout == null) { - if (other.failure_timeout != null) - return false; - } else if (!failure_timeout.equals(other.failure_timeout)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (payload == null) { - if (other.payload != null) - return false; - } else if (!payload.equals(other.payload)) - return false; - if (recipe == null) { - if (other.recipe != null) - return false; - } else if (!recipe.equals(other.recipe)) - return false; - if (retry == null) { - if (other.retry != null) - return false; - } else if (!retry.equals(other.retry)) - return false; - if (success == null) { - if (other.success != null) - return false; - } else if (!success.equals(other.success)) - return false; - if (operationsAccumulateParams == null) { - if (other.operationsAccumulateParams != null) - return false; - } else if (!operationsAccumulateParams.equals(other.operationsAccumulateParams)) - return false; - if (target == null) { - if (other.target != null) - return false; - } else if (!target.equals(other.target)) - return false; - if (timeout == null) { - if (other.timeout != null) - return false; - } else if (!timeout.equals(other.timeout)) - return false; - return true; + return equalsMayBeNull(actor, other.actor) + && equalsMayBeNull(description, other.description) + && equalsMayBeNull(failure, other.failure) + && equalsMayBeNull(failureException, other.failureException) + && equalsMayBeNull(failureGuard, other.failureGuard) + && equalsMayBeNull(failureRetries, other.failureRetries) + && equalsMayBeNull(id, other.id) + && equalsMayBeNull(name, other.name) + && equalsMayBeNull(payload, other.payload) + && equalsMayBeNull(recipe, other.recipe) + && equalsMayBeNull(retry, other.retry) + && equalsMayBeNull(success, other.success) + && equalsMayBeNull(operationsAccumulateParams, other.operationsAccumulateParams) + && equalsMayBeNull(target, other.target) + && equalsMayBeNull(timeout, other.timeout); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2){ + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals(obj2); } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java index b40e8858e..d1212194d 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java @@ -259,9 +259,8 @@ public interface ControlLoopPolicyBuilder { * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. * @param timeout - Overall timeout for the Closed Loop to execute. * @return ControlLoopPolicyBuilder object - * @throws BuilderException */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) throws BuilderException { + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) { return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout); } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java index 5f5baf0bd..45315b077 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java @@ -47,16 +47,19 @@ import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; +import com.google.common.base.Strings; + public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { + private static final String UNKNOWN_POLICY = "Unknown policy "; private static Logger logger = LoggerFactory.getLogger(ControlLoopPolicyBuilderImpl.class.getName()); - private ControlLoopPolicy policy; + private ControlLoopPolicy controlLoopPolicy; - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException { - policy = new ControlLoopPolicy(); + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) { + controlLoopPolicy = new ControlLoopPolicy(); ControlLoop controlLoop = new ControlLoop(); controlLoop.setControlLoopName(controlLoopName); controlLoop.setTimeout(timeout); - policy.setControlLoop(controlLoop); + controlLoopPolicy.setControlLoop(controlLoop); } public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { @@ -78,44 +81,40 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { @Override public ControlLoopPolicyBuilder removePNF() throws BuilderException { - policy.getControlLoop().setPnf(null); + controlLoopPolicy.getControlLoop().setPnf(null); return this; } @Override public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException { - if (services == null) { - throw new BuilderException("Service must not be null"); - } for (Service service : services) { - if (service.getServiceUUID() == null) { - if (service.getServiceName() == null || service.getServiceName().length() < 1) { - throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); - } - if(policy.getControlLoop().getServices()==null){ - policy.getControlLoop().setServices(new LinkedList<>()); - } - policy.getControlLoop().getServices().add(service); + if (service == null) { + throw new BuilderException("Service must not be null"); + } + if (service.getServiceUUID() == null && Strings.isNullOrEmpty(service.getServiceName())) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + if(controlLoopPolicy.getControlLoop().getServices()==null){ + controlLoopPolicy.getControlLoop().setServices(new LinkedList<>()); + } + controlLoopPolicy.getControlLoop().getServices().add(service); } - } return this; } @Override public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException { - if (services == null) { - throw new BuilderException("Service must not be null"); - } - if (policy.getControlLoop().getServices() == null) { + if (controlLoopPolicy.getControlLoop().getServices() == null) { throw new BuilderException("No existing services to remove"); } for (Service service : services) { - if (service.getServiceUUID() == null) { - if (service.getServiceName() == null || service.getServiceName().length() < 1) { - throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); - } + if (service == null) { + throw new BuilderException("Service must not be null"); + } + if (service.getServiceUUID() == null && Strings.isNullOrEmpty(service.getServiceName())) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); } - boolean removed = policy.getControlLoop().getServices().remove(service); + boolean removed = controlLoopPolicy.getControlLoop().getServices().remove(service); if (!removed) { throw new BuilderException("Unknown service " + service.getServiceName()); } @@ -125,26 +124,24 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { @Override public ControlLoopPolicyBuilder removeAllServices() throws BuilderException { - policy.getControlLoop().getServices().clear(); + controlLoopPolicy.getControlLoop().getServices().clear(); return this; } @Override public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException { - if (resources == null) { - throw new BuilderException("resources must not be null"); - } for (Resource resource : resources) { - if (resource.getResourceUUID() == null) { - if (resource.getResourceName() == null || resource.getResourceName().length() <= 0) { - throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); - } + if (resource == null) { + throw new BuilderException("Resource must not be null"); + } + if (resource.getResourceUUID() == null && Strings.isNullOrEmpty(resource.getResourceName())) { + throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); } - if(policy.getControlLoop().getResources()==null){ - policy.getControlLoop().setResources(new LinkedList<>()); + if(controlLoopPolicy.getControlLoop().getResources()==null){ + controlLoopPolicy.getControlLoop().setResources(new LinkedList<>()); } - policy.getControlLoop().getResources().add(resource); + controlLoopPolicy.getControlLoop().getResources().add(resource); } return this; } @@ -157,7 +154,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { if (pnf.getPNFName() == null && pnf.getPNFType() == null) { throw new BuilderException("Invalid PNF - need either pnfName or pnfType"); } - policy.getControlLoop().setPnf(pnf); + controlLoopPolicy.getControlLoop().setPnf(pnf); return this; } @@ -166,13 +163,13 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { if (abatement == null) { throw new BuilderException("abatement must not be null"); } - policy.getControlLoop().setAbatement(abatement); + controlLoopPolicy.getControlLoop().setAbatement(abatement); return this; } @Override public ControlLoopPolicyBuilder setTimeout(Integer timeout) { - policy.getControlLoop().setTimeout(timeout); + controlLoopPolicy.getControlLoop().setTimeout(timeout); return this; } @@ -182,7 +179,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); - policy.getControlLoop().setTrigger_policy(trigger.getId()); + controlLoopPolicy.getControlLoop().setTrigger_policy(trigger.getId()); this.addNewPolicy(trigger); // @@ -199,7 +196,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { // Policy existingPolicy = this.findPolicy(policyID); if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); + throw new BuilderException(UNKNOWN_POLICY + policyID); } // // Create the new Policy @@ -235,7 +232,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { // // Add it to our list // - this.policy.getPolicies().add(newPolicy); + this.controlLoopPolicy.getPolicies().add(newPolicy); // // Return a policy to them // @@ -268,7 +265,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { options.setDefaultFlowStyle(FlowStyle.BLOCK); options.setPrettyFlow(true); Yaml yaml = new Yaml(options); - String dumpedYaml = yaml.dump(policy); + String dumpedYaml = yaml.dump(controlLoopPolicy); // // This is our callback class for our compiler // @@ -277,7 +274,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { // Compile it // try { - ControlLoopCompiler.compile(policy, callback); + ControlLoopCompiler.compile(controlLoopPolicy, callback); } catch (CompilerException e) { logger.error(e.getMessage() + e); callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); @@ -290,16 +287,18 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { } private void addNewPolicy(Policy policy) { - if (this.policy.getPolicies() == null) { - this.policy.setPolicies(new LinkedList<>()); + if (this.controlLoopPolicy.getPolicies() == null) { + this.controlLoopPolicy.setPolicies(new LinkedList<>()); } - this.policy.getPolicies().add(policy); + this.controlLoopPolicy.getPolicies().add(policy); } private Policy findPolicy(String id) { - for (Policy policy : this.policy.getPolicies()) { - if (policy.getId().equals(id)) { - return policy; + if (this.controlLoopPolicy.getPolicies() != null){ + for (Policy policy : this.controlLoopPolicy.getPolicies()) { + if (policy.getId().equals(id)) { + return policy; + } } } return null; @@ -307,19 +306,17 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { @Override public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException { - if (resources == null) { - throw new BuilderException("Resource must not be null"); - } - if (policy.getControlLoop().getResources() == null) { + if (controlLoopPolicy.getControlLoop().getResources() == null) { throw new BuilderException("No existing resources to remove"); } for (Resource resource : resources) { - if (resource.getResourceUUID() == null) { - if (resource.getResourceName() == null || resource.getResourceName().length() < 1) { - throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); - } + if (resource == null) { + throw new BuilderException("Resource must not be null"); + } + if (resource.getResourceUUID() == null && Strings.isNullOrEmpty(resource.getResourceName())) { + throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); } - boolean removed = policy.getControlLoop().getResources().remove(resource); + boolean removed = controlLoopPolicy.getControlLoop().getResources().remove(resource); if (!removed) { throw new BuilderException("Unknown resource " + resource.getResourceName()); } @@ -329,17 +326,17 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { @Override public ControlLoopPolicyBuilder removeAllResources() throws BuilderException { - policy.getControlLoop().getResources().clear(); + controlLoopPolicy.getControlLoop().getResources().clear(); return this; } @Override public Integer calculateTimeout() { int sum = 0; - for (Policy policy : this.policy.getPolicies()) { + for (Policy policy : this.controlLoopPolicy.getPolicies()) { sum += policy.getTimeout().intValue(); } - return new Integer(sum); + return Integer.valueOf(sum); } @Override @@ -349,37 +346,32 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { } Policy trigger = this.findPolicy(id); if (trigger == null) { - throw new BuilderException("Unknown policy " + id); + throw new BuilderException(UNKNOWN_POLICY + id); } else { - this.policy.getControlLoop().setTrigger_policy(id); + this.controlLoopPolicy.getControlLoop().setTrigger_policy(id); } - return new ControlLoop(this.policy.getControlLoop()); + return new ControlLoop(this.controlLoopPolicy.getControlLoop()); } @Override public boolean isOpenLoop() { - if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { - return true; - } - else { - return false; - } + return this.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString()); } @Override public Policy getTriggerPolicy() throws BuilderException { - if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { + if (this.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { return null; } else { - return new Policy(this.findPolicy(this.policy.getControlLoop().getTrigger_policy())); + return new Policy(this.findPolicy(this.controlLoopPolicy.getControlLoop().getTrigger_policy())); } } @Override public ControlLoop getControlLoop() { - return new ControlLoop(this.policy.getControlLoop()); + return new ControlLoop(this.controlLoopPolicy.getControlLoop()); } @Override @@ -429,53 +421,53 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { public boolean removePolicy(String policyID) throws BuilderException { Policy existingPolicy = this.findPolicy(policyID); if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); + throw new BuilderException(UNKNOWN_POLICY + policyID); } // // Check if the policy to remove is trigger_policy // - if (this.policy.getControlLoop().getTrigger_policy().equals(policyID)) { - this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); + if (this.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(policyID)) { + this.controlLoopPolicy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); } else { - // - // Update policies - // - for (Policy policy : this.policy.getPolicies()) { - int index = this.policy.getPolicies().indexOf(policy); - if (policy.getSuccess().equals(policyID)) { - policy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); - } - if (policy.getFailure().equals(policyID)) { - policy.setFailure(FinalResult.FINAL_FAILURE.toString()); - } - if (policy.getFailure_retries().equals(policyID)) { - policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); - } - if (policy.getFailure_timeout().equals(policyID)) { - policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); - } - if (policy.getFailure_exception().equals(policyID)) { - policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); - } - if (policy.getFailure_guard().equals(policyID)) { - policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); - } - this.policy.getPolicies().set(index, policy); - } + updateChainedPoliciesForPolicyRemoval(policyID); } // // remove the policy // - boolean removed = this.policy.getPolicies().remove(existingPolicy); - return removed; + return this.controlLoopPolicy.getPolicies().remove(existingPolicy); + } + + private void updateChainedPoliciesForPolicyRemoval(String idOfPolicyBeingRemoved){ + for (Policy policy : this.controlLoopPolicy.getPolicies()) { + int index = this.controlLoopPolicy.getPolicies().indexOf(policy); + if (policy.getSuccess().equals(idOfPolicyBeingRemoved)) { + policy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); + } + if (policy.getFailure().equals(idOfPolicyBeingRemoved)) { + policy.setFailure(FinalResult.FINAL_FAILURE.toString()); + } + if (policy.getFailure_retries().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); + } + if (policy.getFailure_timeout().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); + } + if (policy.getFailure_exception().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); + } + if (policy.getFailure_guard().equals(idOfPolicyBeingRemoved)) { + policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); + } + this.controlLoopPolicy.getPolicies().set(index, policy); + } } @Override public Policy resetPolicyResults(String policyID) throws BuilderException { Policy existingPolicy = this.findPolicy(policyID); if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); + throw new BuilderException(UNKNOWN_POLICY + policyID); } // // reset policy results @@ -494,11 +486,11 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { // // Remove all existing operational policies // - this.policy.getPolicies().clear(); + this.controlLoopPolicy.getPolicies().clear(); // // Revert controlLoop back to an open loop // - this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); + this.controlLoopPolicy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); return this; } @@ -506,7 +498,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { Policy existingPolicy = this.findPolicy(policyID); if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); + throw new BuilderException(UNKNOWN_POLICY + policyID); } // // Add operationsAccumulateParams to existingPolicy diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java index 3a9840c6c..78d28ef38 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java @@ -29,7 +29,7 @@ import org.onap.policy.controlloop.policy.builder.Results; public class ResultsImpl implements Results { private String specification; - private List messages = new LinkedList(); + private List messages = new LinkedList<>(); @Override public List getMessages() { diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java index a9c632290..96c277b26 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java @@ -27,9 +27,9 @@ import java.util.Map; public class Constraint { - private Integer freq_limit_per_target; - private Map time_window; - private Map active_time_range; + private Integer freqLimitPerTarget; + private Map timeWindow; + private Map activeTimeRange; private List blacklist; @@ -38,32 +38,32 @@ public class Constraint { } public Integer getFreq_limit_per_target() { - return freq_limit_per_target; + return freqLimitPerTarget; } - public void setFreq_limit_per_target(Integer freq_limit_per_target) { - this.freq_limit_per_target = freq_limit_per_target; + public void setFreq_limit_per_target(Integer freqLimitPerTarget) { + this.freqLimitPerTarget = freqLimitPerTarget; } public Map getTime_window() { - return time_window; + return timeWindow; } - public void setTime_window(Map time_window) { - this.time_window = time_window; + public void setTime_window(Map timeWindow) { + this.timeWindow = timeWindow; } public Map getActive_time_range() { - return active_time_range; + return activeTimeRange; } - public void setActive_time_range(Map active_time_range) { - this.active_time_range = active_time_range; + public void setActive_time_range(Map activeTimeRange) { + this.activeTimeRange = activeTimeRange; } @@ -75,10 +75,10 @@ public class Constraint { this.blacklist = blacklist; } - public Constraint(Integer freq_limit_per_target, Map time_window) { - this.freq_limit_per_target = freq_limit_per_target; - if(time_window!=null){ - this.time_window = Collections.unmodifiableMap(time_window); + public Constraint(Integer freqLimitPerTarget, Map timeWindow) { + this.freqLimitPerTarget = freqLimitPerTarget; + if(timeWindow!=null){ + this.timeWindow = Collections.unmodifiableMap(timeWindow); } } @@ -86,23 +86,23 @@ public class Constraint { this.blacklist = new LinkedList<>(blacklist); } - public Constraint(Integer freq_limit_per_target, Map time_window, List blacklist) { - this.freq_limit_per_target = freq_limit_per_target; - this.time_window = Collections.unmodifiableMap(time_window); + public Constraint(Integer freqLimitPerTarget, Map timeWindow, List blacklist) { + this.freqLimitPerTarget = freqLimitPerTarget; + this.timeWindow = Collections.unmodifiableMap(timeWindow); this.blacklist = new LinkedList<>(blacklist); } - public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range) { - this(freq_limit_per_target, time_window); - if (active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(active_time_range); + public Constraint(Integer freqLimitPerTarget, Map timeWindow, Map activeTimeRange) { + this(freqLimitPerTarget, timeWindow); + if (activeTimeRange != null) { + this.activeTimeRange = Collections.unmodifiableMap(activeTimeRange); } } - public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range, List blacklist) { - this(freq_limit_per_target, time_window); - if (active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(active_time_range); + public Constraint(Integer freqLimitPerTarget, Map timeWindow, Map activeTimeRange, List blacklist) { + this(freqLimitPerTarget, timeWindow); + if (activeTimeRange != null) { + this.activeTimeRange = Collections.unmodifiableMap(activeTimeRange); } if(blacklist!=null){ this.blacklist = new LinkedList<>(blacklist); @@ -110,30 +110,30 @@ public class Constraint { } public Constraint(Constraint constraint) { - this.freq_limit_per_target = constraint.freq_limit_per_target; - this.time_window = constraint.time_window; - if (constraint.active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(constraint.active_time_range); + this.freqLimitPerTarget = constraint.freqLimitPerTarget; + this.timeWindow = constraint.timeWindow; + if (constraint.activeTimeRange != null) { + this.activeTimeRange = Collections.unmodifiableMap(constraint.activeTimeRange); } this.blacklist = new LinkedList<>(constraint.blacklist); } public boolean isValid() { - return ((freq_limit_per_target == null && time_window != null)|| (time_window == null && freq_limit_per_target != null))? false : true; + return ((freqLimitPerTarget == null && timeWindow != null)|| (timeWindow == null && freqLimitPerTarget != null))? false : true; } @Override public String toString() { - return "Constraint [freq_limit_per_target=" + freq_limit_per_target + ", time_window=" + time_window + ", active_time_range=" + active_time_range + ", blacklist=" + blacklist + "]"; + return "Constraint [freq_limit_per_target=" + freqLimitPerTarget + ", time_window=" + timeWindow + ", active_time_range=" + activeTimeRange + ", blacklist=" + blacklist + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((freq_limit_per_target == null) ? 0 : freq_limit_per_target.hashCode()); - result = prime * result + ((time_window == null) ? 0 : time_window.hashCode()); - result = prime * result + ((active_time_range == null) ? 0 : active_time_range.hashCode()); + result = prime * result + ((freqLimitPerTarget == null) ? 0 : freqLimitPerTarget.hashCode()); + result = prime * result + ((timeWindow == null) ? 0 : timeWindow.hashCode()); + result = prime * result + ((activeTimeRange == null) ? 0 : activeTimeRange.hashCode()); result = prime * result + ((blacklist == null) ? 0 : blacklist.hashCode()); return result; } @@ -147,26 +147,16 @@ public class Constraint { if (getClass() != obj.getClass()) return false; Constraint other = (Constraint) obj; - if (freq_limit_per_target == null) { - if (other.freq_limit_per_target != null) - return false; - } else if (!freq_limit_per_target.equals(other.freq_limit_per_target)) - return false; - if (time_window == null) { - if (other.time_window != null) - return false; - } else if (!time_window.equals(other.time_window)) - return false; - if (active_time_range == null) { - if (other.active_time_range != null) - return false; - } else if (!active_time_range.equals(other.active_time_range)) - return false; - if (blacklist == null) { - if (other.blacklist != null) - return false; - } else if (!blacklist.equals(other.blacklist)) - return false; - return true; + return equalsMayBeNull(freqLimitPerTarget, other.freqLimitPerTarget) + && equalsMayBeNull(timeWindow, other.timeWindow) + && equalsMayBeNull(activeTimeRange, other.activeTimeRange) + && equalsMayBeNull(blacklist, other.blacklist); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2){ + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals(obj2); } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java index 97d3d6faf..16a384a56 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java @@ -20,7 +20,6 @@ package org.onap.policy.controlloop.policy.guard; -import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.UUID; @@ -30,8 +29,8 @@ public class GuardPolicy { private String id = UUID.randomUUID().toString(); private String name; private String description; - private MatchParameters match_parameters; - private LinkedList limit_constraints; + private MatchParameters matchParameters; + private LinkedList limitConstraints; public GuardPolicy() { //Do Nothing Empty Constructor. @@ -62,19 +61,19 @@ public class GuardPolicy { } public MatchParameters getMatch_parameters() { - return match_parameters; + return matchParameters; } - public void setMatch_parameters(MatchParameters match_parameters) { - this.match_parameters = match_parameters; + public void setMatch_parameters(MatchParameters matchParameters) { + this.matchParameters = matchParameters; } public LinkedList getLimit_constraints() { - return limit_constraints; + return limitConstraints; } - public void setLimit_constraints(LinkedList limit_constraints) { - this.limit_constraints = limit_constraints; + public void setLimit_constraints(LinkedList limitConstraints) { + this.limitConstraints = limitConstraints; } public GuardPolicy(String id) { @@ -83,7 +82,7 @@ public class GuardPolicy { public GuardPolicy(String name, MatchParameters matchParameters) { this.name = name; - this.match_parameters = matchParameters; + this.matchParameters = matchParameters; } public GuardPolicy(String id, String name, String description, MatchParameters matchParameters) { @@ -94,8 +93,8 @@ public class GuardPolicy { public GuardPolicy(String name, MatchParameters matchParameters, List limitConstraints) { this(name, matchParameters); - if (limit_constraints != null) { - this.limit_constraints = (LinkedList) Collections.unmodifiableList(limitConstraints); + if (limitConstraints != null) { + this.limitConstraints = (LinkedList) limitConstraints; } } @@ -113,9 +112,9 @@ public class GuardPolicy { this.id = policy.id; this.name = policy.name; this.description = policy.description; - this.match_parameters = new MatchParameters(policy.match_parameters); - if (policy.limit_constraints != null) { - this.limit_constraints = (LinkedList) Collections.unmodifiableList(policy.limit_constraints); + this.matchParameters = new MatchParameters(policy.matchParameters); + if (policy.limitConstraints != null) { + this.limitConstraints = policy.limitConstraints; } } @@ -126,7 +125,7 @@ public class GuardPolicy { @Override public String toString() { return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters=" - +match_parameters + ", limitConstraints=" + limit_constraints + "]"; + +matchParameters + ", limitConstraints=" + limitConstraints + "]"; } @Override @@ -136,8 +135,8 @@ public class GuardPolicy { result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((limit_constraints == null) ? 0 : limit_constraints.hashCode()); - result = prime * result + ((match_parameters == null) ? 0 : match_parameters.hashCode()); + result = prime * result + ((limitConstraints == null) ? 0 : limitConstraints.hashCode()); + result = prime * result + ((matchParameters == null) ? 0 : matchParameters.hashCode()); return result; } @@ -150,33 +149,17 @@ public class GuardPolicy { if (getClass() != obj.getClass()) return false; GuardPolicy other = (GuardPolicy) obj; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (limit_constraints == null) { - if (other.limit_constraints != null) - return false; - } else if (!limit_constraints.equals(other.limit_constraints)) - return false; - if (match_parameters==null){ - if(other.match_parameters !=null) - return false; - } else if(!match_parameters.equals(other.match_parameters)) - return false; - return true; + return equalsMayBeNull(description, other.description) + && equalsMayBeNull(id, other.id) + && equalsMayBeNull(name, other.name) + && equalsMayBeNull(limitConstraints, other.limitConstraints) + && equalsMayBeNull(matchParameters, other.matchParameters); } - + private boolean equalsMayBeNull(final Object obj1, final Object obj2){ + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals(obj2); + } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java index fbfad741f..8e5d0c09c 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java @@ -119,26 +119,17 @@ public class MatchParameters { if (getClass() != obj.getClass()) return false; MatchParameters other = (MatchParameters) obj; - if (actor == null) { - if (other.actor != null) - return false; - } else if (!actor.equals(other.actor)) - return false; - if (controlLoopName == null) { - if (other.controlLoopName != null) - return false; - } else if (!controlLoopName.equals(other.controlLoopName)) - return false; - if (recipe == null) { - if (other.recipe != null) - return false; - } else if (!recipe.equals(other.recipe)) - return false; - if (targets == null) { - if (other.targets != null) - return false; - } else if (!targets.equals(other.targets)) - return false; - return true; + + return equalsMayBeNull(actor, other.actor) + && equalsMayBeNull(controlLoopName, other.controlLoopName) + && equalsMayBeNull(recipe, other.recipe) + && equalsMayBeNull(targets, other.targets); + } + + private boolean equalsMayBeNull(final Object obj1, final Object obj2){ + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals(obj2); } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java index 8691a0fb7..d521624fd 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java @@ -120,9 +120,8 @@ public interface ControlLoopGuardBuilder { /** * @param guard * @return ControlLoopGuardBuilder object - * @throws BuilderException */ - public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) throws BuilderException { + public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) { return new ControlLoopGuardBuilderImpl(guard); diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java index 4c25a7ef9..60716383d 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java @@ -42,7 +42,9 @@ import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { - private static Logger logger = LoggerFactory.getLogger(ControlLoopGuardBuilderImpl.class.getName()); + private static final String NO_EXISTING_GUARD_POLICY_MATCHING_THE_ID = "No existing guard policy matching the id: "; + private static final String THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL = "The id of target guard policy must not be null"; + private static Logger logger = LoggerFactory.getLogger(ControlLoopGuardBuilderImpl.class.getName()); private ControlLoopGuard cLGuard; public ControlLoopGuardBuilderImpl(Guard guard) { @@ -96,13 +98,13 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { @Override public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException { if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); + throw new BuilderException(THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL); } if (constraints == null) { throw new BuilderException("Constraint much not be null"); } if (!addLimitConstraints(id,constraints)) { - throw new BuilderException("No existing guard policy matching the id: " + id); + throw new BuilderException(NO_EXISTING_GUARD_POLICY_MATCHING_THE_ID + id); } return this; } @@ -133,13 +135,13 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { @Override public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException { if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); + throw new BuilderException(THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL); } if (constraints == null) { throw new BuilderException("Constraint much not be null"); } if (!removeConstraints(id, constraints)) { - throw new BuilderException("No existing guard policy matching the id: " + id); + throw new BuilderException(NO_EXISTING_GUARD_POLICY_MATCHING_THE_ID + id); } return this; } @@ -173,7 +175,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { throw new BuilderException("No guard policies exist"); } if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); + throw new BuilderException(THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL); } boolean exist = false; for (GuardPolicy policy: cLGuard.getGuards()) { @@ -183,7 +185,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { } } if (!exist) { - throw new BuilderException("No existing guard policy matching the id: " + id); + throw new BuilderException(NO_EXISTING_GUARD_POLICY_MATCHING_THE_ID + id); } return this; } diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java new file mode 100644 index 000000000..0ec882fef --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.controlloop.compiler; + +import org.junit.Test; +import org.onap.policy.common.utils.test.ExceptionsTester; + +public class CompilerExceptionTest extends ExceptionsTester{ + + @Test + public void test() throws Exception { + test(CompilerException.class); + } + +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java index ee5ed785d..048aef270 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java @@ -27,48 +27,135 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.FinalResult; public class ControlLoopCompilerTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); @Test - public void testTest() { - try { - this.test("src/test/resources/v1.0.0/test.yaml"); - } catch (Exception e) { - fail(e.getMessage()); - } + public void testTest() throws Exception { + List expectedOnErrorMessages = new ArrayList<>(); + expectedOnErrorMessages.add("Operational Policy has an bad ID"); + expectedOnErrorMessages.add("Policy id is set to a PolicyResult SUCCESS"); + expectedOnErrorMessages.add("Policy id is set to a FinalResult FINAL_SUCCESS"); + expectedOnErrorMessages.add("Policy actor is null"); + expectedOnErrorMessages.add("Policy actor is invalid"); + expectedOnErrorMessages.add("Policy recipe is null"); + expectedOnErrorMessages.add("Policy recipe is invalid"); + expectedOnErrorMessages.add("Policy recipe is invalid"); + expectedOnErrorMessages.add("Policy recipe is invalid"); + expectedOnErrorMessages.add("Policy target is null"); + expectedOnErrorMessages.add("Policy target is invalid"); + expectedOnErrorMessages.add("Policy success is neither another policy nor FINAL_SUCCESS"); + expectedOnErrorMessages.add("Policy failure is neither another policy nor FINAL_FAILURE"); + expectedOnErrorMessages.add("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); + expectedOnErrorMessages.add("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); + expectedOnErrorMessages.add("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); + expectedOnErrorMessages.add("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); + expectedOnErrorMessages.add("Unsupported version for this compiler"); + expectedOnErrorMessages.add("controlLoop overall timeout is less than the sum of operational policy timeouts."); + + TestControlLoopCompilerCallback testControlLoopCompilerCallback = new TestControlLoopCompilerCallback(expectedOnErrorMessages); + ControlLoopPolicy controlLoopPolicy = this.test("src/test/resources/v1.0.0/test.yaml", testControlLoopCompilerCallback); + assertEquals(22, controlLoopPolicy.getPolicies().size()); + assertTrue(testControlLoopCompilerCallback.areAllExpectedOnErrorsReceived()); + } + + @Test + public void testSuccessConnectedToUnknownPolicy() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy"); + this.test("src/test/resources/v1.0.0/bad_policy_success_connected_to_unknown_policy.yaml"); + } + + @Test + public void testFailureConnectedToUnknownPolicy() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy"); + this.test("src/test/resources/v1.0.0/bad_policy_failure_connected_to_unknown_policy.yaml"); + } + + @Test + public void testFailureTimeoutToUnknownPolicy() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy"); + this.test("src/test/resources/v1.0.0/bad_policy_failure_timeout_connected_to_unknown_policy.yaml"); + } + + @Test + public void testFailureRetriesToUnknownPolicy() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy"); + this.test("src/test/resources/v1.0.0/bad_policy_failure_retries_connected_to_unknown_policy.yaml"); + } + + @Test + public void testFailureExceptionToUnknownPolicy() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy"); + this.test("src/test/resources/v1.0.0/bad_policy_failure_exception_connected_to_unknown_policy.yaml"); + } + + @Test + public void testFailureGuardToUnknownPolicy() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy"); + this.test("src/test/resources/v1.0.0/bad_policy_failure_guard_connected_to_unknown_policy.yaml"); } @Test - public void testBad1() { - try { - this.test("src/test/resources/v1.0.0/bad_trigger_1.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } + public void testInvalidTriggerPolicyId() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Unexpected value for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); + this.test("src/test/resources/v1.0.0/bad_trigger_1.yaml"); } + @Test - public void testBad2() { - try { - this.test("src/test/resources/v1.0.0/bad_trigger_2.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } + public void testNoTriggerPolicyId() throws Exception { + expectedException.expect(CompilerException.class); + this.test("src/test/resources/v1.0.0/bad_trigger_no_trigger_id.yaml"); } @Test - public void testBad() { - try { - this.test("src/test/resources/v1.0.0/bad_policies_1.yaml"); - } catch (Exception e) { - } + public void testNoControlLoopName() throws Exception { + List expectedOnErrorMessages = new ArrayList<>(); + expectedOnErrorMessages.add("Missing controlLoopName"); + expectedOnErrorMessages.add("Unsupported version for this compiler"); + TestControlLoopCompilerCallback testControlLoopCompilerCallback = new TestControlLoopCompilerCallback(expectedOnErrorMessages); + this.test("src/test/resources/v1.0.0/bad_control_loop_no_control_loop_name.yaml", testControlLoopCompilerCallback); + assertTrue(testControlLoopCompilerCallback.areAllExpectedOnErrorsReceived()); + } + + @Test + public void testInvalidFinalResult() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Unexpected Final Result for trigger_policy, should only be FINAL_OPENLOOP or a valid Policy ID"); + this.test("src/test/resources/v1.0.0/bad_trigger_2.yaml"); + } + + @Test + public void testCompileEmptyFile() throws Exception { + expectedException.expect(CompilerException.class); + expectedException.expectMessage("Could not parse yaml specification."); + this.test("src/test/resources/v1.0.0/empty.yaml"); + } + + public ControlLoopPolicy test(String testFile) throws Exception { + return test(testFile, null); } - public void test(String testFile) throws Exception { + public ControlLoopPolicy test(String testFile, ControlLoopCompilerCallback controlLoopCompilerCallback) throws Exception { try (InputStream is = new FileInputStream(new File(testFile))) { - ControlLoopCompiler.compile(is, null); + return ControlLoopCompiler.compile(is, controlLoopCompilerCallback); } catch (FileNotFoundException e) { fail(e.getMessage()); } catch (IOException e) { @@ -76,6 +163,36 @@ public class ControlLoopCompilerTest { } catch (Exception e) { throw e; } + return null; } + + class TestControlLoopCompilerCallback implements ControlLoopCompilerCallback{ + + private List expectedOnErrorMessages; + + public TestControlLoopCompilerCallback(List expectedOnErrorMessages){ + this.expectedOnErrorMessages = expectedOnErrorMessages; + } + + @Override + public boolean onWarning(String message) { + return true; + } + + @Override + public boolean onError(String message) { + if (!expectedOnErrorMessages.remove(message)){ + fail("Unexpected onError message: " + message); + } + return true; + } + + public boolean areAllExpectedOnErrorsReceived(){ + return expectedOnErrorMessages.size() == 0; + } + + }; } + + diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java index f1681247d..05d4e469d 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java @@ -20,8 +20,10 @@ package org.onap.policy.controlloop.policy; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -31,8 +33,12 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.UUID; - +import org.junit.Ignore; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.policy.aai.PNF; +import org.onap.policy.aai.PNFType; import org.onap.policy.controlloop.policy.builder.BuilderException; import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; import org.onap.policy.controlloop.policy.builder.Message; @@ -47,6 +53,9 @@ import org.yaml.snakeyaml.error.YAMLException; public class ControlLoopPolicyBuilderTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); @Test public void testControlLoop() { @@ -85,17 +94,202 @@ public class ControlLoopPolicyBuilderTest { assertTrue(builder.getControlLoop().getResources().size() == 2); builder = builder.removeAllResources(); assertTrue(builder.getControlLoop().getResources().size() == 0); - // - // Test set abatement - // - assertFalse(builder.getControlLoop().getAbatement()); - builder = builder.setAbatement(true); - assertTrue(builder.getControlLoop().getAbatement()); } catch (BuilderException e) { fail(e.getMessage()); } } + @Test + public void testAddNullService() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Service must not be null"); + builder.addService((Service)null); + } + + @Test + public void testAddInvalidService() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Invalid service - need either a serviceUUID or serviceName"); + builder.addService(new Service()); + } + + @Test + public void testAddServiceWithUUID() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + UUID uuid = UUID.randomUUID(); + Service serviceWithUUID = new Service(uuid); + builder.addService(serviceWithUUID); + assertTrue(builder.getControlLoop().getServices().size() == 1); + } + + @Test + public void testAddNullResource() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Resource must not be null"); + builder.addResource((Resource)null); + } + + + @Test + public void testAddInvalidResource() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Invalid resource - need either resourceUUID or resourceName"); + builder.addResource(new Resource()); + } + + @Test + public void testAddAndRemoveResourceWithUUID() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + UUID uuid = UUID.randomUUID(); + Resource resourceWithUUID = new Resource(uuid); + builder.addResource(resourceWithUUID); + assertTrue(builder.getControlLoop().getResources().size() == 1); + + builder.removeResource(resourceWithUUID); + assertTrue(builder.getControlLoop().getResources().size() == 0); + } + + @Test + public void testRemoveNullResource() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Resource resource = new Resource("resource1", ResourceType.VF); + builder.addResource(resource); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Resource must not be null"); + builder.removeResource((Resource)null); + } + + @Test + public void testRemoveResourceNoExistingResources() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("No existing resources to remove"); + builder.removeResource(new Resource("resource1", ResourceType.VF)); + } + + @Test + public void testRemoveInvalidResource() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Resource resource = new Resource("resource1", ResourceType.VF); + builder.addResource(resource); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Invalid resource - need either a resourceUUID or resourceName"); + builder.removeResource(new Resource()); + } + + @Test + public void testRemoveUnknownResource() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Resource resource = new Resource("resource1", ResourceType.VF); + builder.addResource(resource); + final String unknownResourceName = "reource2"; + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Unknown resource " + unknownResourceName); + builder.removeResource(new Resource(unknownResourceName, ResourceType.VF)); + } + + @Test + public void testControlLoopWithInitialResourceAndServices() { + try { + Resource vCTS = new Resource("vCTS", ResourceType.VF); + Service vSCP = new Service("vSCP"); + Service vUSP = new Service("vUSP"); + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400, vCTS, vSCP, vUSP); + assertTrue(builder.getControlLoop().getResources().size() == 1); + assertTrue(builder.getControlLoop().getServices().size() == 2); + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testControlLoopWithInitialResourcesAndService() { + try { + Resource vCTS = new Resource("vCTS", ResourceType.VF); + Resource vCOM = new Resource("vCTS", ResourceType.VF); + Service vSCP = new Service("vSCP"); + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400, vSCP, vCTS, vCOM); + assertTrue(builder.getControlLoop().getServices().size() == 1); + assertTrue(builder.getControlLoop().getResources().size() == 2); + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + @Ignore + // I'VE MARKED THIS TEST CASE AS IGNORE BECAUSE THE TEST CASE FAILS + // This test case fails because builder.getControlLoop() returns an instance of ControlLoop copied using + // the ControlLoop(ControlLoop controlLoop) constructor. + // This constructor does not copy the value of pnf into the newly created object + // On the face of it, this looks like a bug, but perhaps there is a reason for this + // PLEASE ADVISE IF THE BEHAVIOUR IS INCORRECT OR THE TEST CASE IS INVALID + public void testControlLoopForPnf() { + try { + PNF pnf = new PNF(); + pnf.setPNFType(PNFType.ENODEB); + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400, pnf); + assertEquals(pnf, builder.getControlLoop().getPnf()); + + builder.removePNF(); + assertNull(builder.getControlLoop().getPnf()); + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + @Ignore + // Fails for the same reason as the above test case + public void testSetAndRemovePnf() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + assertNull(builder.getControlLoop().getPnf()); + + PNF pnf = new PNF(); + pnf.setPNFType(PNFType.ENODEB); + builder.setPNF(pnf); + assertEquals(pnf, builder.getControlLoop().getPnf()); + + builder.removePNF(); + assertNull(builder.getControlLoop().getPnf()); + } + + @Test + public void testSetNullPnf() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("PNF must not be null"); + builder.setPNF(null); + } + + @Test + public void testSetInvalidPnf() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Invalid PNF - need either pnfName or pnfType"); + builder.setPNF(new PNF()); + } + + @Test + public void testSetAbatement() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + assertFalse(builder.getControlLoop().getAbatement()); + builder = builder.setAbatement(true); + assertTrue(builder.getControlLoop().getAbatement()); + } + + @Test + public void testSetNullAbatement() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("abatement must not be null"); + builder = builder.setAbatement(null); + } + @Test public void testTimeout() { try { @@ -192,6 +386,41 @@ public class ControlLoopPolicyBuilderTest { fail(e.getMessage()); } } + + @Test + public void testSetTriggerPolicyNullPolicyId() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Id must not be null"); + builder.setTriggerPolicy(null); + } + + @Test + public void testSetTriggerPolicyNoPoliciesExist() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + final String unknownPolicyId = "100"; + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Unknown policy " + unknownPolicyId); + builder.setTriggerPolicy(unknownPolicyId); + } + + @Test + public void testSetTriggerPolicyUnknownPolicy() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + final String unknownPolicyId = "100"; + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Unknown policy " + unknownPolicyId); + builder.setTriggerPolicy(unknownPolicyId); + } @Test public void testAddRemovePolicies() { @@ -220,14 +449,34 @@ public class ControlLoopPolicyBuilderTest { 600, triggerPolicy.getId(), PolicyResult.FAILURE, + PolicyResult.FAILURE_EXCEPTION, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.FAILURE_GUARD); // assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy1.getId())); assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId())); assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId())); assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId())); + + // + // Test create a policy and chain it to the results of trigger policy success + // + Policy onSuccessPolicy1 = builder.setPolicyForPolicyResult( + "Do something", + "If the restart succeeds, do something else.", + "APPC", + new Target(TargetType.VM), + "SomethingElse", + null, + 1, + 600, + triggerPolicy.getId(), + PolicyResult.SUCCESS); + // + assertTrue(builder.getTriggerPolicy().getSuccess().equals(onSuccessPolicy1.getId())); + // // Test remove policy // @@ -272,6 +521,24 @@ public class ControlLoopPolicyBuilderTest { assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId())); assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId())); assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId())); + // + // Test set the policy result for success to an existing operational policy + // + onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( + onRestartFailurePolicy2.getId(), + triggerPolicy.getId(), + PolicyResult.FAILURE, + PolicyResult.FAILURE_EXCEPTION, + PolicyResult.FAILURE_GUARD, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT, + PolicyResult.SUCCESS); + assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getSuccess().equals(onRestartFailurePolicy2.getId())); // // Test remove all existing operational policies @@ -283,6 +550,88 @@ public class ControlLoopPolicyBuilderTest { fail(e.getMessage()); } } + + @Test + public void testAddToUnknownPolicy() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + final String policyId = "100"; + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Unknown policy " + policyId); + + builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600, + policyId, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT, + PolicyResult.FAILURE_GUARD); + } + + @Test + public void testAddExistingPolicyToUnknownPolicy() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + + + Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600, + triggerPolicy.getId(), + PolicyResult.FAILURE); + + final String unknownPolicyId = "100"; + expectedException.expect(BuilderException.class); + expectedException.expectMessage(unknownPolicyId + " does not exist"); + + builder.setPolicyForPolicyResult( + onRestartFailurePolicy.getId(), + unknownPolicyId, + PolicyResult.FAILURE); + } + + @Test + public void testAddUnknownExistingPolicyToPolicy() throws BuilderException { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + + final String unknownPolicyId = "100"; + expectedException.expect(BuilderException.class); + expectedException.expectMessage("Operational policy " + unknownPolicyId + " does not exist"); + + builder.setPolicyForPolicyResult( + unknownPolicyId, + triggerPolicy.getId(), + PolicyResult.FAILURE); + } @Test public void testAddOperationsAccumulateParams() { diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java new file mode 100644 index 000000000..0b2f62def --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java @@ -0,0 +1,171 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.controlloop.policy; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.policy.aai.PNF; +import org.onap.policy.sdc.Resource; +import org.onap.policy.sdc.ResourceType; +import org.onap.policy.sdc.Service; + +public class ControlLoopTest { + + private String controlLoopName = "control loop 1"; + private String version = "1.0.1"; + private String triggerPolicy = FinalResult.FINAL_OPENLOOP.toString(); + private Integer timeout = 100; + private Boolean abatement = false; + + @Test + public void testEqualsSameInstance() { + ControlLoop controlLoop1 = new ControlLoop(); + assertTrue(controlLoop1.equals(controlLoop1)); + } + + @Test + public void testEqualsNull() { + ControlLoop controlLoop1 = new ControlLoop(); + assertFalse(controlLoop1.equals(null)); + } + @Test + public void testEqualsInstanceOfDiffClass() { + ControlLoop controlLoop1 = new ControlLoop(); + assertFalse(controlLoop1.equals("")); + } + + @Test + public void testEqualsNoServicesAndResourcesOrTimeout() { + final PNF pnf = new PNF(); + pnf.setPNFName("pnf 1"); + + ControlLoop controlLoop1 = new ControlLoop(); + controlLoop1.setControlLoopName(controlLoopName); + controlLoop1.setVersion(version); + controlLoop1.setPnf(pnf); + controlLoop1.setTrigger_policy(triggerPolicy); + controlLoop1.setAbatement(abatement); + + ControlLoop controlLoop2 = new ControlLoop(); + controlLoop2.setControlLoopName(controlLoopName); + controlLoop2.setVersion(version); + controlLoop2.setPnf(pnf); + controlLoop2.setTrigger_policy(triggerPolicy); + controlLoop2.setAbatement(abatement); + + assertTrue(controlLoop1.equals(controlLoop2)); + } + + @Test + public void testEquals() { + final PNF pnf = new PNF(); + pnf.setPNFName("pnf 1"); + + ControlLoop controlLoop1 = new ControlLoop(); + controlLoop1.setControlLoopName(controlLoopName); + controlLoop1.setVersion(version); + Service service1 = new Service("service1"); + Service service2 = new Service("service2"); + List services = new ArrayList<>(); + services.add(service1); + services.add(service2); + controlLoop1.setServices(services); + Resource resource1 = new Resource("resource1", ResourceType.VF); + Resource resource2 = new Resource("resource2", ResourceType.VFC); + List resources = new ArrayList<>(); + resources.add(resource1); + resources.add(resource2); + controlLoop1.setResources(resources); + controlLoop1.setPnf(pnf); + controlLoop1.setTrigger_policy(triggerPolicy); + controlLoop1.setTimeout(timeout); + controlLoop1.setAbatement(abatement); + + ControlLoop controlLoop2 = new ControlLoop(); + controlLoop2.setControlLoopName(controlLoopName); + controlLoop2.setVersion(version); + Service controlLoop2_service1 = new Service("service1"); + Service controlLoop2_service2 = new Service("service2"); + List controlLoop2_services = new ArrayList<>(); + controlLoop2_services.add(controlLoop2_service1); + controlLoop2_services.add(controlLoop2_service2); + controlLoop2.setServices(controlLoop2_services); + Resource controlLoop2_resource1 = new Resource("resource1", ResourceType.VF); + Resource controlLoop2_resource2 = new Resource("resource2", ResourceType.VFC); + List controlLoop2_resources = new ArrayList<>(); + controlLoop2_resources.add(controlLoop2_resource1); + controlLoop2_resources.add(controlLoop2_resource2); + controlLoop2.setResources(controlLoop2_resources); + controlLoop2.setPnf(pnf); + controlLoop2.setTrigger_policy(triggerPolicy); + controlLoop2.setTimeout(timeout); + controlLoop1.setAbatement(abatement); + + assertTrue(controlLoop1.equals(controlLoop2)); + assertEquals(controlLoop1.hashCode(), controlLoop2.hashCode()); + } + + @Test + @Ignore + // I'VE MARKED THIS TEST CASE AS IGNORE BECAUSE THE TEST CASE FAILS + // This test case fails because the ControlLoop(ControlLoop controlLoop) constructor. + // does not copy the value of pnf and version into the newly created object + // PLEASE ADVISE IF THE EXISTING BEHAVIOUR IS CORRECT + public void testControlLoop() { + final PNF pnf = new PNF(); + pnf.setPNFName("pnf 1"); + + ControlLoop controlLoop1 = new ControlLoop(); + controlLoop1.setControlLoopName(controlLoopName); + controlLoop1.setVersion(version); + Service service1 = new Service("service1"); + Service service2 = new Service("service2"); + List services = new ArrayList<>(); + services.add(service1); + services.add(service2); + controlLoop1.setServices(services); + Resource resource1 = new Resource("resource1", ResourceType.VF); + Resource resource2 = new Resource("resource2", ResourceType.VFC); + List resources = new ArrayList<>(); + resources.add(resource1); + resources.add(resource2); + controlLoop1.setResources(resources); + controlLoop1.setPnf(pnf); + controlLoop1.setTrigger_policy(triggerPolicy); + controlLoop1.setAbatement(abatement); + + ControlLoop controlLoop2 = new ControlLoop(controlLoop1); + + assertEquals(controlLoop1.getControlLoopName(), controlLoop2.getControlLoopName()); + assertEquals(controlLoop1.getVersion(), controlLoop2.getVersion()); + assertEquals(controlLoop1.getServices(), controlLoop2.getServices()); + assertEquals(controlLoop1.getResources(), controlLoop2.getResources()); + assertEquals(controlLoop1.getPnf(), controlLoop2.getPnf()); + assertEquals(controlLoop1.getTrigger_policy(), controlLoop2.getTrigger_policy()); + assertEquals(controlLoop1.getAbatement(), controlLoop2.getAbatement()); + + assertTrue(controlLoop1.equals(controlLoop2)); + } + +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/OperationsAccumulateParamsTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/OperationsAccumulateParamsTest.java new file mode 100644 index 000000000..5d627a906 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/OperationsAccumulateParamsTest.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.controlloop.policy; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class OperationsAccumulateParamsTest { + + @Test + public void testConstructor() { + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(); + assertNull(operationsAccumulateParams.getPeriod()); + assertNull(operationsAccumulateParams.getLimit()); + } + + @Test + public void testConstructorOperationsAccumulateParams() { + String period = "15m"; + Integer limit = 10; + OperationsAccumulateParams operationsAccumulateParams1 = new OperationsAccumulateParams(period, limit); + OperationsAccumulateParams operationsAccumulateParams2 = new OperationsAccumulateParams(operationsAccumulateParams1); + assertEquals(period, operationsAccumulateParams1.getPeriod()); + assertEquals(limit, operationsAccumulateParams2.getLimit()); + } + + @Test + public void testOperationsAccumulateParamsStringInteger() { + String period = "15m"; + Integer limit = 10; + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(period, limit); + assertEquals(period, operationsAccumulateParams.getPeriod()); + assertEquals(limit, operationsAccumulateParams.getLimit()); + } + + @Test + public void testSetAndGetPeriod() { + String period = "15m"; + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(); + operationsAccumulateParams.setPeriod(period); + assertEquals(period, operationsAccumulateParams.getPeriod()); + } + + @Test + public void testSetLimit() { + Integer limit = 10; + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(); + operationsAccumulateParams.setLimit(limit); + assertEquals(limit, operationsAccumulateParams.getLimit()); } + + @Test + public void testToString() { + String period = "15m"; + Integer limit = 10; + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(period, limit); + assertEquals("OperationsAccumulateParams [period=15m, limit=10]", operationsAccumulateParams.toString()); + } + + @Test + public void testEqualsAndHashCode() { + String period = "15m"; + Integer limit = 10; + OperationsAccumulateParams operationsAccumulateParams1 = new OperationsAccumulateParams(); + OperationsAccumulateParams operationsAccumulateParams2 = new OperationsAccumulateParams(); + + assertTrue(operationsAccumulateParams1.equals(operationsAccumulateParams2)); + + operationsAccumulateParams1.setPeriod(period); + assertFalse(operationsAccumulateParams1.equals(operationsAccumulateParams2)); + operationsAccumulateParams2.setPeriod(period); + assertTrue(operationsAccumulateParams1.equals(operationsAccumulateParams2)); + assertEquals(operationsAccumulateParams1.hashCode(), operationsAccumulateParams2.hashCode()); + + operationsAccumulateParams1.setLimit(limit);; + assertFalse(operationsAccumulateParams1.equals(operationsAccumulateParams2)); + operationsAccumulateParams2.setLimit(limit); + assertTrue(operationsAccumulateParams1.equals(operationsAccumulateParams2)); + assertEquals(operationsAccumulateParams1.hashCode(), operationsAccumulateParams2.hashCode()); + } + + + @Test + public void testEqualsSameObject(){ + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(); + assertTrue(operationsAccumulateParams.equals(operationsAccumulateParams)); + } + + @Test + public void testEqualsNull(){ + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(); + assertFalse(operationsAccumulateParams.equals(null)); + } + + @Test + public void testEqualsInstanceOfDiffClass(){ + OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams(); + assertFalse(operationsAccumulateParams.equals("")); + } + +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java new file mode 100644 index 000000000..d0aa2e675 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java @@ -0,0 +1,249 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.controlloop.policy.guard; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +public class ConstraintTest { + + @Test + public void testConstraint() { + Constraint constraint = new Constraint(); + + assertNull(constraint.getFreq_limit_per_target()); + assertNull(constraint.getTime_window()); + assertNull(constraint.getActive_time_range()); + assertNull(constraint.getBlacklist()); + } + + @Test + public void testGetAndSetFreq_limit_per_target() { + Integer freqLimitPerTarget = 10; + Constraint constraint = new Constraint(); + constraint.setFreq_limit_per_target(freqLimitPerTarget); + assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target()); + } + + @Test + public void testGetAndSetTime_window() { + Map timeWindow = new HashMap<>(); + timeWindow.put("timeWindowKey", "timeWindowValue"); + Constraint constraint = new Constraint(); + constraint.setTime_window(timeWindow); + assertEquals(timeWindow, constraint.getTime_window()); + } + + @Test + public void testGetAndSetActive_time_range() { + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("timeWindowKey", "timeWindowValue"); + Constraint constraint = new Constraint(); + constraint.setActive_time_range(activeTimeRange);; + assertEquals(activeTimeRange, constraint.getActive_time_range()); + } + + @Test + public void testGetAndSetBlacklist() { + List blacklist = new ArrayList<>(); + blacklist.add("blacklist item"); + Constraint constraint = new Constraint(); + constraint.setBlacklist(blacklist); + assertEquals(blacklist, constraint.getBlacklist()); + } + + @Test + public void testConstraintIntegerMapOfStringString() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + + Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow); + + assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target()); + assertEquals(timeWindow, constraint.getTime_window()); + assertNull(constraint.getActive_time_range()); + assertNull(constraint.getBlacklist()); + } + + @Test + public void testConstraintListOfString() { + List blacklist = new ArrayList<>(); + blacklist.add("blacklist item"); + Constraint constraint = new Constraint(blacklist); + + assertNull(constraint.getFreq_limit_per_target()); + assertNull(constraint.getTime_window()); + assertNull(constraint.getActive_time_range()); + assertEquals(blacklist, constraint.getBlacklist()); + } + + @Test + public void testConstraintIntegerMapOfStringStringListOfString() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + List blacklist = new ArrayList<>(); + blacklist.add("blacklist item"); + Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, blacklist); + + assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target()); + assertEquals(timeWindow, constraint.getTime_window()); + assertNull(constraint.getActive_time_range()); + assertEquals(blacklist, constraint.getBlacklist()); + } + + @Test + public void testConstraintIntegerMapOfStringStringMapOfStringString() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("timeWindowKey", "timeWindowValue"); + Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange); + + assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target()); + assertEquals(timeWindow, constraint.getTime_window()); + assertEquals(activeTimeRange, constraint.getActive_time_range()); + assertNull(constraint.getBlacklist()); + + } + + @Test + public void testConstraintIntegerMapOfStringStringMapOfStringStringListOfString() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("timeWindowKey", "timeWindowValue"); + List blacklist = new ArrayList<>(); + blacklist.add("blacklist item"); + Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange, blacklist); + + assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target()); + assertEquals(timeWindow, constraint.getTime_window()); + assertEquals(activeTimeRange, constraint.getActive_time_range()); + assertEquals(blacklist, constraint.getBlacklist()); + } + + @Test + public void testConstraintConstraint() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("timeWindowKey", "timeWindowValue"); + List blacklist = new ArrayList<>(); + blacklist.add("blacklist item"); + Constraint constraint1 = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange, blacklist); + Constraint constraint2 = new Constraint(constraint1); + + assertEquals(freqLimitPerTarget, constraint2.getFreq_limit_per_target()); + assertEquals(timeWindow, constraint2.getTime_window()); + assertEquals(activeTimeRange, constraint2.getActive_time_range()); + assertEquals(blacklist, constraint2.getBlacklist()); + } + + @Test + public void testIsValid() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + + Constraint constraint = new Constraint(); + assertTrue(constraint.isValid()); + + constraint.setFreq_limit_per_target(freqLimitPerTarget); + assertFalse(constraint.isValid()); + + constraint.setTime_window(timeWindow); + assertTrue(constraint.isValid()); + + constraint.setFreq_limit_per_target(null); + assertFalse(constraint.isValid()); + } + + @Test + public void testToString() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("timeWindowKey", "timeWindowValue"); + List blacklist = new ArrayList<>(); + blacklist.add("blacklist item"); + Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange, blacklist); + + assertEquals(constraint.toString(), "Constraint [freq_limit_per_target=" + freqLimitPerTarget + ", time_window=" + timeWindow + ", active_time_range=" + activeTimeRange + ", blacklist=" + blacklist + "]"); + } + + @Test + public void testEquals() { + Integer freqLimitPerTarget = 10; + Map timeWindow = new HashMap<>(); + Map activeTimeRange = new HashMap<>(); + List blacklist = new ArrayList<>(); + blacklist.add("blacklist item"); + + Constraint constraint1 = new Constraint(); + Constraint constraint2 = new Constraint(); + assertTrue(constraint1.equals(constraint2)); + + constraint1.setFreq_limit_per_target(freqLimitPerTarget); + assertFalse(constraint1.equals(constraint2)); + constraint2.setFreq_limit_per_target(freqLimitPerTarget); + assertTrue(constraint1.equals(constraint2)); + assertEquals(constraint1.hashCode(), constraint2.hashCode()); + + constraint1.setTime_window(timeWindow); + assertFalse(constraint1.equals(constraint2)); + constraint2.setTime_window(timeWindow); + assertTrue(constraint1.equals(constraint2)); + assertEquals(constraint1.hashCode(), constraint2.hashCode()); + + constraint1.setActive_time_range(activeTimeRange); + assertFalse(constraint1.equals(constraint2)); + constraint2.setActive_time_range(activeTimeRange); + assertTrue(constraint1.equals(constraint2)); + assertEquals(constraint1.hashCode(), constraint2.hashCode()); + + constraint1.setBlacklist(blacklist); + assertFalse(constraint1.equals(constraint2)); + constraint2.setBlacklist(blacklist); + assertTrue(constraint1.equals(constraint2)); + assertEquals(constraint1.hashCode(), constraint2.hashCode()); + } + + @Test + public void testEqualsSameObject(){ + Constraint constraint = new Constraint(); + assertTrue(constraint.equals(constraint)); + } + + @Test + public void testEqualsNull(){ + Constraint constraint = new Constraint(); + assertFalse(constraint.equals(null)); + } + + @Test + public void testEqualsInstanceOfDiffClass(){ + Constraint constraint = new Constraint(); + assertFalse(constraint.equals("")); + } + +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java index d1a35413e..711997dac 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java @@ -27,6 +27,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.util.LinkedList; import org.junit.Test; import org.slf4j.Logger; @@ -49,6 +50,69 @@ public class ControlLoopGuardTest { this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); } + @Test + public void testConstructorControlLoopGuard(){ + Guard guard1 = new Guard(); + GuardPolicy guardPolicy1 = new GuardPolicy(); + GuardPolicy guardPolicy2 = new GuardPolicy(); + LinkedList guardPolicies = new LinkedList<>(); + guardPolicies.add(guardPolicy1); + guardPolicies.add(guardPolicy2); + + ControlLoopGuard controlLoopGuard1 = new ControlLoopGuard(); + controlLoopGuard1.setGuard(guard1); + controlLoopGuard1.setGuards(guardPolicies); + ControlLoopGuard controlLoopGuard2 = new ControlLoopGuard(controlLoopGuard1); + + assertEquals(guard1, controlLoopGuard2.getGuard()); + assertEquals(guardPolicies, controlLoopGuard2.getGuards()); + } + + @Test + public void testEqualsAndHashCode(){ + Guard guard1 = new Guard(); + GuardPolicy guardPolicy1 = new GuardPolicy(); + GuardPolicy guardPolicy2 = new GuardPolicy(); + LinkedList guardPolicies = new LinkedList<>(); + guardPolicies.add(guardPolicy1); + guardPolicies.add(guardPolicy2); + + ControlLoopGuard controlLoopGuard1 = new ControlLoopGuard(); + ControlLoopGuard controlLoopGuard2 = new ControlLoopGuard(); + + assertTrue(controlLoopGuard1.equals(controlLoopGuard2)); + assertEquals(controlLoopGuard1.hashCode(), controlLoopGuard2.hashCode()); + + controlLoopGuard1.setGuard(guard1); + assertFalse(controlLoopGuard1.equals(controlLoopGuard2)); + controlLoopGuard2.setGuard(guard1); + assertTrue(controlLoopGuard1.equals(controlLoopGuard2)); + assertEquals(controlLoopGuard1.hashCode(), controlLoopGuard2.hashCode()); + + controlLoopGuard1.setGuards(guardPolicies); + assertFalse(controlLoopGuard1.equals(controlLoopGuard2)); + controlLoopGuard2.setGuards(guardPolicies); + assertTrue(controlLoopGuard1.equals(controlLoopGuard2)); + assertEquals(controlLoopGuard1.hashCode(), controlLoopGuard2.hashCode()); + } + + @Test + public void testEqualsSameObject(){ + ControlLoopGuard controlLoopGuard = new ControlLoopGuard(); + assertTrue(controlLoopGuard.equals(controlLoopGuard)); + } + + @Test + public void testEqualsNull(){ + ControlLoopGuard controlLoopGuard = new ControlLoopGuard(); + assertFalse(controlLoopGuard.equals(null)); + } + + @Test + public void testEqualsInstanceOfDiffClass(){ + ControlLoopGuard controlLoopGuard = new ControlLoopGuard(); + assertFalse(controlLoopGuard.equals("")); + } public void test(String testFile) { try (InputStream is = new FileInputStream(new File(testFile))) { diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java new file mode 100644 index 000000000..3bf801d57 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java @@ -0,0 +1,267 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.controlloop.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.LinkedList; +import java.util.List; + +import org.junit.Test; + +public class GuardPolicyTest { + + @Test + public void testConstructor(){ + GuardPolicy guardPolicy = new GuardPolicy(); + + assertNotNull(guardPolicy.getId()); + assertNull(guardPolicy.getName()); + assertNull(guardPolicy.getDescription()); + assertNull(guardPolicy.getMatch_parameters()); + assertNull(guardPolicy.getLimit_constraints()); + } + + @Test + public void testConstructorString(){ + String id = "guard id"; + GuardPolicy guardPolicy = new GuardPolicy(id); + + assertEquals(id, guardPolicy.getId()); + assertNull(guardPolicy.getName()); + assertNull(guardPolicy.getDescription()); + assertNull(guardPolicy.getMatch_parameters()); + assertNull(guardPolicy.getLimit_constraints()); + } + + @Test + public void testConstructorStringStringStringMatchParameters(){ + String id = "guard id"; + String name = "guard name"; + String description = "guard description"; + MatchParameters matchParameters = new MatchParameters(); + List limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + GuardPolicy guardPolicy = new GuardPolicy(id, name, description, matchParameters); + + assertNotNull(guardPolicy.getId()); + assertEquals(name, guardPolicy.getName()); + assertEquals(description, guardPolicy.getDescription()); + assertEquals(matchParameters, guardPolicy.getMatch_parameters()); + assertNull(guardPolicy.getLimit_constraints()); + } + + @Test + public void testConstructorStringMatchParametersList(){ + String name = "guard name"; + MatchParameters matchParameters = new MatchParameters(); + List limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + GuardPolicy guardPolicy = new GuardPolicy(name, matchParameters, limitConstraints); + + assertNotNull(guardPolicy.getId()); + assertEquals(name, guardPolicy.getName()); + assertNull(guardPolicy.getDescription()); + assertEquals(matchParameters, guardPolicy.getMatch_parameters()); + assertEquals(limitConstraints, guardPolicy.getLimit_constraints()); + } + + @Test + public void testConstructorStringStringMatchParametersList(){ + String name = "guard name"; + String description = "guard description"; + MatchParameters matchParameters = new MatchParameters(); + List limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + GuardPolicy guardPolicy = new GuardPolicy(name, description, matchParameters, limitConstraints); + + assertNotNull(guardPolicy.getId()); + assertEquals(name, guardPolicy.getName()); + assertEquals(description, guardPolicy.getDescription()); + assertEquals(matchParameters, guardPolicy.getMatch_parameters()); + assertEquals(limitConstraints, guardPolicy.getLimit_constraints()); + } + + @Test + public void testConstructorStringStringStringMatchParametersList(){ + String id = "guard id"; + String name = "guard name"; + String description = "guard description"; + MatchParameters matchParameters = new MatchParameters(); + List limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + GuardPolicy guardPolicy = new GuardPolicy(id, name, description, matchParameters, limitConstraints); + + assertEquals(id, guardPolicy.getId()); + assertEquals(name, guardPolicy.getName()); + assertEquals(description, guardPolicy.getDescription()); + assertEquals(matchParameters, guardPolicy.getMatch_parameters()); + assertEquals(limitConstraints, guardPolicy.getLimit_constraints()); + } + + @Test + public void testConstructorGuardPolicy(){ + String id = "guard id"; + String name = "guard name"; + String description = "guard description"; + MatchParameters matchParameters = new MatchParameters(); + List limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + GuardPolicy guardPolicy1 = new GuardPolicy(id, name, description, matchParameters, limitConstraints); + + GuardPolicy guardPolicy2 = new GuardPolicy(guardPolicy1); + + + assertEquals(id, guardPolicy2.getId()); + assertEquals(name, guardPolicy2.getName()); + assertEquals(description, guardPolicy2.getDescription()); + assertEquals(matchParameters, guardPolicy2.getMatch_parameters()); + assertEquals(limitConstraints, guardPolicy2.getLimit_constraints()); + } + + @Test + public void testSetAndGetId(){ + String id = "guard id"; + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setId(id); + assertEquals(id, guardPolicy.getId()); + } + + @Test + public void testSetAndGetName(){ + String name = "guard name"; + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setName(name); + assertEquals(name, guardPolicy.getName()); + } + + @Test + public void testSetAndGetDescription(){ + String description = "guard description"; + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setDescription(description); + assertEquals(description, guardPolicy.getDescription()); + } + + @Test + public void testSetAndGetMatchParameters(){ + MatchParameters matchParameters = new MatchParameters(); + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setMatch_parameters(matchParameters); + assertEquals(matchParameters, guardPolicy.getMatch_parameters()); + } + + @Test + public void testSetAndGetLimitConstraints(){ + LinkedList limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setLimit_constraints(limitConstraints); + assertEquals(limitConstraints, guardPolicy.getLimit_constraints()); + } + + @Test + public void testIsValid(){ + GuardPolicy guardPolicy = new GuardPolicy(); + assertFalse(guardPolicy.isValid()); + + guardPolicy.setName("guard name"); + assertTrue(guardPolicy.isValid()); + + guardPolicy.setId(null); + assertFalse(guardPolicy.isValid()); + } + + @Test + public void testToString(){ + String id = "guard id"; + String name = "guard name"; + String description = "guard description"; + MatchParameters matchParameters = new MatchParameters(); + List limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + GuardPolicy guardPolicy = new GuardPolicy(id, name, description, matchParameters, limitConstraints); + + assertEquals(guardPolicy.toString(), "Policy [id=guard id, name=guard name, description=guard description, " + + "match_parameters=MatchParameters [controlLoopName=null, actor=null, recipe=null, targets=null], " + + "limitConstraints=[Constraint [freq_limit_per_target=null, time_window=null, active_time_range=null, blacklist=null]]]", guardPolicy.toString()); + } + + @Test + public void testEquals(){ + String id = "guard id"; + String name = "guard name"; + String description = "guard description"; + GuardPolicy guardPolicy1 = new GuardPolicy(id); + GuardPolicy guardPolicy2 = new GuardPolicy(); + assertFalse(guardPolicy1.equals(guardPolicy2)); + + guardPolicy2.setId(id); + assertTrue(guardPolicy1.equals(guardPolicy2)); + assertEquals(guardPolicy1.hashCode(), guardPolicy2.hashCode()); + + guardPolicy1.setName(name); + assertFalse(guardPolicy1.equals(guardPolicy2)); + guardPolicy2.setName(name); + assertTrue(guardPolicy1.equals(guardPolicy2)); + assertEquals(guardPolicy1.hashCode(), guardPolicy2.hashCode()); + + guardPolicy1.setDescription(description); + assertFalse(guardPolicy1.equals(guardPolicy2)); + guardPolicy2.setDescription(description); + assertTrue(guardPolicy1.equals(guardPolicy2)); + assertEquals(guardPolicy1.hashCode(), guardPolicy2.hashCode()); + + MatchParameters matchParameters = new MatchParameters(); + guardPolicy1.setMatch_parameters(matchParameters); + assertFalse(guardPolicy1.equals(guardPolicy2)); + guardPolicy2.setMatch_parameters(matchParameters); + assertTrue(guardPolicy1.equals(guardPolicy2)); + assertEquals(guardPolicy1.hashCode(), guardPolicy2.hashCode()); + + LinkedList limitConstraints = new LinkedList<>(); + limitConstraints.add(new Constraint()); + guardPolicy1.setLimit_constraints(limitConstraints); + assertFalse(guardPolicy1.equals(guardPolicy2)); + guardPolicy2.setLimit_constraints(limitConstraints); + assertTrue(guardPolicy1.equals(guardPolicy2)); + assertEquals(guardPolicy1.hashCode(), guardPolicy2.hashCode()); + } + + @Test + public void testEqualsSameObject(){ + GuardPolicy guardPolicy = new GuardPolicy(); + assertTrue(guardPolicy.equals(guardPolicy)); + } + + @Test + public void testEqualsNull(){ + GuardPolicy guardPolicy = new GuardPolicy(); + assertFalse(guardPolicy.equals(null)); + } + + @Test + public void testEqualsInstanceOfDiffClass(){ + GuardPolicy guardPolicy = new GuardPolicy(); + assertFalse(guardPolicy.equals("")); + } +} diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_control_loop_no_control_loop_name.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_control_loop_no_control_loop_name.yaml new file mode 100644 index 000000000..ce51ff618 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_control_loop_no_control_loop_name.yaml @@ -0,0 +1,23 @@ +controlLoop: + controlLoopName: + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policies_1.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policies_1.yaml deleted file mode 100644 index f6ad68425..000000000 --- a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policies_1.yaml +++ /dev/null @@ -1,25 +0,0 @@ -controlLoop: - controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 - version: 1.0.0 - services: - - serviceName: Foo Service - resources: - - resourceName: Bar VNF - resourceType: VF - trigger_policy: unique-policy-id-1-restart - timeout: 1200 - -policies: - - id: unique-policy-id-1-restart - name: Restart Policy for Trigger Event - description: - actor: APPC - recipe: Restart - target: VM - retry: 2 - timeout: 300 - success: FINAL_FAILURE - failure: unique-policy-id-3-rebuild - failure_timeout: unique-policy-id-3-rebuild - failure_retries: unique-policy-id-3-rebuild - failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_connected_to_unknown_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_connected_to_unknown_policy.yaml new file mode 100644 index 000000000..ad65dbfcf --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_connected_to_unknown_policy.yaml @@ -0,0 +1,23 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure: unknown-policy diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_exception_connected_to_unknown_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_exception_connected_to_unknown_policy.yaml new file mode 100644 index 000000000..334f2aa6e --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_exception_connected_to_unknown_policy.yaml @@ -0,0 +1,23 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_exception: unknown-policy diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_guard_connected_to_unknown_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_guard_connected_to_unknown_policy.yaml new file mode 100644 index 000000000..8d39ee86d --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_guard_connected_to_unknown_policy.yaml @@ -0,0 +1,23 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_guard: unknown-policy diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_retries_connected_to_unknown_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_retries_connected_to_unknown_policy.yaml new file mode 100644 index 000000000..4108369a5 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_retries_connected_to_unknown_policy.yaml @@ -0,0 +1,23 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_retries: unknown-policy diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_timeout_connected_to_unknown_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_timeout_connected_to_unknown_policy.yaml new file mode 100644 index 000000000..5dcc96a86 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_failure_timeout_connected_to_unknown_policy.yaml @@ -0,0 +1,23 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_timeout: unknown-policy diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_success_connected_to_unknown_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_success_connected_to_unknown_policy.yaml new file mode 100644 index 000000000..6df86e390 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policy_success_connected_to_unknown_policy.yaml @@ -0,0 +1,23 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: unknown-policy diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_no_trigger_id.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_no_trigger_id.yaml new file mode 100644 index 000000000..8231b2498 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_no_trigger_id.yaml @@ -0,0 +1,21 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/empty.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/empty.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test.yaml index b89a725cf..55caa0b9f 100644 --- a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test.yaml +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test.yaml @@ -15,81 +15,290 @@ policies: description: actor: APPC recipe: Restart - target: VM + target: + type: VM + resourceID: vm1 retry: 2 timeout: 300 - success: unique-policy-id-2-healthcheck-restart + success: unique-policy-id-2-modifyconfig failure: unique-policy-id-3-rebuild failure_timeout: unique-policy-id-3-rebuild failure_retries: unique-policy-id-3-rebuild - failure_exception: final_failure_exception + failure_exception: unique-policy-id-7-modifyconfig-for-failure + failure_guard: unique-policy-id-7-modifyconfig-for-failure - - id: unique-policy-id-2-healthcheck-restart - name: HealthCheck Policy + - id: unique-policy-id-2-modifyconfig + name: ModifyConfig Policy description: actor: APPC - recipe: HealthCheck - target: VM + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 retry: 2 timeout: 300 - success: final_success + success: FINAL_SUCCESS failure: unique-policy-id-3-rebuild failure_timeout: unique-policy-id-3-rebuild failure_retries: unique-policy-id-3-rebuild - failure_exception: final_failure_exception + failure_exception: FINAL_FAILURE_EXCEPTION - id: unique-policy-id-3-rebuild name: Rebuild Policy description: actor: APPC recipe: Rebuild - target: VM + target: + type: VM + resourceID: vm1 retry: 0 timeout: 600 - success: unique-policy-id-4-healthcheck-rebuild + success: unique-policy-id-4-modifyconfig failure: unique-policy-id-5-migrate failure_timeout: unique-policy-id-5-migrate failure_retries: unique-policy-id-5-migrate - failure_exception: final_failure_exception + failure_exception: FINAL_FAILURE_EXCEPTION - - id: unique-policy-id-4-healthcheck-rebuild + - id: unique-policy-id-4-modifyconfig name: HealthCheck the Rebuild Policy description: actor: APPC - recipe: HealthCheck - target: VM + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 retry: 2 timeout: 300 - success: final_success + success: FINAL_SUCCESS failure: unique-policy-id-5-migrate failure_timeout: unique-policy-id-5-migrate failure_retries: unique-policy-id-5-migrate - failure_exception: final_failure_exception + failure_exception: FINAL_FAILURE_EXCEPTION - id: unique-policy-id-5-migrate name: Migrate Policy description: actor: APPC recipe: Migrate - target: VM + target: + type: VM + resourceID: vm1 retry: 0 timeout: 600 - success: unique-policy-id-6-healthcheck-migrate - failure: final_failure - failure_timeout: final_failure_timeout - failure_retries: final_failure_retries - failure_exception: final_failure_exception + success: unique-policy-id-6-modifyconfig + failure: FINAL_FAILURE + failure_timeout: FINAL_FAILURE_TIMEOUT + failure_retries: FINAL_FAILURE_RETRIES + failure_exception: FINAL_FAILURE_EXCEPTION - - id: unique-policy-id-6-healthcheck-migrate - name: Healthcheck the Migrate Policy + - id: unique-policy-id-6-modifyconfig + name: ModifyConfig after Migrate Policy description: actor: APPC - recipe: HealthCheck - target: VM + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 retry: 2 timeout: 300 - success: final_success - failure: final_failure - failure_timeout: final_failure_timeout - failure_retries: final_failure_retries - failure_exception: final_failure_exception + success: FINAL_SUCCESS + failure: FINAL_FAILURE + failure_timeout: FINAL_FAILURE_TIMEOUT + failure_retries: FINAL_FAILURE_RETRIES + failure_exception: FINAL_FAILURE_EXCEPTION + + - id: unique-policy-id-7-modifyconfig-for-failure + name: ModifyConfig for Failure + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + failure: FINAL_FAILURE + failure_timeout: FINAL_FAILURE_TIMEOUT + failure_retries: FINAL_FAILURE_RETRIES + failure_exception: FINAL_FAILURE_EXCEPTION + + - id: + name: invalid policy - id is null + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: SUCCESS + name: invalid policy - id is a PolicyResult + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: FINAL_SUCCESS + name: invalid policy - id is a FinalResult + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: invalid-policy-null-actor + name: invalid policy - actor is null + description: + actor: + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: invalid-policy-unknown-actor + name: invalid policy - actor is unknown + description: + actor: UnknownActor + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: invalid-policy-null-receipe + name: invalid policy - receipe is null + description: + actor: APPC + recipe: + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: invalid-policy-unknown-receipe + name: invalid policy - unknown receipe + description: + actor: APPC + recipe: UnknownReceipe + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: invalid-policy-null-target + name: invalid policy - target is null + description: + actor: APPC + recipe: ModifyConfig + target: + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: invalid-policy-null-target-type + name: invalid policy - target type is null + description: + actor: APPC + recipe: ModifyConfig + target: + type: + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_SUCCESS + + - id: invalid-policy-invalid-success-policy + name: invalid policy - success policy is invalid + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + success: FINAL_FAILURE + + - id: invalid-policy-invalid-failure-policy + name: invalid policy - failure policy is invalid + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure: FINAL_FAILURE_TIMEOUT + + - id: invalid-policy-invalid-failure-timeout-policy + name: invalid policy - failure timeout policy is invalid + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_timeout: FINAL_FAILURE_RETRIES + + - id: invalid-policy-invalid-failure-retries-policy + name: invalid policy - failure retries policy is invalid + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_retries: FINAL_FAILURE_EXCEPTION + + - id: invalid-policy-invalid-failure-exception-policy + name: invalid policy - failure exception policy is invalid + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_exception: FINAL_FAILURE_GUARD + + - id: invalid-policy-invalid-failure-guard-policy + name: invalid policy - failure guard policy is invalid + description: + actor: APPC + recipe: ModifyConfig + target: + type: VM + resourceID: vm1 + retry: 2 + timeout: 300 + failure_guard: FINAL_SUCCESS + + -- cgit 1.2.3-korg