From 8279af376b435e1d7dd118a1955c5681edf3b847 Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Wed, 29 Aug 2018 07:58:53 -0400 Subject: Fix remaining checkstyle Lots of formatting, missing javadoc, distance from use, imports must be explicit, ordering of methods. Fixed some abbreviation problems in classes and renamed JUnit tests to fix this. Issue-ID: POLICY-883 Change-Id: I8494f63d88d63c0232aca97f7bcc848816228fb1 Signed-off-by: Pamela Dragosh --- .../actor/so/SOActorServiceProvider.java | 6 +- .../actor/so/SoActorServiceProviderTest.java | 180 +++++++++ .../actor/so/TestSOActorServiceProvider.java | 180 --------- .../actor/vfc/TestVFCActorServiceProvider.java | 117 ------ .../actor/vfc/VfcActorServiceProviderTest.java | 118 ++++++ .../eventmanager/ControlLoopEventManager.java | 16 +- .../eventmanager/ControlLoopEventManagerTest.java | 18 +- .../ControlLoopOperationManagerTest.java | 4 +- .../feature/trans/ControlLoopMetricsFeature.java | 9 +- .../guard/PolicyGuardXacmlRequestAttributes.java | 26 +- .../org/onap/policy/guard/impl/PNFTargetLock.java | 6 +- .../onap/policy/guard/PIPEngineGetHistoryTest.java | 428 -------------------- .../onap/policy/guard/PipEngineGetHistoryTest.java | 428 ++++++++++++++++++++ .../org/onap/policy/guard/PolicyGuardTest.java | 2 +- .../src/test/resources/META-INF/persistence.xml | 37 +- .../src/test/resources/blacklist_template.xml | 145 ++++--- .../test/resources/frequency_limiter_template.xml | 158 +++++--- .../org/onap/policy/aai/AaiNqGenericVnfTest.java | 3 +- .../org/onap/policy/aai/AaiNqVfModuleTest.java | 1 + controlloop/common/model-impl/appc/pom.xml | 40 -- controlloop/common/model-impl/appclcm/pom.xml | 40 -- controlloop/common/model-impl/events/pom.xml | 41 -- .../java/org/onap/policy/rest/RESTManager.java | 24 +- .../main/java/org/onap/policy/sdc/Resource.java | 99 +++-- .../java/org/onap/policy/sdc/ResourceInstance.java | 85 ++-- .../java/org/onap/policy/sdc/ResourceType.java | 34 +- .../src/main/java/org/onap/policy/sdc/Service.java | 50 ++- .../java/org/onap/policy/sdc/ServiceInstance.java | 60 ++- .../java/org/onap/policy/sdc/TestResource.java | 28 +- .../org/onap/policy/sdc/TestResourceInstance.java | 10 +- .../org/onap/policy/so/SOAsyncRequestStatus.java | 6 +- .../org/onap/policy/so/SOCloudConfiguration.java | 6 +- .../org/onap/policy/so/SOInstanceReferences.java | 6 +- .../main/java/org/onap/policy/so/SOManager.java | 11 +- .../main/java/org/onap/policy/so/SOModelInfo.java | 6 +- .../onap/policy/so/SOPolicyExceptionHolder.java | 6 +- .../java/org/onap/policy/so/SORelatedInstance.java | 6 +- .../policy/so/SORelatedInstanceListElement.java | 6 +- .../main/java/org/onap/policy/so/SORequest.java | 6 +- .../java/org/onap/policy/so/SORequestDetails.java | 59 ++- .../java/org/onap/policy/so/SORequestError.java | 6 +- .../java/org/onap/policy/so/SORequestInfo.java | 6 +- .../org/onap/policy/so/SORequestParameters.java | 3 +- .../org/onap/policy/so/SORequestReferences.java | 6 +- .../java/org/onap/policy/so/SORequestStatus.java | 9 +- .../main/java/org/onap/policy/so/SOResponse.java | 6 +- .../java/org/onap/policy/so/SOResponseWrapper.java | 14 +- .../onap/policy/so/SOServiceExceptionHolder.java | 6 +- .../java/org/onap/policy/so/SOSubscriberInfo.java | 6 +- .../org/onap/policy/so/DummyWorkingMemory.java | 25 +- .../java/org/onap/policy/so/TestSOManager.java | 275 ------------- .../java/org/onap/policy/so/TestSoDummyServer.java | 33 +- .../java/org/onap/policy/so/TestSoManager.java | 278 +++++++++++++ .../org/onap/policy/so/TestSoRequestDetails.java | 92 ++--- .../org/onap/policy/so/TestSoResponseWrapper.java | 46 +-- .../policy/vnf/trafficgenerator/PGRequest.java | 9 +- .../onap/policy/vnf/trafficgenerator/PGStream.java | 9 +- .../policy/vnf/trafficgenerator/PGStreams.java | 9 +- .../onap/policy/vnf/trafficgenerator/TestDemo.java | 4 +- .../org/onap/policy/vfc/VFCHealActionVmInfo.java | 45 +-- .../onap/policy/vfc/VFCHealAdditionalParams.java | 45 +-- .../java/org/onap/policy/vfc/VFCHealRequest.java | 61 +-- .../main/java/org/onap/policy/vfc/VFCManager.java | 16 +- .../main/java/org/onap/policy/vfc/VFCRequest.java | 43 +- .../main/java/org/onap/policy/vfc/VFCResponse.java | 43 +- .../org/onap/policy/vfc/VFCResponseDescriptor.java | 74 ++-- .../org/onap/policy/vfc/util/Serialization.java | 12 +- .../test/java/org/onap/policy/vfc/TestDemo.java | 3 +- .../onap/policy/vfc/TestVFCHealActionVmInfo.java | 45 --- .../policy/vfc/TestVFCHealAdditionalParams.java | 45 --- .../org/onap/policy/vfc/TestVFCHealRequest.java | 49 --- .../java/org/onap/policy/vfc/TestVFCManager.java | 275 ------------- .../java/org/onap/policy/vfc/TestVFCRequest.java | 51 --- .../java/org/onap/policy/vfc/TestVFCResponse.java | 49 --- .../onap/policy/vfc/TestVFCResponseDescriptor.java | 64 --- .../onap/policy/vfc/TestVfcHealActionVmInfo.java | 48 +++ .../policy/vfc/TestVfcHealAdditionalParams.java | 48 +++ .../org/onap/policy/vfc/TestVfcHealRequest.java | 52 +++ .../java/org/onap/policy/vfc/TestVfcManager.java | 303 ++++++++++++++ .../java/org/onap/policy/vfc/TestVfcRequest.java | 54 +++ .../java/org/onap/policy/vfc/TestVfcResponse.java | 52 +++ .../onap/policy/vfc/TestVfcResponseDescriptor.java | 67 ++++ .../onap/policy/vfc/util/TestSerialization.java | 11 +- .../controlloop/compiler/ControlLoopCompiler.java | 4 +- .../guard/compiler/ControlLoopGuardCompiler.java | 38 +- .../policy/controlloop/policy/ControlLoop.java | 9 +- .../controlloop/policy/ControlLoopPolicy.java | 23 +- .../policy/controlloop/policy/FinalResult.java | 13 + .../policy/OperationsAccumulateParams.java | 27 +- .../org/onap/policy/controlloop/policy/Policy.java | 38 ++ .../policy/controlloop/policy/PolicyResult.java | 8 +- .../org/onap/policy/controlloop/policy/Target.java | 51 +-- .../policy/builder/ControlLoopPolicyBuilder.java | 180 +++++---- .../controlloop/policy/builder/MessageLevel.java | 12 +- .../builder/impl/ControlLoopPolicyBuilderImpl.java | 174 ++++---- .../controlloop/policy/guard/Constraint.java | 58 ++- .../controlloop/policy/guard/ControlLoopGuard.java | 27 +- .../policy/controlloop/policy/guard/Guard.java | 19 +- .../controlloop/policy/guard/GuardPolicy.java | 20 + .../controlloop/policy/guard/MatchParameters.java | 35 +- .../guard/builder/ControlLoopGuardBuilder.java | 51 ++- .../builder/impl/ControlLoopGuardBuilderImpl.java | 32 +- .../compiler/ControlLoopCompilerTest.java | 12 +- .../compiler/ControlLoopGuardCompilerTest.java | 6 + .../policy/ControlLoopPolicyBuilderTest.java | 119 +++--- .../controlloop/policy/ControlLoopPolicyTest.java | 19 +- .../policy/controlloop/policy/ControlLoopTest.java | 25 +- .../policy/OperationsAccumulateParamsTest.java | 10 +- .../controlloop/policy/guard/ConstraintTest.java | 16 +- .../policy/guard/ControlLoopGuardBuilderTest.java | 43 +- .../policy/guard/ControlLoopGuardTest.java | 19 +- .../controlloop/policy/guard/GuardPolicyTest.java | 7 +- .../onap/policy/simulators/SoSimulatorTest.java | 1 + .../src/main/resources/blacklist_template.xml | 145 ++++--- .../main/resources/frequency_limiter_template.xml | 158 +++++--- .../resources/frequency_limiter_template_old.xml | 122 ++++-- .../template/demo/ControlLoopFailureTest.java | 48 ++- .../java/org/onap/policy/template/demo/Util.java | 439 +++++++++++---------- .../policy/template/demo/VCPEControlLoopTest.java | 399 ------------------- .../policy/template/demo/VDNSControlLoopTest.java | 403 ------------------- .../policy/template/demo/VFCControlLoopTest.java | 362 ----------------- .../policy/template/demo/VFWControlLoopTest.java | 427 -------------------- .../policy/template/demo/VcpeControlLoopTest.java | 407 +++++++++++++++++++ .../policy/template/demo/VdnsControlLoopTest.java | 411 +++++++++++++++++++ .../policy/template/demo/VfcControlLoopTest.java | 376 ++++++++++++++++++ .../policy/template/demo/VfwControlLoopTest.java | 435 ++++++++++++++++++++ .../src/test/resources/META-INF/persistence.xml | 39 +- 127 files changed, 5439 insertions(+), 4736 deletions(-) create mode 100644 controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java delete mode 100644 controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java delete mode 100644 controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java create mode 100644 controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java create mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/PipEngineGetHistoryTest.java delete mode 100644 controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSOManager.java create mode 100644 controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoManager.java delete mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealActionVmInfo.java delete mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealAdditionalParams.java delete mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealRequest.java delete mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCManager.java delete mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCRequest.java delete mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponse.java delete mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponseDescriptor.java create mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealActionVmInfo.java create mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealAdditionalParams.java create mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealRequest.java create mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcManager.java create mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcRequest.java create mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponse.java create mode 100644 controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponseDescriptor.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java (limited to 'controlloop') diff --git a/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java b/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java index ccc13a557..602bc284b 100644 --- a/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java +++ b/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java @@ -20,6 +20,9 @@ package org.onap.policy.controlloop.actor.so; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; @@ -45,9 +48,6 @@ import org.onap.policy.so.SORequestParameters; import org.onap.policy.so.util.Serialization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.gson.reflect.TypeToken; public class SOActorServiceProvider implements Actor { private static final Logger logger = LoggerFactory.getLogger(SOActorServiceProvider.class); diff --git a/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java b/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java new file mode 100644 index 000000000..fcc55ead3 --- /dev/null +++ b/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * TestSOActorServiceProvider + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T. 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.actor.so; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.UUID; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.onap.policy.aai.AaiNqResponse; +import org.onap.policy.aai.AaiNqResponseWrapper; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.so.SORequest; +import org.onap.policy.so.SORequestParameters; +import org.onap.policy.so.util.Serialization; + +public class SoActorServiceProviderTest { + + @Test + public void testConstructRequest() throws Exception { + VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); + final ControlLoopOperation operation = new ControlLoopOperation(); + final AaiNqResponseWrapper aaiNqResp = loadAaiResponse(onset, "aai/AaiNqResponse-Full.json"); + + final UUID requestId = UUID.randomUUID(); + onset.setRequestId(requestId); + + Policy policy = new Policy(); + policy.setActor("Dorothy"); + policy.setRecipe("GoToOz"); + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp)); + + policy.setActor("SO"); + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp)); + + policy.setRecipe("VF Module Create"); + + // empty policy payload + SORequest request = new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp); + assertNotNull(request); + + assertEquals("my_module_3", request.getRequestDetails().getRequestInfo().getInstanceName()); + assertEquals("policy", request.getRequestDetails().getRequestInfo().getRequestorId()); + assertEquals("RegionOne", request.getRequestDetails().getCloudConfiguration().getLcpCloudRegionId()); + + // non-empty policy payload + policy.setPayload(makePayload()); + request = new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp); + assertNotNull(request); + assertEquals(true, request.getRequestDetails().getRequestParameters().isUsePreload()); + assertEquals("avalue", request.getRequestDetails().getRequestParameters().getUserParams().get(0).get("akey")); + assertEquals(1, request.getRequestDetails().getConfigurationParameters().size()); + assertEquals("cvalue", request.getRequestDetails().getConfigurationParameters().get(0).get("ckey")); + + // null response + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, null)); + + // response has no base VF module + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, + loadAaiResponse(onset, "aai/AaiNqResponse-NoBase.json"))); + + // response has no non-base VF modules (other than the "dummy") + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, + loadAaiResponse(onset, "aai/AaiNqResponse-NoNonBase.json"))); + } + + @Test + public void testSendRequest() { + try { + SOActorServiceProvider.sendRequest(UUID.randomUUID().toString(), null, null); + } catch (Exception e) { + fail("Test should not throw an exception"); + } + } + + @Test + public void testMethods() { + SOActorServiceProvider sp = new SOActorServiceProvider(); + + assertEquals("SO", sp.actor()); + assertEquals(1, sp.recipes().size()); + assertEquals("VF Module Create", sp.recipes().get(0)); + assertEquals(0, sp.recipePayloads("VF Module Create").size()); + } + + /** + * Creates a policy payload containing request & configuration parameters. + * + * @return the payload + */ + private Map makePayload() { + Map payload = new TreeMap<>(); + + payload.put(SOActorServiceProvider.REQ_PARAM_NM, makeReqParams()); + payload.put(SOActorServiceProvider.CONFIG_PARAM_NM, makeConfigParams()); + + return payload; + } + + /** + * Creates request parameters. + * + * @return request parameters, encoded as JSON + */ + private String makeReqParams() { + SORequestParameters params = new SORequestParameters(); + + params.setUsePreload(true); + + Map map = new TreeMap<>(); + map.put("akey", "avalue"); + + List> lst = new LinkedList<>(); + lst.add(map); + + params.setUserParams(lst); + + return Serialization.gsonPretty.toJson(params); + } + + /** + * Creates configuration parameters. + * + * @return configuration parameters, encoded as JSON + */ + private String makeConfigParams() { + Map map = new TreeMap<>(); + map.put("ckey", "cvalue"); + + List> lst = new LinkedList<>(); + lst.add(map); + + return Serialization.gsonPretty.toJson(lst); + } + + /** + * Reads an AAI vserver named-query response from a file. + * + * @param onset the ONSET event + * @param fileName name of the file containing the JSON response + * @return output from the AAI vserver named-query + * @throws IOException if the file cannot be read + */ + private AaiNqResponseWrapper loadAaiResponse(VirtualControlLoopEvent onset, String fileName) throws IOException { + String resp = IOUtils.toString(getClass().getResource(fileName), StandardCharsets.UTF_8); + AaiNqResponse aaiNqResponse = Serialization.gsonPretty.fromJson(resp, AaiNqResponse.class); + + return new AaiNqResponseWrapper(onset.getRequestId(), aaiNqResponse); + } +} diff --git a/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java b/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java deleted file mode 100644 index c3155367b..000000000 --- a/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java +++ /dev/null @@ -1,180 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * TestSOActorServiceProvider - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018 AT&T. 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.actor.so; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.UUID; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.onap.policy.aai.AaiNqResponse; -import org.onap.policy.aai.AaiNqResponseWrapper; -import org.onap.policy.controlloop.ControlLoopOperation; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.policy.Policy; -import org.onap.policy.so.SORequest; -import org.onap.policy.so.SORequestParameters; -import org.onap.policy.so.util.Serialization; - -public class TestSOActorServiceProvider { - - @Test - public void testConstructRequest() throws Exception { - VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); - final ControlLoopOperation operation = new ControlLoopOperation(); - final AaiNqResponseWrapper aaiNqResp = loadAaiResponse(onset, "aai/AaiNqResponse-Full.json"); - - final UUID requestId = UUID.randomUUID(); - onset.setRequestId(requestId); - - Policy policy = new Policy(); - policy.setActor("Dorothy"); - policy.setRecipe("GoToOz"); - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp)); - - policy.setActor("SO"); - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp)); - - policy.setRecipe("VF Module Create"); - - // empty policy payload - SORequest request = new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp); - assertNotNull(request); - - assertEquals("my_module_3", request.getRequestDetails().getRequestInfo().getInstanceName()); - assertEquals("policy", request.getRequestDetails().getRequestInfo().getRequestorId()); - assertEquals("RegionOne", request.getRequestDetails().getCloudConfiguration().getLcpCloudRegionId()); - - // non-empty policy payload - policy.setPayload(makePayload()); - request = new SOActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp); - assertNotNull(request); - assertEquals(true, request.getRequestDetails().getRequestParameters().isUsePreload()); - assertEquals("avalue", request.getRequestDetails().getRequestParameters().getUserParams().get(0).get("akey")); - assertEquals(1, request.getRequestDetails().getConfigurationParameters().size()); - assertEquals("cvalue", request.getRequestDetails().getConfigurationParameters().get(0).get("ckey")); - - // null response - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, null)); - - // response has no base VF module - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, - loadAaiResponse(onset, "aai/AaiNqResponse-NoBase.json"))); - - // response has no non-base VF modules (other than the "dummy") - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy, - loadAaiResponse(onset, "aai/AaiNqResponse-NoNonBase.json"))); - } - - @Test - public void testSendRequest() { - try { - SOActorServiceProvider.sendRequest(UUID.randomUUID().toString(), null, null); - } catch (Exception e) { - fail("Test should not throw an exception"); - } - } - - @Test - public void testMethods() { - SOActorServiceProvider sp = new SOActorServiceProvider(); - - assertEquals("SO", sp.actor()); - assertEquals(1, sp.recipes().size()); - assertEquals("VF Module Create", sp.recipes().get(0)); - assertEquals(0, sp.recipePayloads("VF Module Create").size()); - } - - /** - * Creates a policy payload containing request & configuration parameters. - * - * @return the payload - */ - private Map makePayload() { - Map payload = new TreeMap<>(); - - payload.put(SOActorServiceProvider.REQ_PARAM_NM, makeReqParams()); - payload.put(SOActorServiceProvider.CONFIG_PARAM_NM, makeConfigParams()); - - return payload; - } - - /** - * Creates request parameters. - * - * @return request parameters, encoded as JSON - */ - private String makeReqParams() { - SORequestParameters params = new SORequestParameters(); - - params.setUsePreload(true); - - Map map = new TreeMap<>(); - map.put("akey", "avalue"); - - List> lst = new LinkedList<>(); - lst.add(map); - - params.setUserParams(lst); - - return Serialization.gsonPretty.toJson(params); - } - - /** - * Creates configuration parameters. - * - * @return configuration parameters, encoded as JSON - */ - private String makeConfigParams() { - Map map = new TreeMap<>(); - map.put("ckey", "cvalue"); - - List> lst = new LinkedList<>(); - lst.add(map); - - return Serialization.gsonPretty.toJson(lst); - } - - /** - * Reads an AAI vserver named-query response from a file. - * - * @param onset the ONSET event - * @param fileName name of the file containing the JSON response - * @return output from the AAI vserver named-query - * @throws IOException if the file cannot be read - */ - private AaiNqResponseWrapper loadAaiResponse(VirtualControlLoopEvent onset, String fileName) throws IOException { - String resp = IOUtils.toString(getClass().getResource(fileName), StandardCharsets.UTF_8); - AaiNqResponse aaiNqResponse = Serialization.gsonPretty.fromJson(resp, AaiNqResponse.class); - - return new AaiNqResponseWrapper(onset.getRequestId(), aaiNqResponse); - } -} diff --git a/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java b/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java deleted file mode 100644 index caf89eb45..000000000 --- a/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * TestVFCActorServiceProvider - * ================================================================================ - * 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.actor.vfc; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.util.Objects; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.aai.AaiGetVnfResponse; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.controlloop.ControlLoopOperation; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.policy.Policy; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.simulators.Util; -import org.onap.policy.vfc.VFCRequest; - -public class TestVFCActorServiceProvider { - - /** - * Set up for test class. - */ - @BeforeClass - public static void setUpSimulator() { - try { - Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } - - @Test - public void testConstructRequest() { - VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); - ControlLoopOperation operation = new ControlLoopOperation(); - - Policy policy = new Policy(); - policy.setRecipe("GoToOz"); - - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - onset.getAai().put("generic-vnf.vnf-id", "dorothy.gale.1939"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); - PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - UUID requestId = UUID.randomUUID(); - onset.setRequestId(requestId); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - onset.getAai().put("generic-vnf.vnf-name", "Dorothy"); - PolicyEngine.manager.getEnvironment().remove("aai.password"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - onset.getAai().put("service-instance.service-instance-id", ""); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse())); - - policy.setRecipe("Restart"); - assertNotNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse())); - - VFCRequest request = - VFCActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse()); - - assertEquals(requestId, Objects.requireNonNull(request).getRequestId()); - assertEquals("dorothy.gale.1939", request.getHealRequest().getVnfInstanceId()); - assertEquals("restartvm", request.getHealRequest().getAdditionalParams().getAction()); - } - - @Test - public void testMethods() { - VFCActorServiceProvider sp = new VFCActorServiceProvider(); - - assertEquals("VFC", sp.actor()); - assertEquals(1, sp.recipes().size()); - assertEquals("Restart", sp.recipes().get(0)); - assertEquals("VM", sp.recipeTargets("Restart").get(0)); - assertEquals(0, sp.recipePayloads("Restart").size()); - } -} diff --git a/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java b/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java new file mode 100644 index 000000000..934ea134c --- /dev/null +++ b/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * TestVFCActorServiceProvider + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corp. 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.actor.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.Objects; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.aai.AaiGetVnfResponse; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.simulators.Util; +import org.onap.policy.vfc.VFCRequest; + +public class VfcActorServiceProviderTest { + + /** + * Set up for test class. + */ + @BeforeClass + public static void setUpSimulator() { + try { + Util.buildAaiSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } + + @Test + public void testConstructRequest() { + VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); + ControlLoopOperation operation = new ControlLoopOperation(); + + Policy policy = new Policy(); + policy.setRecipe("GoToOz"); + + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + onset.getAai().put("generic-vnf.vnf-id", "dorothy.gale.1939"); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); + PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + UUID requestId = UUID.randomUUID(); + onset.setRequestId(requestId); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + onset.getAai().put("generic-vnf.vnf-name", "Dorothy"); + PolicyEngine.manager.getEnvironment().remove("aai.password"); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + onset.getAai().put("service-instance.service-instance-id", ""); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse())); + + policy.setRecipe("Restart"); + assertNotNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse())); + + VFCRequest request = + VFCActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse()); + + assertEquals(requestId, Objects.requireNonNull(request).getRequestId()); + assertEquals("dorothy.gale.1939", request.getHealRequest().getVnfInstanceId()); + assertEquals("restartvm", request.getHealRequest().getAdditionalParams().getAction()); + } + + @Test + public void testMethods() { + VFCActorServiceProvider sp = new VFCActorServiceProvider(); + + assertEquals("VFC", sp.actor()); + assertEquals(1, sp.recipes().size()); + assertEquals("Restart", sp.recipes().get(0)); + assertEquals("VM", sp.recipeTargets("Restart").get(0)); + assertEquals(0, sp.recipePayloads("Restart").size()); + } +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java index bb349591e..4b438a94d 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java @@ -791,7 +791,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable { } /** - * Does provisioning status, for an event, have a value other than ACTIVE? + * Does provisioning status, for an event, have a value other than ACTIVE. * * @param event the event * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null}, @@ -829,11 +829,11 @@ public class ControlLoopEventManager implements LockCallback, Serializable { try { if (vserverName != null) { - String aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); + String aaiHostUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url"); String aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name="; - String url = aaiHostURL + aaiGetQueryByVserver; + String url = aaiHostUrl + aaiGetQueryByVserver; logger.info("AAI Host URL by VServer: {}", url); response = new AaiManager(new RESTManager()).getQueryByVserverName(url, aaiUser, aaiPassword, requestId, vserverName); @@ -859,20 +859,20 @@ public class ControlLoopEventManager implements LockCallback, Serializable { String vnfName = event.getAai().get(GENERIC_VNF_VNF_NAME); String vnfId = event.getAai().get(GENERIC_VNF_VNF_ID); - String aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); + String aaiHostUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url"); String aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); try { if (vnfName != null) { String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name="; - String url = aaiHostURL + aaiGetQueryByVnfName; + String url = aaiHostUrl + aaiGetQueryByVnfName; logger.info("AAI Host URL by VNF name: {}", url); response = new AaiManager(new RESTManager()).getQueryByVnfName(url, aaiUser, aaiPassword, requestId, vnfName); } else if (vnfId != null) { String aaiGetQueryByVnfId = "/aai/v11/network/generic-vnfs/generic-vnf/"; - String url = aaiHostURL + aaiGetQueryByVnfId; + String url = aaiHostUrl + aaiGetQueryByVnfId; logger.info("AAI Host URL by VNF ID: {}", url); response = new AaiManager(new RESTManager()).getQueryByVnfId(url, aaiUser, aaiPassword, requestId, vnfId); @@ -890,13 +890,13 @@ public class ControlLoopEventManager implements LockCallback, Serializable { * @return output from the AAI vserver named-query */ public AaiNqResponseWrapper getNqVserverFromAai() { - if(nqVserverResponse != null) { + if (nqVserverResponse != null) { // already queried return nqVserverResponse; } String vserverName = onset.getAai().get(VSERVER_VSERVER_NAME); - if(vserverName == null) { + if (vserverName == null) { logger.warn("Missing vserver-name for AAI request {}", onset.getRequestId()); return null; } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java index 1b2d8db61..562a46e4e 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java @@ -26,6 +26,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -44,9 +45,9 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.policy.aai.AaiGetVnfResponse; import org.onap.policy.aai.AaiGetVserverResponse; -import org.onap.policy.aai.AaiNqVServer; import org.onap.policy.aai.AaiNqRequestError; import org.onap.policy.aai.AaiNqResponseWrapper; +import org.onap.policy.aai.AaiNqVServer; import org.onap.policy.aai.RelatedToProperty; import org.onap.policy.aai.Relationship; import org.onap.policy.aai.RelationshipData; @@ -101,6 +102,9 @@ public class ControlLoopEventManagerTest { HttpServletServer.factory.destroy(); } + /** + * Setup. + */ @Before public void setUp() { onset = new VirtualControlLoopEvent(); @@ -368,7 +372,7 @@ public class ControlLoopEventManagerTest { */ public static AaiGetVserverResponse getQueryByVserverName2(String urlGet, String username, String password, UUID requestId, String key) { - AaiGetVserverResponse response = new AaiGetVserverResponse(); + final AaiGetVserverResponse response = new AaiGetVserverResponse(); AaiNqVServer svr = new AaiNqVServer(); @@ -1049,7 +1053,7 @@ public class ControlLoopEventManagerTest { } @Test - public void testProcessVNFResponse_Success() throws Exception { + public void testProcessVnfResponse_Success() throws Exception { AaiGetVnfResponse resp = new AaiGetVnfResponse(); resp.setIsClosedLoopDisabled(false); resp.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE); @@ -1057,7 +1061,7 @@ public class ControlLoopEventManagerTest { } @Test - public void testProcessVNFResponse_NullResponse() throws Exception { + public void testProcessVnfResponse_NullResponse() throws Exception { thrown.expect(AaiException.class); thrown.expectMessage("AAI Response is null (query by vnf-id)"); @@ -1066,7 +1070,7 @@ public class ControlLoopEventManagerTest { } @Test - public void testProcessVNFResponse_Error() throws Exception { + public void testProcessVnfResponse_Error() throws Exception { thrown.expect(AaiException.class); thrown.expectMessage("AAI Responded with a request error (query by vnf-name)"); @@ -1080,7 +1084,7 @@ public class ControlLoopEventManagerTest { } @Test - public void testProcessVNFResponse_Disabled() throws Exception { + public void testProcessVnfResponse_Disabled() throws Exception { thrown.expect(AaiException.class); thrown.expectMessage("is-closed-loop-disabled is set to true (query by vnf-id)"); @@ -1091,7 +1095,7 @@ public class ControlLoopEventManagerTest { } @Test - public void testProcessVNFResponse_Inactive() throws Exception { + public void testProcessVnfResponse_Inactive() throws Exception { thrown.expect(AaiException.class); thrown.expectMessage("prov-status is not ACTIVE (query by vnf-name)"); diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java index cd541cf66..46452974e 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java @@ -454,10 +454,10 @@ public class ControlLoopOperationManagerTest { clom.startOperation(onsetEvent); - assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1", + assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1", clom.getOperationMessage()); assertEquals( - "actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1, Guard result: " + "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1, Guard result: " + "The Wizard Escaped", clom.getOperationMessage("The Wizard Escaped")); diff --git a/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeature.java b/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeature.java index 37bafa45d..f1d577d43 100644 --- a/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeature.java +++ b/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeature.java @@ -24,8 +24,6 @@ import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.controlloop.VirtualControlLoopNotification; import org.onap.policy.drools.features.PolicyControllerFeatureAPI; import org.onap.policy.drools.system.PolicyController; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Feature that tracks Transactions by observing Notification Patterns. @@ -35,7 +33,7 @@ public class ControlLoopMetricsFeature implements PolicyControllerFeatureAPI { /** * Feature Sequence Priority. */ - public final static int FEATURE_SEQUENCE_PRIORITY = 100000; + public static final int FEATURE_SEQUENCE_PRIORITY = 100000; /** * Properties Configuration Name. @@ -60,11 +58,6 @@ public class ControlLoopMetricsFeature implements PolicyControllerFeatureAPI { return false; } - /** - * Logger. - */ - private static Logger logger = LoggerFactory.getLogger(ControlLoopMetricsFeature.class); - /** * Intercept Control Loop Notifications. * diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java index 5e69d6435..ab1d04efa 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,20 +31,20 @@ public class PolicyGuardXacmlRequestAttributes { /** * Construct an instance. * - * @param clnameID the control loop Id - * @param actorID the actor Id - * @param operationID the operation Id - * @param targetID the target Id - * @param requestID the request Id + * @param clnameId the control loop Id + * @param actorId the actor Id + * @param operationId the operation Id + * @param targetId the target Id + * @param requestId the request Id */ - public PolicyGuardXacmlRequestAttributes(String clnameID, String actorID, String operationID, String targetID, - String requestID) { + public PolicyGuardXacmlRequestAttributes(String clnameId, String actorId, String operationId, String targetId, + String requestId) { super(); - this.clnameID = clnameID; - this.actorID = actorID; - this.operationID = operationID; - this.targetID = targetID; - this.requestID = requestID; + this.clnameID = clnameId; + this.actorID = actorId; + this.operationID = operationId; + this.targetID = targetId; + this.requestID = requestId; } @Override diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java index 06bd9fb89..904448591 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java @@ -42,14 +42,14 @@ public class PNFTargetLock implements TargetLock, Serializable { * * @param type the target type * @param target the target - * @param requestID the request Id + * @param requestId the request Id * @param callback the callback */ - public PNFTargetLock(TargetType type, String target, UUID requestID, LockCallback callback) { + public PNFTargetLock(TargetType type, String target, UUID requestId, LockCallback callback) { this.lockId = UUID.randomUUID(); this.targetType = type; this.target = target; - this.requestId = requestID; + this.requestId = requestId; this.callback = callback; } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java deleted file mode 100644 index 8c7392e71..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java +++ /dev/null @@ -1,428 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.guard; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.Status; -import com.att.research.xacml.api.pip.PIPEngine; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPRequest; -import com.att.research.xacml.api.pip.PIPResponse; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdAttribute; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.StdStatus; -import com.att.research.xacml.std.StdStatusCode; -import com.att.research.xacml.std.pip.StdPIPRequest; -import com.att.research.xacml.std.pip.StdPIPResponse; -import com.att.research.xacml.std.pip.finders.EngineFinder; -import com.att.research.xacml.util.FactoryException; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.drools.system.PolicyEngine; - -public class PIPEngineGetHistoryTest { - static PIPEngineGetHistory pegh; - private static final String ISSUER = "issuerIntw:mid:end"; - - private static EntityManagerFactory emf; - private static EntityManager em; - - /** - * Set up test class. - */ - @BeforeClass - public static void testPipEngineGetHistory() { - pegh = null; - try { - pegh = new PIPEngineGetHistory(); - } catch (Exception e) { - fail("PIPEngineGetHistory constructor failed"); - } - - // Set PU - System.setProperty(Util.PU_KEY, Util.JUNITPU); - - // Enter dummy props to avoid nullPointerException - PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_URL, "a"); - PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_USER, "b"); - PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_PASS, "c"); - - // Connect to in-mem db - emf = Persistence.createEntityManagerFactory(Util.JUNITPU); - em = emf.createEntityManager(); - - // Create necessary table - String sql = "CREATE TABLE `operationshistory10` (" + "`CLNAME` varchar(255)," + "`requestID` varchar(100)," - + "`actor` varchar(50) ," + "`operation` varchar(50)," + "`target` varchar(50)," - + "`starttime` timestamp," + "`outcome` varchar(50)," + "`message` varchar(255)," - + "`subrequestId` varchar(100)," + "`endtime` timestamp" + ")"; - Query nq = em.createNativeQuery(sql); - em.getTransaction().begin(); - nq.executeUpdate(); - em.getTransaction().commit(); - } - - @AfterClass - public static void tearDown() { - emf.close(); - } - - /** - * Setup method. - */ - @Before - public void setUp() { - // clear the table - String sql = "DELETE FROM `operationshistory10`"; - Query nq = em.createNativeQuery(sql); - em.getTransaction().begin(); - nq.executeUpdate(); - em.getTransaction().commit(); - } - - @Test - public void testAttributesRequired() { - assertTrue(pegh.attributesRequired().isEmpty()); - } - - @Test - public void testAttributesProvided() { - assertTrue(pegh.attributesProvided().isEmpty()); - } - - @Test - public void testGetAttributes() { - StdPIPRequest mockPipRequest = mock(StdPIPRequest.class); - EngineFinder mockPipFinder = mock(EngineFinder.class); - - // Test issuer null - when(mockPipRequest.getIssuer()).thenReturn(null); - try { - assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); - } catch (Exception e) { - fail("getAttributes failed"); - } - - // Test issuer not equal to our issuer - pegh.setIssuer(ISSUER); - when(mockPipRequest.getIssuer()).thenReturn("something else"); - try { - assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); - } catch (Exception e) { - fail("getAttributes failed"); - } - - // Test issuer equal to our issuer - when(mockPipRequest.getIssuer()).thenReturn(ISSUER); - try { - assertNotNull(pegh.getAttributes(mockPipRequest, mockPipFinder)); - } catch (Exception e) { - // Normal to catch exception - } - } - - @Test - public void testGetCountFromDb() { - - // Use reflection to run getCountFromDB - Method method = null; - int count = -1; - try { - method = PIPEngineGetHistory.class.getDeclaredMethod("getCountFromDb", String.class, String.class, - String.class, String.class); - method.setAccessible(true); - count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException e) { - fail(e.getLocalizedMessage()); - } - // No entries yet - assertEquals(0, count); - - // Add an entry - String addEntry = "insert into operationshistory10 (outcome, CLNAME, actor, operation, target, endtime)" - + "values('success','testcl', 'actor', 'op', 'target', CURRENT_TIMESTAMP())"; - Query nq2 = em.createNativeQuery(addEntry); - em.getTransaction().begin(); - nq2.executeUpdate(); - em.getTransaction().commit(); - - try { - count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - fail(e.getLocalizedMessage()); - } - // Should count 1 entry now - assertEquals(1, count); - } - - @Test - public void testConfigure() throws PIPException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.configure("Dorothy", new Properties()); - - pegh.setDescription(null); - pegh.setIssuer(null); - pegh.configure("Dorothy", new Properties()); - } - - @Test - public void getAttributesTest() throws URISyntaxException, PIPException, FactoryException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.setIssuer("Dorothy"); - - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; - Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; - Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; - PIPRequest pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, - "Dorothy,tw:1000:SECOND"); - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); - } - - @Test - public void timeWindowTest() throws URISyntaxException, PIPException, FactoryException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.setIssuer("Dorothy"); - - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; - Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; - Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; - - PIPRequest pipRequest = - new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:SECOND"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = - new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MINUTE"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = - new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:HOUR"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = - new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:DAY"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = - new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:WEEK"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = - new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MONTH"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, - "Dorothy,tw:100:QUARTER"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = - new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:YEAR"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, - "Dorothy,tw:100:FORTNIGHT"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, - "Dorothy,tw:100:FORT NIGHT"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); - } - - private class DummyPipFinder implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - try { - List attributeList = new ArrayList<>(); - Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); - Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://www.w3.org/2001/XMLSchema#string")); - - Identifier attributeIdIn0 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue valueIn0 = new StdAttributeValue(dataTypeIdIn, "ActorDorothy"); - Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); - attributeList.add(attribute0); - - Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue valueIn1 = new StdAttributeValue(dataTypeIdIn, "OperationHomeFromOZ"); - Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); - attributeList.add(attribute1); - - Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue valueIn2 = new StdAttributeValue(dataTypeIdIn, "TargetWickedWitch"); - Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn2); - attributeList.add(attribute2); - - return new StdPIPResponse(attributeList); - } catch (Exception e) { - return null; - } - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } - - private class DummyPipFinderPipException implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - throw new PIPException(); - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } - - private class DummyPipFinderResponseStatusNok implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - Status status = new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Processing Error"); - return new StdPIPResponse(status); - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } - - private class DummyPipFinderResponseEmptyAttrs implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - List attributeList = new ArrayList<>(); - return new StdPIPResponse(attributeList); - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) - throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PipEngineGetHistoryTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PipEngineGetHistoryTest.java new file mode 100644 index 000000000..5780cecd6 --- /dev/null +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PipEngineGetHistoryTest.java @@ -0,0 +1,428 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * 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.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.Status; +import com.att.research.xacml.api.pip.PIPEngine; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.StdStatus; +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.std.pip.StdPIPRequest; +import com.att.research.xacml.std.pip.StdPIPResponse; +import com.att.research.xacml.std.pip.finders.EngineFinder; +import com.att.research.xacml.util.FactoryException; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Query; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.drools.system.PolicyEngine; + +public class PipEngineGetHistoryTest { + static PIPEngineGetHistory pegh; + private static final String ISSUER = "issuerIntw:mid:end"; + + private static EntityManagerFactory emf; + private static EntityManager em; + + /** + * Set up test class. + */ + @BeforeClass + public static void testPipEngineGetHistory() { + pegh = null; + try { + pegh = new PIPEngineGetHistory(); + } catch (Exception e) { + fail("PIPEngineGetHistory constructor failed"); + } + + // Set PU + System.setProperty(Util.PU_KEY, Util.JUNITPU); + + // Enter dummy props to avoid nullPointerException + PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_URL, "a"); + PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_USER, "b"); + PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_PASS, "c"); + + // Connect to in-mem db + emf = Persistence.createEntityManagerFactory(Util.JUNITPU); + em = emf.createEntityManager(); + + // Create necessary table + String sql = "CREATE TABLE `operationshistory10` (" + "`CLNAME` varchar(255)," + "`requestID` varchar(100)," + + "`actor` varchar(50) ," + "`operation` varchar(50)," + "`target` varchar(50)," + + "`starttime` timestamp," + "`outcome` varchar(50)," + "`message` varchar(255)," + + "`subrequestId` varchar(100)," + "`endtime` timestamp" + ")"; + Query nq = em.createNativeQuery(sql); + em.getTransaction().begin(); + nq.executeUpdate(); + em.getTransaction().commit(); + } + + @AfterClass + public static void tearDown() { + emf.close(); + } + + /** + * Setup method. + */ + @Before + public void setUp() { + // clear the table + String sql = "DELETE FROM `operationshistory10`"; + Query nq = em.createNativeQuery(sql); + em.getTransaction().begin(); + nq.executeUpdate(); + em.getTransaction().commit(); + } + + @Test + public void testAttributesRequired() { + assertTrue(pegh.attributesRequired().isEmpty()); + } + + @Test + public void testAttributesProvided() { + assertTrue(pegh.attributesProvided().isEmpty()); + } + + @Test + public void testGetAttributes() { + StdPIPRequest mockPipRequest = mock(StdPIPRequest.class); + EngineFinder mockPipFinder = mock(EngineFinder.class); + + // Test issuer null + when(mockPipRequest.getIssuer()).thenReturn(null); + try { + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); + } catch (Exception e) { + fail("getAttributes failed"); + } + + // Test issuer not equal to our issuer + pegh.setIssuer(ISSUER); + when(mockPipRequest.getIssuer()).thenReturn("something else"); + try { + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); + } catch (Exception e) { + fail("getAttributes failed"); + } + + // Test issuer equal to our issuer + when(mockPipRequest.getIssuer()).thenReturn(ISSUER); + try { + assertNotNull(pegh.getAttributes(mockPipRequest, mockPipFinder)); + } catch (Exception e) { + // Normal to catch exception + } + } + + @Test + public void testGetCountFromDb() { + + // Use reflection to run getCountFromDB + Method method = null; + int count = -1; + try { + method = PIPEngineGetHistory.class.getDeclaredMethod("getCountFromDb", String.class, String.class, + String.class, String.class); + method.setAccessible(true); + count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException e) { + fail(e.getLocalizedMessage()); + } + // No entries yet + assertEquals(0, count); + + // Add an entry + String addEntry = "insert into operationshistory10 (outcome, CLNAME, actor, operation, target, endtime)" + + "values('success','testcl', 'actor', 'op', 'target', CURRENT_TIMESTAMP())"; + Query nq2 = em.createNativeQuery(addEntry); + em.getTransaction().begin(); + nq2.executeUpdate(); + em.getTransaction().commit(); + + try { + count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + fail(e.getLocalizedMessage()); + } + // Should count 1 entry now + assertEquals(1, count); + } + + @Test + public void testConfigure() throws PIPException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.configure("Dorothy", new Properties()); + + pegh.setDescription(null); + pegh.setIssuer(null); + pegh.configure("Dorothy", new Properties()); + } + + @Test + public void getAttributesTest() throws URISyntaxException, PIPException, FactoryException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.setIssuer("Dorothy"); + + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; + Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; + Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; + PIPRequest pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:1000:SECOND"); + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); + } + + @Test + public void timeWindowTest() throws URISyntaxException, PIPException, FactoryException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.setIssuer("Dorothy"); + + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; + Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; + Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; + + PIPRequest pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:SECOND"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MINUTE"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:HOUR"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:DAY"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:WEEK"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MONTH"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:QUARTER"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:YEAR"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:FORTNIGHT"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:FORT NIGHT"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); + } + + private class DummyPipFinder implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + try { + List attributeList = new ArrayList<>(); + Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); + Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://www.w3.org/2001/XMLSchema#string")); + + Identifier attributeIdIn0 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue valueIn0 = new StdAttributeValue(dataTypeIdIn, "ActorDorothy"); + Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); + attributeList.add(attribute0); + + Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue valueIn1 = new StdAttributeValue(dataTypeIdIn, "OperationHomeFromOZ"); + Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); + attributeList.add(attribute1); + + Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue valueIn2 = new StdAttributeValue(dataTypeIdIn, "TargetWickedWitch"); + Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn2); + attributeList.add(attribute2); + + return new StdPIPResponse(attributeList); + } catch (Exception e) { + return null; + } + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } + + private class DummyPipFinderPipException implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + throw new PIPException(); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } + + private class DummyPipFinderResponseStatusNok implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + Status status = new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Processing Error"); + return new StdPIPResponse(status); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } + + private class DummyPipFinderResponseEmptyAttrs implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + List attributeList = new ArrayList<>(); + return new StdPIPResponse(attributeList); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } +} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java index 9cee0af27..273d8fb01 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java @@ -279,7 +279,7 @@ public class PolicyGuardTest { } @Test - public void testLockTargetTargetTypeStringUUIDLockCallbackInt() throws Exception { + public void testLockTargetTargetTypeStringUuidLockCallbackInt() throws Exception { TargetType type = TargetType.VM; LockResult result; diff --git a/controlloop/common/guard/src/test/resources/META-INF/persistence.xml b/controlloop/common/guard/src/test/resources/META-INF/persistence.xml index e4f597f63..73b9e1809 100644 --- a/controlloop/common/guard/src/test/resources/META-INF/persistence.xml +++ b/controlloop/common/guard/src/test/resources/META-INF/persistence.xml @@ -19,22 +19,29 @@ ============LICENSE_END========================================================= --> + xmlns="http://xmlns.jcp.org/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> - - - org.eclipse.persistence.jpa.PersistenceProvider - - - - - - - - - + + + org.eclipse.persistence.jpa.PersistenceProvider + + + + + + + + + diff --git a/controlloop/common/guard/src/test/resources/blacklist_template.xml b/controlloop/common/guard/src/test/resources/blacklist_template.xml index c27ced3ac..590b19d25 100644 --- a/controlloop/common/guard/src/test/resources/blacklist_template.xml +++ b/controlloop/common/guard/src/test/resources/blacklist_template.xml @@ -18,57 +18,100 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - + + Policy for frequency limiter. + + + + - ${clname} - - + ${clname} + + - - - ${actor} - - - - ${recipe} - - - - - - - DENY - only if target is in black list and guard is active. - - - - - - - - - - - - - - - ${blackListElement} - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - + + + ${actor} + + + + ${recipe} + + + + + + + DENY - only if target is in black list and guard is + active. + + + + + + + + + + + + + + + ${blackListElement} + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + diff --git a/controlloop/common/guard/src/test/resources/frequency_limiter_template.xml b/controlloop/common/guard/src/test/resources/frequency_limiter_template.xml index 9e44ae846..34aa1af69 100644 --- a/controlloop/common/guard/src/test/resources/frequency_limiter_template.xml +++ b/controlloop/common/guard/src/test/resources/frequency_limiter_template.xml @@ -18,60 +18,110 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - - + + Policy for frequency limiter. + + + + + - ${clname} - - + ${clname} + + - - - ${actor} - - - - ${recipe} - - - - - ${targets} - - - - - - - - DENY - only if number of operations performed in the past is larger than the limit and the Guard is active. - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - - ${limit} - - + + + ${actor} + + + + ${recipe} + + + + + ${targets} + + + + + + + + DENY - only if number of operations performed in + the past is larger than the limit and the Guard is active. + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + + ${limit} + + diff --git a/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java b/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java index 4ca91e73a..7a94dccf0 100644 --- a/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java +++ b/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * aai * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ package org.onap.policy.aai; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java b/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java index b4fbd7652..b82f2b377 100644 --- a/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java +++ b/controlloop/common/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java @@ -22,6 +22,7 @@ package org.onap.policy.aai; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/controlloop/common/model-impl/appc/pom.xml b/controlloop/common/model-impl/appc/pom.xml index 1c3cd1063..49a5266ea 100644 --- a/controlloop/common/model-impl/appc/pom.xml +++ b/controlloop/common/model-impl/appc/pom.xml @@ -42,44 +42,4 @@ - - - - maven-checkstyle-plugin - - - onap-java-style - - check - - process-sources - - - onap-checkstyle/onap-java-style.xml - - ${project.build.sourceDirectory} - true - true - true - - - true - true - warning - - - - - - org.onap.oparent - checkstyle - 0.1.1 - compile - - - - - diff --git a/controlloop/common/model-impl/appclcm/pom.xml b/controlloop/common/model-impl/appclcm/pom.xml index 45885296d..e40b3daeb 100644 --- a/controlloop/common/model-impl/appclcm/pom.xml +++ b/controlloop/common/model-impl/appclcm/pom.xml @@ -42,44 +42,4 @@ - - - - maven-checkstyle-plugin - - - onap-java-style - - check - - process-sources - - - onap-checkstyle/onap-java-style.xml - - ${project.build.sourceDirectory} - true - true - true - - - true - true - warning - - - - - - org.onap.oparent - checkstyle - 0.1.1 - compile - - - - - diff --git a/controlloop/common/model-impl/events/pom.xml b/controlloop/common/model-impl/events/pom.xml index 8fec961d8..b49aa9267 100644 --- a/controlloop/common/model-impl/events/pom.xml +++ b/controlloop/common/model-impl/events/pom.xml @@ -41,45 +41,4 @@ test - - - - - maven-checkstyle-plugin - - - onap-java-style - - check - - process-sources - - - onap-checkstyle/onap-java-style.xml - - ${project.build.sourceDirectory} - true - true - true - - - true - true - warning - - - - - - org.onap.oparent - checkstyle - 0.1.1 - compile - - - - - diff --git a/controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java b/controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java index 52ce13ef9..39e0d8a7f 100644 --- a/controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java +++ b/controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java @@ -51,6 +51,17 @@ public class RESTManager { } } + /** + * Perform REST Post. + * + * @param url the url + * @param username the user name + * @param password the password + * @param headers any headers + * @param contentType what the content type is + * @param body body to send + * @return the response status code and the body + */ public Pair post(String url, String username, String password, Map headers, String contentType, String body) { @@ -77,7 +88,7 @@ public class RESTManager { } } post.addHeader("Content-Type", contentType); - if(authHeader != null) { + if (authHeader != null) { post.setHeader(HttpHeaders.AUTHORIZATION, authHeader); } @@ -107,6 +118,15 @@ public class RESTManager { } } + /** + * Do a REST get. + * + * @param url URL + * @param username user name + * @param password password + * @param headers any headers to add + * @return a Pair for the response status and the body + */ public Pair get(String url, String username, String password, Map headers) { @@ -124,7 +144,7 @@ public class RESTManager { get.addHeader(entry.getKey(), headers.get(entry.getKey())); } } - if(authHeader != null) { + if (authHeader != null) { get.setHeader(HttpHeaders.AUTHORIZATION, authHeader); } diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Resource.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Resource.java index 25d0903d7..121b54e5a 100644 --- a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Resource.java +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Resource.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * sdc * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ public class Resource implements Serializable { private static final long serialVersionUID = -913729158733348027L; - private UUID resourceUUID; - private UUID resourceInvariantUUID; + private UUID resourceUuid; + private UUID resourceInvariantUuid; private String resourceName; private String resourceVersion; private ResourceType resourceType; @@ -37,16 +37,21 @@ public class Resource implements Serializable { //Empty Constructor } + /** + * Constructor. + * + * @param resource copy object + */ public Resource(Resource resource) { - this.resourceUUID = resource.resourceUUID; - this.resourceInvariantUUID = resource.resourceInvariantUUID; + this.resourceUuid = resource.resourceUuid; + this.resourceInvariantUuid = resource.resourceInvariantUuid; this.resourceName = resource.resourceName; this.resourceVersion = resource.resourceVersion; this.resourceType = resource.resourceType; } public Resource(UUID uuid) { - this.resourceUUID = uuid; + this.resourceUuid = uuid; } public Resource(String name, ResourceType type) { @@ -54,28 +59,37 @@ public class Resource implements Serializable { this.resourceType = type; } - public Resource(UUID uuid, UUID invariantUUID, String name, String version, ResourceType type) { - this.resourceUUID = uuid; - this.resourceInvariantUUID = invariantUUID; + /** + * Constructor. + * + * @param uuid uuid + * @param invariantUuid invariant uuid + * @param name name + * @param version version + * @param type type + */ + public Resource(UUID uuid, UUID invariantUuid, String name, String version, ResourceType type) { + this.resourceUuid = uuid; + this.resourceInvariantUuid = invariantUuid; this.resourceName = name; this.resourceVersion = version; this.resourceType = type; } - public UUID getResourceUUID() { - return resourceUUID; + public UUID getResourceUuid() { + return resourceUuid; } - public void setResourceUUID(UUID resourceUUID) { - this.resourceUUID = resourceUUID; + public void setResourceUuid(UUID resourceUuid) { + this.resourceUuid = resourceUuid; } - public UUID getResourceInvariantUUID() { - return resourceInvariantUUID; + public UUID getResourceInvariantUuid() { + return resourceInvariantUuid; } - public void setResourceInvariantUUID(UUID resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; + public void setResourceInvariantUuid(UUID resourceInvariantUuid) { + this.resourceInvariantUuid = resourceInvariantUuid; } public String getResourceName() { @@ -104,55 +118,70 @@ public class Resource implements Serializable { @Override public String toString() { - return "Resource [resourceUUID=" + resourceUUID + ", resourceInvariantUUID=" + resourceInvariantUUID + return "Resource [resourceUUID=" + resourceUuid + ", resourceInvariantUUID=" + resourceInvariantUuid + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceType=" + resourceType + "]"; } + @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); + result = prime * result + ((resourceInvariantUuid == null) ? 0 : resourceInvariantUuid.hashCode()); result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); - result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); + result = prime * result + ((resourceUuid == null) ? 0 : resourceUuid.hashCode()); result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.hashCode()); return result; } + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Resource other = (Resource) obj; - if (resourceInvariantUUID == null) { - if (other.resourceInvariantUUID != null) + if (resourceInvariantUuid == null) { + if (other.resourceInvariantUuid != null) { return false; - } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) + } + } else if (!resourceInvariantUuid.equals(other.resourceInvariantUuid)) { return false; + } if (resourceName == null) { - if (other.resourceName != null) + if (other.resourceName != null) { return false; - } else if (!resourceName.equals(other.resourceName)) + } + } else if (!resourceName.equals(other.resourceName)) { return false; + } if (resourceType == null) { - if (other.resourceType != null) + if (other.resourceType != null) { return false; - } else if (!resourceType.equals(other.resourceType)) + } + } else if (!resourceType.equals(other.resourceType)) { return false; - if (resourceUUID == null) { - if (other.resourceUUID != null) + } + if (resourceUuid == null) { + if (other.resourceUuid != null) { return false; - } else if (!resourceUUID.equals(other.resourceUUID)) + } + } else if (!resourceUuid.equals(other.resourceUuid)) { return false; + } if (resourceVersion == null) { - if (other.resourceVersion != null) + if (other.resourceVersion != null) { return false; - } else if (!resourceVersion.equals(other.resourceVersion)) + } + } else if (!resourceVersion.equals(other.resourceVersion)) { return false; + } return true; } diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceInstance.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceInstance.java index 7fca79fc3..eaee5a27b 100644 --- a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceInstance.java +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceInstance.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * sdc * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,25 +28,30 @@ public class ResourceInstance implements Serializable { private String resourceInstanceName; private String resourceName; - private UUID resourceInvariantUUID; + private UUID resourceInvariantUuid; private String resourceVersion; private ResourceType resourceType; - private UUID resourceUUID; + private UUID resourceUuid; public ResourceInstance() { //Empty Constructor } + /** + * Constructor. + * + * @param instance copy object + */ public ResourceInstance(ResourceInstance instance) { if (instance == null) { return; } this.resourceInstanceName = instance.resourceInstanceName; this.resourceName = instance.resourceName; - this.resourceInvariantUUID = instance.resourceInvariantUUID; + this.resourceInvariantUuid = instance.resourceInvariantUuid; this.resourceVersion = instance.resourceVersion; this.resourceType = instance.resourceType; - this.resourceUUID = instance.resourceUUID; + this.resourceUuid = instance.resourceUuid; } public String getResourceInstanceName() { @@ -66,11 +71,11 @@ public class ResourceInstance implements Serializable { } public UUID getResourceInvariantUUID() { - return resourceInvariantUUID; + return resourceInvariantUuid; } - public void setResourceInvariantUUID(UUID resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; + public void setResourceInvariantUUID(UUID resourceInvariantUuid) { + this.resourceInvariantUuid = resourceInvariantUuid; } public String getResourceVersion() { @@ -89,68 +94,84 @@ public class ResourceInstance implements Serializable { this.resourceType = resourceType; } - public UUID getResourceUUID() { - return resourceUUID; + public UUID getResourceUuid() { + return resourceUuid; } - public void setResourceUUID(UUID resourceUUID) { - this.resourceUUID = resourceUUID; + public void setResourceUuid(UUID resourceUuid) { + this.resourceUuid = resourceUuid; } @Override public String toString() { return "ResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName - + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion=" + resourceVersion - + ", resourceType=" + resourceType + ", resourceUUID=" + resourceUUID + "]"; + + ", resourceInvariantUUID=" + resourceInvariantUuid + ", resourceVersion=" + resourceVersion + + ", resourceType=" + resourceType + ", resourceUUID=" + resourceUuid + "]"; } + @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((resourceInstanceName == null) ? 0 : resourceInstanceName.hashCode()); - result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); + result = prime * result + ((resourceInvariantUuid == null) ? 0 : resourceInvariantUuid.hashCode()); result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); - result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); + result = prime * result + ((resourceUuid == null) ? 0 : resourceUuid.hashCode()); result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.hashCode()); return result; } + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } ResourceInstance other = (ResourceInstance) obj; if (resourceInstanceName == null) { - if (other.resourceInstanceName != null) + if (other.resourceInstanceName != null) { return false; - } else if (!resourceInstanceName.equals(other.resourceInstanceName)) + } + } else if (!resourceInstanceName.equals(other.resourceInstanceName)) { return false; - if (resourceInvariantUUID == null) { - if (other.resourceInvariantUUID != null) + } + if (resourceInvariantUuid == null) { + if (other.resourceInvariantUuid != null) { return false; - } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) + } + } else if (!resourceInvariantUuid.equals(other.resourceInvariantUuid)) { return false; + } if (resourceName == null) { - if (other.resourceName != null) + if (other.resourceName != null) { return false; - } else if (!resourceName.equals(other.resourceName)) + } + } else if (!resourceName.equals(other.resourceName)) { return false; - if (resourceType != other.resourceType) + } + if (resourceType != other.resourceType) { return false; - if (resourceUUID == null) { - if (other.resourceUUID != null) + } + if (resourceUuid == null) { + if (other.resourceUuid != null) { return false; - } else if (!resourceUUID.equals(other.resourceUUID)) + } + } else if (!resourceUuid.equals(other.resourceUuid)) { return false; + } if (resourceVersion == null) { - if (other.resourceVersion != null) + if (other.resourceVersion != null) { return false; - } else if (!resourceVersion.equals(other.resourceVersion)) + } + } else if (!resourceVersion.equals(other.resourceVersion)) { return false; + } return true; } diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceType.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceType.java index c4dbfffa4..6202d64e0 100644 --- a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceType.java +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceType.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * sdc * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,21 +21,21 @@ package org.onap.policy.sdc; public enum ResourceType { - VF("VF"), - VFC("VFC"), - VL("VL"), - CP("CP") - ; - - private String type; - - private ResourceType(String type) { - this.type = type; - } + VF("VF"), + VFC("VFC"), + VL("VL"), + CP("CP") + ; + + private String type; + + private ResourceType(String type) { + this.type = type; + } + + @Override + public String toString() { + return this.type; + } - @Override - public String toString() { - return this.type; - } - } diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Service.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Service.java index 7bfc62e67..b3ebcc238 100644 --- a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Service.java +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Service.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * sdc * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,6 +44,14 @@ public class Service implements Serializable { this.serviceName = name; } + /** + * Constructor. + * + * @param uuid service id + * @param invariantUUID service invariant id + * @param name name + * @param version version + */ public Service(UUID uuid, UUID invariantUUID, String name, String version) { this.serviceUUID = uuid; this.serviceInvariantUUID = invariantUUID; @@ -51,6 +59,11 @@ public class Service implements Serializable { this.serviceVersion = version; } + /** + * Constructor. + * + * @param service copy object + */ public Service(Service service) { this.serviceUUID = service.serviceUUID; this.serviceInvariantUUID = service.serviceInvariantUUID; @@ -95,6 +108,7 @@ public class Service implements Serializable { return "Service [serviceUUID=" + serviceUUID + ", serviceInvariantUUID=" + serviceInvariantUUID + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + "]"; } + @Override public int hashCode() { final int prime = 31; @@ -105,35 +119,47 @@ public class Service implements Serializable { result = prime * result + ((serviceVersion == null) ? 0 : serviceVersion.hashCode()); return result; } + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Service other = (Service) obj; if (serviceInvariantUUID == null) { - if (other.serviceInvariantUUID != null) + if (other.serviceInvariantUUID != null) { return false; - } else if (!serviceInvariantUUID.equals(other.serviceInvariantUUID)) + } + } else if (!serviceInvariantUUID.equals(other.serviceInvariantUUID)) { return false; + } if (serviceName == null) { - if (other.serviceName != null) + if (other.serviceName != null) { return false; - } else if (!serviceName.equals(other.serviceName)) + } + } else if (!serviceName.equals(other.serviceName)) { return false; + } if (serviceUUID == null) { - if (other.serviceUUID != null) + if (other.serviceUUID != null) { return false; - } else if (!serviceUUID.equals(other.serviceUUID)) + } + } else if (!serviceUUID.equals(other.serviceUUID)) { return false; + } if (serviceVersion == null) { - if (other.serviceVersion != null) + if (other.serviceVersion != null) { return false; - } else if (!serviceVersion.equals(other.serviceVersion)) + } + } else if (!serviceVersion.equals(other.serviceVersion)) { return false; + } return true; } diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ServiceInstance.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ServiceInstance.java index c35d7dfde..a477267a3 100644 --- a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ServiceInstance.java +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ServiceInstance.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * sdc * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,6 +38,11 @@ public class ServiceInstance implements Serializable { //Empty Constructor } + /** + * Constructor. + * + * @param instance copy object + */ public ServiceInstance(ServiceInstance instance) { if (instance == null) { return; @@ -114,6 +119,7 @@ public class ServiceInstance implements Serializable { + ", widgetModelVersion=" + widgetModelVersion + ", serviceName=" + serviceName + ", serviceInstanceName=" + serviceInstanceName + "]"; } + @Override public int hashCode() { final int prime = 31; @@ -127,50 +133,68 @@ public class ServiceInstance implements Serializable { result = prime * result + ((widgetModelVersion == null) ? 0 : widgetModelVersion.hashCode()); return result; } + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } ServiceInstance other = (ServiceInstance) obj; if (personaModelUUID == null) { - if (other.personaModelUUID != null) + if (other.personaModelUUID != null) { return false; - } else if (!personaModelUUID.equals(other.personaModelUUID)) + } + } else if (!personaModelUUID.equals(other.personaModelUUID)) { return false; + } if (serviceInstanceName == null) { - if (other.serviceInstanceName != null) + if (other.serviceInstanceName != null) { return false; - } else if (!serviceInstanceName.equals(other.serviceInstanceName)) + } + } else if (!serviceInstanceName.equals(other.serviceInstanceName)) { return false; + } if (serviceInstanceUUID == null) { - if (other.serviceInstanceUUID != null) + if (other.serviceInstanceUUID != null) { return false; - } else if (!serviceInstanceUUID.equals(other.serviceInstanceUUID)) + } + } else if (!serviceInstanceUUID.equals(other.serviceInstanceUUID)) { return false; + } if (serviceName == null) { - if (other.serviceName != null) + if (other.serviceName != null) { return false; - } else if (!serviceName.equals(other.serviceName)) + } + } else if (!serviceName.equals(other.serviceName)) { return false; + } if (serviceUUID == null) { - if (other.serviceUUID != null) + if (other.serviceUUID != null) { return false; - } else if (!serviceUUID.equals(other.serviceUUID)) + } + } else if (!serviceUUID.equals(other.serviceUUID)) { return false; + } if (widgetModelUUID == null) { - if (other.widgetModelUUID != null) + if (other.widgetModelUUID != null) { return false; - } else if (!widgetModelUUID.equals(other.widgetModelUUID)) + } + } else if (!widgetModelUUID.equals(other.widgetModelUUID)) { return false; + } if (widgetModelVersion == null) { - if (other.widgetModelVersion != null) + if (other.widgetModelVersion != null) { return false; - } else if (!widgetModelVersion.equals(other.widgetModelVersion)) + } + } else if (!widgetModelVersion.equals(other.widgetModelVersion)) { return false; + } return true; } diff --git a/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResource.java b/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResource.java index 7e64787f8..7b3a3e1f6 100644 --- a/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResource.java +++ b/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResource.java @@ -32,26 +32,26 @@ public class TestResource { @Test public void testConstructors() { Resource res = new Resource(); - assertEquals(null, res.getResourceUUID()); - assertEquals(null, res.getResourceInvariantUUID()); + assertEquals(null, res.getResourceUuid()); + assertEquals(null, res.getResourceInvariantUuid()); assertEquals(null, res.getResourceName()); assertEquals(null, res.getResourceType()); assertEquals(null, res.getResourceVersion()); UUID uuid = UUID.randomUUID(); res = new Resource(uuid); - assertEquals(uuid, res.getResourceUUID()); - assertEquals(null, res.getResourceInvariantUUID()); + assertEquals(uuid, res.getResourceUuid()); + assertEquals(null, res.getResourceInvariantUuid()); assertEquals(null, res.getResourceName()); assertEquals(null, res.getResourceType()); assertEquals(null, res.getResourceVersion()); String name = "constTest"; res = new Resource(name, ResourceType.CP); - assertEquals(null, res.getResourceUUID()); + assertEquals(null, res.getResourceUuid()); assertEquals(name, res.getResourceName()); assertEquals(ResourceType.CP, res.getResourceType()); - assertEquals(null, res.getResourceInvariantUUID()); + assertEquals(null, res.getResourceInvariantUuid()); assertEquals(null, res.getResourceVersion()); uuid = UUID.randomUUID(); @@ -59,15 +59,15 @@ public class TestResource { name = "constTestUUID"; String version = "0.0.1"; res = new Resource(uuid, uuidInvariant, name, version, ResourceType.VF); - assertEquals(uuid, res.getResourceUUID()); - assertEquals(uuidInvariant, res.getResourceInvariantUUID()); + assertEquals(uuid, res.getResourceUuid()); + assertEquals(uuidInvariant, res.getResourceInvariantUuid()); assertEquals(name, res.getResourceName()); assertEquals(ResourceType.VF, res.getResourceType()); assertEquals(version, res.getResourceVersion()); Resource r2 = new Resource(res); - assertEquals(uuid, r2.getResourceUUID()); - assertEquals(uuidInvariant, r2.getResourceInvariantUUID()); + assertEquals(uuid, r2.getResourceUuid()); + assertEquals(uuidInvariant, r2.getResourceInvariantUuid()); assertEquals(name, r2.getResourceName()); assertEquals(ResourceType.VF, r2.getResourceType()); assertEquals(version, r2.getResourceVersion()); @@ -77,16 +77,16 @@ public class TestResource { public void testUuid() { Resource res = new Resource(); UUID uuid = UUID.randomUUID(); - res.setResourceUUID(uuid); - assertEquals(uuid, res.getResourceUUID()); + res.setResourceUuid(uuid); + assertEquals(uuid, res.getResourceUuid()); } @Test public void testInvariantUuid() { Resource res = new Resource(); UUID uuid = UUID.randomUUID(); - res.setResourceInvariantUUID(uuid); - assertEquals(uuid, res.getResourceInvariantUUID()); + res.setResourceInvariantUuid(uuid); + assertEquals(uuid, res.getResourceInvariantUuid()); } @Test diff --git a/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResourceInstance.java b/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResourceInstance.java index 77847f167..2a1dc42b3 100644 --- a/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResourceInstance.java +++ b/controlloop/common/model-impl/sdc/src/test/java/org/onap/policy/sdc/TestResourceInstance.java @@ -33,7 +33,7 @@ public class TestResourceInstance { public void testConstructors() { ResourceInstance ri = new ResourceInstance(); assertEquals(null, ri.getResourceInstanceName()); - assertEquals(null, ri.getResourceUUID()); + assertEquals(null, ri.getResourceUuid()); assertEquals(null, ri.getResourceInvariantUUID()); assertEquals(null, ri.getResourceName()); assertEquals(null, ri.getResourceType()); @@ -41,7 +41,7 @@ public class TestResourceInstance { ResourceInstance ri2 = new ResourceInstance((ResourceInstance) null); assertEquals(null, ri2.getResourceInstanceName()); - assertEquals(null, ri2.getResourceUUID()); + assertEquals(null, ri2.getResourceUuid()); assertEquals(null, ri2.getResourceInvariantUUID()); assertEquals(null, ri2.getResourceName()); assertEquals(null, ri2.getResourceType()); @@ -49,7 +49,7 @@ public class TestResourceInstance { ri2 = new ResourceInstance(ri); assertEquals(ri2.getResourceInstanceName(), ri.getResourceInstanceName()); - assertEquals(ri2.getResourceUUID(), ri.getResourceUUID()); + assertEquals(ri2.getResourceUuid(), ri.getResourceUuid()); assertEquals(ri2.getResourceInvariantUUID(), ri.getResourceInvariantUUID()); assertEquals(ri2.getResourceName(), ri.getResourceName()); assertEquals(ri2.getResourceType(), ri.getResourceType()); @@ -68,8 +68,8 @@ public class TestResourceInstance { public void testUuid() { ResourceInstance ri = new ResourceInstance(); UUID uuid = UUID.randomUUID(); - ri.setResourceUUID(uuid); - assertEquals(uuid, ri.getResourceUUID()); + ri.setResourceUuid(uuid); + assertEquals(uuid, ri.getResourceUuid()); } @Test diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOAsyncRequestStatus.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOAsyncRequestStatus.java index ea1257d4d..5bb03de06 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOAsyncRequestStatus.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOAsyncRequestStatus.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ package org.onap.policy.so; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.time.LocalDateTime; -import com.google.gson.annotations.SerializedName; - public class SOAsyncRequestStatus implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOCloudConfiguration.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOCloudConfiguration.java index 7ad497a9f..b52fe2b7c 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOCloudConfiguration.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOCloudConfiguration.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SOCloudConfiguration implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOInstanceReferences.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOInstanceReferences.java index 307e0514f..645e7f711 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOInstanceReferences.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOInstanceReferences.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SOInstanceReferences implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOManager.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOManager.java index 92d52f4c2..a3f2be30b 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOManager.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOManager.java @@ -63,7 +63,7 @@ public final class SOManager { private long restGetTimeout = GET_REQUEST_WAIT_INTERVAL; /** - * Default constructor + * Default constructor. */ public SOManager() { restManager = new RESTManager(); @@ -100,12 +100,11 @@ public final class SOManager { /** * This method makes an asynchronous Rest call to MSO and inserts the response into * Drools working memory. - * + * + * @param requestID request id * @param wm the Drools working memory - * @param url the URL to use on the POST request - * @param urlBase the SO base URL - * @param username user name for SO requests - * @param password password for SO requests + * @param serviceInstanceId service instance id + * @param vnfInstanceId vnf instance id * @param request the SO request * @return a concurrent Future for the thread that handles the request */ diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOModelInfo.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOModelInfo.java index eb257a7e9..15cbd23d0 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOModelInfo.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOModelInfo.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SOModelInfo implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOPolicyExceptionHolder.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOPolicyExceptionHolder.java index 975a21cbc..4c4fed1f2 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOPolicyExceptionHolder.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOPolicyExceptionHolder.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SOPolicyExceptionHolder implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstance.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstance.java index e7f3efc57..90fe339ee 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstance.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstance.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SORelatedInstance implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstanceListElement.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstanceListElement.java index 1148ef1e0..4d3d27346 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstanceListElement.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORelatedInstanceListElement.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SORelatedInstanceListElement implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequest.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequest.java index 73ebba260..4a2f405e7 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequest.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,12 @@ package org.onap.policy.so; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.time.LocalDateTime; import java.util.UUID; -import com.google.gson.annotations.SerializedName; - public class SORequest implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestDetails.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestDetails.java index 13d25cf81..465895117 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestDetails.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestDetails.java @@ -20,11 +20,12 @@ package org.onap.policy.so; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.util.LinkedList; import java.util.List; import java.util.Map; -import com.google.gson.annotations.SerializedName; public class SORequestDetails implements Serializable { @@ -55,6 +56,11 @@ public class SORequestDetails implements Serializable { } + /** + * Constructor. + * + * @param soRequestDetails copy object + */ public SORequestDetails(SORequestDetails soRequestDetails) { this.modelInfo = soRequestDetails.modelInfo; this.cloudConfiguration = soRequestDetails.cloudConfiguration; @@ -66,48 +72,65 @@ public class SORequestDetails implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } SORequestDetails other = (SORequestDetails) obj; if (cloudConfiguration == null) { - if (other.cloudConfiguration != null) + if (other.cloudConfiguration != null) { return false; - } else if (!cloudConfiguration.equals(other.cloudConfiguration)) + } + } else if (!cloudConfiguration.equals(other.cloudConfiguration)) { return false; + } if (configurationParameters == null) { - if (other.configurationParameters != null) + if (other.configurationParameters != null) { return false; - } else if (!configurationParameters.equals(other.configurationParameters)) + } + } else if (!configurationParameters.equals(other.configurationParameters)) { return false; + } if (modelInfo == null) { - if (other.modelInfo != null) + if (other.modelInfo != null) { return false; - } else if (!modelInfo.equals(other.modelInfo)) + } + } else if (!modelInfo.equals(other.modelInfo)) { return false; + } if (relatedInstanceList == null) { - if (other.relatedInstanceList != null) + if (other.relatedInstanceList != null) { return false; - } else if (!relatedInstanceList.equals(other.relatedInstanceList)) + } + } else if (!relatedInstanceList.equals(other.relatedInstanceList)) { return false; + } if (requestInfo == null) { - if (other.requestInfo != null) + if (other.requestInfo != null) { return false; - } else if (!requestInfo.equals(other.requestInfo)) + } + } else if (!requestInfo.equals(other.requestInfo)) { return false; + } if (requestParameters == null) { - if (other.requestParameters != null) + if (other.requestParameters != null) { return false; - } else if (!requestParameters.equals(other.requestParameters)) + } + } else if (!requestParameters.equals(other.requestParameters)) { return false; + } if (subscriberInfo == null) { - if (other.subscriberInfo != null) + if (other.subscriberInfo != null) { return false; - } else if (!subscriberInfo.equals(other.subscriberInfo)) + } + } else if (!subscriberInfo.equals(other.subscriberInfo)) { return false; + } return true; } diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestError.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestError.java index 763210831..7594ef95c 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestError.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestError.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SORequestError implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestInfo.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestInfo.java index fd92e3284..c30e50c17 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestInfo.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestInfo.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SORequestInfo implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestParameters.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestParameters.java index 7ea20defd..69faded76 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestParameters.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestParameters.java @@ -20,11 +20,12 @@ package org.onap.policy.so; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.util.LinkedList; import java.util.List; import java.util.Map; -import com.google.gson.annotations.SerializedName; public class SORequestParameters implements Serializable { diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestReferences.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestReferences.java index ed14f6b58..71b1cccfe 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestReferences.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestReferences.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SORequestReferences implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestStatus.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestStatus.java index 2e77c157b..79406574d 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestStatus.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SORequestStatus.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +20,12 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SORequestStatus implements Serializable { - /** - * - */ private static final long serialVersionUID = -3283942659786236032L; @SerializedName("percentProgress") diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponse.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponse.java index 20e0c4155..e9350838a 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponse.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponse.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SOResponse implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponseWrapper.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponseWrapper.java index e18cbb62d..dcf640d83 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponseWrapper.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOResponseWrapper.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SOResponseWrapper implements Serializable { private static final long serialVersionUID = 7673023687132889069L; @@ -86,12 +86,12 @@ public class SOResponseWrapper implements Serializable { return result; } - public void setRequestID(String requestID) { - this.requestID = requestID; + public void setRequestID(String requestId) { + this.requestID = requestId; } - public void setSoResponse(SOResponse sOResponse) { - soResponse = sOResponse; + public void setSoResponse(SOResponse response) { + soResponse = response; } @Override diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOServiceExceptionHolder.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOServiceExceptionHolder.java index 703e13be5..65ba446e3 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOServiceExceptionHolder.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOServiceExceptionHolder.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,12 @@ package org.onap.policy.so; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.util.LinkedList; import java.util.List; -import com.google.gson.annotations.SerializedName; - public class SOServiceExceptionHolder implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOSubscriberInfo.java b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOSubscriberInfo.java index 618e9ec1e..f7a4982a1 100644 --- a/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOSubscriberInfo.java +++ b/controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOSubscriberInfo.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ package org.onap.policy.so; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class SOSubscriberInfo implements Serializable { private static final long serialVersionUID = -3283942659786236032L; diff --git a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/DummyWorkingMemory.java b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/DummyWorkingMemory.java index af7ddc426..b8fd036c5 100644 --- a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/DummyWorkingMemory.java +++ b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/DummyWorkingMemory.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.so; import java.util.Collection; @@ -50,16 +51,15 @@ public class DummyWorkingMemory implements WorkingMemory { } @Override - public void removeEventListener(RuleRuntimeEventListener listener) { + public void addEventListener(AgendaEventListener listener) { } @Override - public Collection getRuleRuntimeEventListeners() { - return null; + public void addEventListener(KieBaseEventListener listener) { } @Override - public void addEventListener(AgendaEventListener listener) { + public void removeEventListener(RuleRuntimeEventListener listener) { } @Override @@ -67,16 +67,17 @@ public class DummyWorkingMemory implements WorkingMemory { } @Override - public Collection getAgendaEventListeners() { - return null; + public void removeEventListener(KieBaseEventListener listener) { } @Override - public void addEventListener(KieBaseEventListener listener) { + public Collection getRuleRuntimeEventListeners() { + return null; } @Override - public void removeEventListener(KieBaseEventListener listener) { + public Collection getAgendaEventListeners() { + return null; } @Override @@ -90,16 +91,16 @@ public class DummyWorkingMemory implements WorkingMemory { } @Override - public void dispose() { + public FactHandle insert(Object object) { + return null; } @Override - public String getEntryPointId() { - return null; + public void dispose() { } @Override - public FactHandle insert(Object object) { + public String getEntryPointId() { return null; } diff --git a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSOManager.java b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSOManager.java deleted file mode 100644 index 4a7fdda8d..000000000 --- a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSOManager.java +++ /dev/null @@ -1,275 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * TestSOManager - * ================================================================================ - * 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.so; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import java.io.IOException; -import java.net.URI; -import java.util.UUID; -import java.util.concurrent.Future; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.drools.core.WorkingMemory; -import org.glassfish.grizzly.http.server.HttpServer; -import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; -import org.glassfish.jersey.server.ResourceConfig; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.drools.system.PolicyEngine; - -public class TestSOManager { - private static final String BASE_URI = "http://localhost:46553/TestSOManager"; - private static final String BASE_SO_URI = BASE_URI + "/SO"; - private static HttpServer server; - - @BeforeClass - public static void setUp() { - final ResourceConfig rc = new ResourceConfig(TestSoDummyServer.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); - } - - @AfterClass - public static void tearDown() throws Exception { - server.shutdown(); - } - - @Test - public void testGrizzlyServer() throws ClientProtocolException, IOException { - CloseableHttpClient httpclient = HttpClients.createDefault(); - HttpGet httpGet = new HttpGet("http://localhost:46553/TestSOManager/SO/Stats"); - CloseableHttpResponse response = httpclient.execute(httpGet); - - String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8"); - assertTrue(returnBody.matches("^\\{\"GET\": [0-9]*,\"STAT\": [0-9]*,\"POST\": [0-9]*,\"PUT\": [0-9]*\\}$")); - } - - @Test - public void testServiceInstantiation() throws IOException { - SOManager manager = new SOManager(); - assertNotNull(manager); - manager.setRestGetTimeout(100); - - SOResponse response = - manager.createModuleInstance("http:/localhost:99999999", BASE_SO_URI, "sean", "citizen", null); - assertNull(response); - - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", null); - assertNull(response); - - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", new SORequest()); - assertNull(response); - - SORequest request = new SORequest(); - request.setRequestId(UUID.randomUUID()); - request.setRequestScope("Test"); - request.setRequestType("ReturnBadJson"); - request.setStartTime("2018-03-23 16:31"); - request.setRequestStatus(new SORequestStatus()); - request.getRequestStatus().setRequestState("ONGOING"); - - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", request); - assertNull(response); - - request.setRequestType("ReturnCompleted"); - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", request); - assertNotNull(response); - assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType("ReturnFailed"); - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", request); - assertNotNull(response); - assertEquals("FAILED", response.getRequest().getRequestStatus().getRequestState()); - - // Use scope to set the number of iterations we'll wait for - - request.setRequestType("ReturnOnging200"); - request.setRequestScope(new Integer(10).toString()); - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", request); - assertNotNull(response); - assertNotNull(response.getRequest()); - assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType("ReturnOnging202"); - request.setRequestScope(new Integer(20).toString()); - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", request); - assertNotNull(response); - assertNotNull(response.getRequest()); - assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); - - // Test timeout after 20 attempts for a response - request.setRequestType("ReturnOnging202"); - request.setRequestScope(new Integer(21).toString()); - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", request); - assertNull(response); - - // Test bad response after 3 attempts for a response - request.setRequestType("ReturnBadAfterWait"); - request.setRequestScope(new Integer(3).toString()); - response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", - "citizen", request); - assertNull(response); - } - - @Test - public void testVfModuleCreation() throws IOException { - SOManager manager = new SOManager(); - assertNotNull(manager); - manager.setRestGetTimeout(100); - - PolicyEngine.manager.setEnvironmentProperty("so.username", "sean"); - PolicyEngine.manager.setEnvironmentProperty("so.password", "citizen"); - - WorkingMemory wm = new DummyWorkingMemory(); - - PolicyEngine.manager.setEnvironmentProperty("so.url", "http:/localhost:99999999"); - Future asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, - UUID.randomUUID().toString(), UUID.randomUUID().toString(), null); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - PolicyEngine.manager.setEnvironmentProperty("so.url", BASE_SO_URI); - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), null); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), new SORequest()); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - SORequest request = new SORequest(); - request.setRequestId(UUID.randomUUID()); - request.setRequestScope("Test"); - request.setRequestType("ReturnBadJson"); - request.setStartTime("2018-03-23 16:31"); - request.setRequestStatus(new SORequestStatus()); - request.getRequestStatus().setRequestState("ONGOING"); - - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - request.setRequestType("ReturnCompleted"); - - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - request.setRequestType("ReturnFailed"); - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals("FAILED", response.getRequest().getRequestStatus().getRequestState()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - // Use scope to set the number of iterations we'll wait for - - request.setRequestType("ReturnOnging200"); - request.setRequestScope(new Integer(10).toString()); - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - try { - SOResponse response = asyncRestCallFuture.get(); - assertNotNull(response.getRequest()); - assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - request.setRequestType("ReturnOnging202"); - request.setRequestScope(new Integer(20).toString()); - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - try { - SOResponse response = asyncRestCallFuture.get(); - assertNotNull(response.getRequest()); - assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - // Test timeout after 20 attempts for a response - request.setRequestType("ReturnOnging202"); - request.setRequestScope(new Integer(21).toString()); - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - // Test bad response after 3 attempts for a response - request.setRequestType("ReturnBadAfterWait"); - request.setRequestScope(new Integer(3).toString()); - asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - try { - SOResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - } -} diff --git a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoDummyServer.java b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoDummyServer.java index 348523140..5eb0a01ee 100644 --- a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoDummyServer.java +++ b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoDummyServer.java @@ -22,6 +22,7 @@ package org.onap.policy.so; +import com.google.gson.Gson; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.ws.rs.GET; @@ -29,7 +30,6 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; -import com.google.gson.Gson; @Path("/SO") public class TestSoDummyServer { @@ -41,6 +41,11 @@ public class TestSoDummyServer { private static Map ongoingRequestMap = new ConcurrentHashMap<>(); + /** + * Stats method. + * + * @return response + */ @GET @Path("/Stats") public Response serviceGetStats() { @@ -49,6 +54,12 @@ public class TestSoDummyServer { + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); } + /** + * Get stat type. + * + * @param statType the stat type + * @return http response + */ @GET @Path("/OneStat/{statType}") public Response serviceGetStat(@PathParam("statType") final String statType) { @@ -56,6 +67,12 @@ public class TestSoDummyServer { return Response.status(200).entity("{\"TYPE\": " + statType + "}").build(); } + /** + * Post to service instantiation. + * + * @param jsonString string to send + * @return http response + */ @POST @Path("/serviceInstantiation/v7") public Response servicePostRequest(final String jsonString) { @@ -138,6 +155,14 @@ public class TestSoDummyServer { return null; } + /** + * Post. + * + * @param serviceInstanceId service instance id + * @param vnfInstanceId vnf instance id + * @param jsonString json body + * @return http response + */ @POST @Path("/serviceInstantiation/v7/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/scaleOut") public Response servicePostRequestVfModules(@PathParam("serviceInstanceId") final String serviceInstanceId, @@ -221,6 +246,12 @@ public class TestSoDummyServer { return null; } + /** + * Get instance ID. + * + * @param nsInstanceId node instance id + * @return http response + */ @GET @Path("/orchestrationRequests/v5/{nsInstanceId}") public Response soRequestStatus(@PathParam("nsInstanceId") final String nsInstanceId) { diff --git a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoManager.java b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoManager.java new file mode 100644 index 000000000..38bfcd398 --- /dev/null +++ b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoManager.java @@ -0,0 +1,278 @@ +/*- + * ============LICENSE_START======================================================= + * TestSOManager + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.so; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URI; +import java.util.UUID; +import java.util.concurrent.Future; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.drools.core.WorkingMemory; +import org.glassfish.grizzly.http.server.HttpServer; +import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.drools.system.PolicyEngine; + +public class TestSoManager { + private static final String BASE_URI = "http://localhost:46553/TestSOManager"; + private static final String BASE_SO_URI = BASE_URI + "/SO"; + private static HttpServer server; + + @BeforeClass + public static void setUp() { + final ResourceConfig rc = new ResourceConfig(TestSoDummyServer.class); + server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); + } + + @AfterClass + public static void tearDown() throws Exception { + server.shutdown(); + } + + @Test + public void testGrizzlyServer() throws ClientProtocolException, IOException { + CloseableHttpClient httpclient = HttpClients.createDefault(); + HttpGet httpGet = new HttpGet("http://localhost:46553/TestSOManager/SO/Stats"); + CloseableHttpResponse response = httpclient.execute(httpGet); + + String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8"); + assertTrue(returnBody.matches("^\\{\"GET\": [0-9]*,\"STAT\": [0-9]*,\"POST\": [0-9]*,\"PUT\": [0-9]*\\}$")); + } + + @Test + public void testServiceInstantiation() throws IOException { + SOManager manager = new SOManager(); + assertNotNull(manager); + manager.setRestGetTimeout(100); + + SOResponse response = + manager.createModuleInstance("http:/localhost:99999999", BASE_SO_URI, "sean", "citizen", null); + assertNull(response); + + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", null); + assertNull(response); + + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", new SORequest()); + assertNull(response); + + SORequest request = new SORequest(); + request.setRequestId(UUID.randomUUID()); + request.setRequestScope("Test"); + request.setRequestType("ReturnBadJson"); + request.setStartTime("2018-03-23 16:31"); + request.setRequestStatus(new SORequestStatus()); + request.getRequestStatus().setRequestState("ONGOING"); + + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", request); + assertNull(response); + + request.setRequestType("ReturnCompleted"); + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", request); + assertNotNull(response); + assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); + + request.setRequestType("ReturnFailed"); + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", request); + assertNotNull(response); + assertEquals("FAILED", response.getRequest().getRequestStatus().getRequestState()); + + // Use scope to set the number of iterations we'll wait for + + request.setRequestType("ReturnOnging200"); + request.setRequestScope(new Integer(10).toString()); + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", request); + assertNotNull(response); + assertNotNull(response.getRequest()); + assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); + + request.setRequestType("ReturnOnging202"); + request.setRequestScope(new Integer(20).toString()); + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", request); + assertNotNull(response); + assertNotNull(response.getRequest()); + assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); + + // Test timeout after 20 attempts for a response + request.setRequestType("ReturnOnging202"); + request.setRequestScope(new Integer(21).toString()); + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", request); + assertNull(response); + + // Test bad response after 3 attempts for a response + request.setRequestType("ReturnBadAfterWait"); + request.setRequestScope(new Integer(3).toString()); + response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean", + "citizen", request); + assertNull(response); + } + + @Test + public void testVfModuleCreation() throws IOException { + SOManager manager = new SOManager(); + assertNotNull(manager); + manager.setRestGetTimeout(100); + + PolicyEngine.manager.setEnvironmentProperty("so.username", "sean"); + PolicyEngine.manager.setEnvironmentProperty("so.password", "citizen"); + + WorkingMemory wm = new DummyWorkingMemory(); + + PolicyEngine.manager.setEnvironmentProperty("so.url", "http:/localhost:99999999"); + Future asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, + UUID.randomUUID().toString(), UUID.randomUUID().toString(), null); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals(999, response.getHttpResponseCode()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + PolicyEngine.manager.setEnvironmentProperty("so.url", BASE_SO_URI); + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), null); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals(999, response.getHttpResponseCode()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), new SORequest()); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals(999, response.getHttpResponseCode()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + SORequest request = new SORequest(); + request.setRequestId(UUID.randomUUID()); + request.setRequestScope("Test"); + request.setRequestType("ReturnBadJson"); + request.setStartTime("2018-03-23 16:31"); + request.setRequestStatus(new SORequestStatus()); + request.getRequestStatus().setRequestState("ONGOING"); + + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), request); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals(999, response.getHttpResponseCode()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + request.setRequestType("ReturnCompleted"); + + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), request); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + request.setRequestType("ReturnFailed"); + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), request); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals("FAILED", response.getRequest().getRequestStatus().getRequestState()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + // Use scope to set the number of iterations we'll wait for + + request.setRequestType("ReturnOnging200"); + request.setRequestScope(new Integer(10).toString()); + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), request); + try { + SOResponse response = asyncRestCallFuture.get(); + assertNotNull(response.getRequest()); + assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + request.setRequestType("ReturnOnging202"); + request.setRequestScope(new Integer(20).toString()); + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), request); + try { + SOResponse response = asyncRestCallFuture.get(); + assertNotNull(response.getRequest()); + assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + // Test timeout after 20 attempts for a response + request.setRequestType("ReturnOnging202"); + request.setRequestScope(new Integer(21).toString()); + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), request); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals(999, response.getHttpResponseCode()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + + // Test bad response after 3 attempts for a response + request.setRequestType("ReturnBadAfterWait"); + request.setRequestScope(new Integer(3).toString()); + asyncRestCallFuture = manager.asyncSORestCall(UUID.randomUUID().toString(), wm, UUID.randomUUID().toString(), + UUID.randomUUID().toString(), request); + try { + SOResponse response = asyncRestCallFuture.get(); + assertEquals(999, response.getHttpResponseCode()); + } catch (Exception e) { + fail("test should not throw an exception"); + } + } +} diff --git a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoRequestDetails.java b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoRequestDetails.java index 6e9a2bade..c4b024593 100755 --- a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoRequestDetails.java +++ b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoRequestDetails.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * so * ================================================================================ - * + * 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. @@ -72,45 +72,45 @@ public class TestSoRequestDetails { assertEquals(subscriberInfo, obj.getSubscriberInfo()); } - @Test - public void testSOMRequestDetailsMethods() { - SORequestDetails details = new SORequestDetails(); - assertNotNull(details); - assertNotEquals(0, details.hashCode()); - - SOCloudConfiguration cloudConfiguration = new SOCloudConfiguration(); - details.setCloudConfiguration(cloudConfiguration); - assertEquals(cloudConfiguration, details.getCloudConfiguration()); - assertNotEquals(0, details.hashCode()); - - SOModelInfo modelInfo = new SOModelInfo(); - details.setModelInfo(modelInfo); - assertEquals(modelInfo, details.getModelInfo()); - assertNotEquals(0, details.hashCode()); - - List relatedInstanceList = new ArrayList<>(); - details.setRelatedInstanceList(relatedInstanceList); - assertEquals(relatedInstanceList, details.getRelatedInstanceList()); - assertNotEquals(0, details.hashCode()); - - SORequestInfo requestInfo = new SORequestInfo(); - details.setRequestInfo(requestInfo); - assertEquals(requestInfo, details.getRequestInfo()); - assertNotEquals(0, details.hashCode()); - - SORequestParameters requestParameters = new SORequestParameters(); - details.setRequestParameters(requestParameters); - assertEquals(requestParameters, details.getRequestParameters()); - assertNotEquals(0, details.hashCode()); - - SOSubscriberInfo subscriberInfo = new SOSubscriberInfo(); - details.setSubscriberInfo(subscriberInfo); - assertEquals(subscriberInfo, details.getSubscriberInfo()); - assertNotEquals(0, details.hashCode()); - - assertEquals("SORequestDetails [modelInfo=org.onap.policy.so", details.toString().substring(0, 46)); - - SORequestDetails copiedDetails = new SORequestDetails(details); + @Test + public void testSoMRequestDetailsMethods() { + SORequestDetails details = new SORequestDetails(); + assertNotNull(details); + assertNotEquals(0, details.hashCode()); + + SOCloudConfiguration cloudConfiguration = new SOCloudConfiguration(); + details.setCloudConfiguration(cloudConfiguration); + assertEquals(cloudConfiguration, details.getCloudConfiguration()); + assertNotEquals(0, details.hashCode()); + + SOModelInfo modelInfo = new SOModelInfo(); + details.setModelInfo(modelInfo); + assertEquals(modelInfo, details.getModelInfo()); + assertNotEquals(0, details.hashCode()); + + List relatedInstanceList = new ArrayList<>(); + details.setRelatedInstanceList(relatedInstanceList); + assertEquals(relatedInstanceList, details.getRelatedInstanceList()); + assertNotEquals(0, details.hashCode()); + + SORequestInfo requestInfo = new SORequestInfo(); + details.setRequestInfo(requestInfo); + assertEquals(requestInfo, details.getRequestInfo()); + assertNotEquals(0, details.hashCode()); + + SORequestParameters requestParameters = new SORequestParameters(); + details.setRequestParameters(requestParameters); + assertEquals(requestParameters, details.getRequestParameters()); + assertNotEquals(0, details.hashCode()); + + SOSubscriberInfo subscriberInfo = new SOSubscriberInfo(); + details.setSubscriberInfo(subscriberInfo); + assertEquals(subscriberInfo, details.getSubscriberInfo()); + assertNotEquals(0, details.hashCode()); + + assertEquals("SORequestDetails [modelInfo=org.onap.policy.so", details.toString().substring(0, 46)); + + SORequestDetails copiedDetails = new SORequestDetails(details); assertTrue(details.equals(details)); assertTrue(details.equals(copiedDetails)); @@ -143,7 +143,7 @@ public class TestSoRequestDetails { assertFalse(details.equals(copiedDetails)); copiedDetails.setRequestInfo(requestInfo); assertTrue(details.equals(copiedDetails)); - + details.setRequestParameters(null); assertFalse(details.equals(copiedDetails)); copiedDetails.setRequestParameters(null); @@ -152,7 +152,7 @@ public class TestSoRequestDetails { assertFalse(details.equals(copiedDetails)); copiedDetails.setRequestParameters(requestParameters); assertTrue(details.equals(copiedDetails)); - + details.setSubscriberInfo(null); assertFalse(details.equals(copiedDetails)); copiedDetails.setSubscriberInfo(null); @@ -161,14 +161,14 @@ public class TestSoRequestDetails { assertFalse(details.equals(copiedDetails)); copiedDetails.setSubscriberInfo(subscriberInfo); assertTrue(details.equals(copiedDetails)); - + details.setRelatedInstanceList(null); assertFalse(details.equals(copiedDetails)); - copiedDetails.setRelatedInstanceList(null); + copiedDetails.setRelatedInstanceList(null); assertTrue(details.equals(copiedDetails)); details.setRelatedInstanceList(relatedInstanceList); assertFalse(details.equals(copiedDetails)); - copiedDetails.setRelatedInstanceList(relatedInstanceList); + copiedDetails.setRelatedInstanceList(relatedInstanceList); assertTrue(details.equals(copiedDetails)); - } + } } diff --git a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoResponseWrapper.java b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoResponseWrapper.java index 4f21630a2..d7ef9708d 100755 --- a/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoResponseWrapper.java +++ b/controlloop/common/model-impl/so/src/test/java/org/onap/policy/so/TestSoResponseWrapper.java @@ -53,23 +53,23 @@ public class TestSoResponseWrapper { obj.setRequestID("id2"); assertEquals("id2", obj.getRequestID()); } - - @Test - public void testSOResponseWrapperMethods() { - String requestID = UUID.randomUUID().toString(); - SOResponse response = new SOResponse(); - - SOResponseWrapper responseWrapper = new SOResponseWrapper(response, requestID); - assertNotNull(responseWrapper); - assertNotEquals(0, responseWrapper.hashCode()); - - assertEquals(response, responseWrapper.getSoResponse()); - - assertNotEquals(0, responseWrapper.hashCode()); - - assertEquals("SOResponseWrapper [SOResponse=org.onap.policy.", responseWrapper.toString().substring(0, 46)); - - SOResponseWrapper identicalResponseWrapper = new SOResponseWrapper(response, requestID); + + @Test + public void testSoResponseWrapperMethods() { + String requestId = UUID.randomUUID().toString(); + SOResponse response = new SOResponse(); + + SOResponseWrapper responseWrapper = new SOResponseWrapper(response, requestId); + assertNotNull(responseWrapper); + assertNotEquals(0, responseWrapper.hashCode()); + + assertEquals(response, responseWrapper.getSoResponse()); + + assertNotEquals(0, responseWrapper.hashCode()); + + assertEquals("SOResponseWrapper [SOResponse=org.onap.policy.", responseWrapper.toString().substring(0, 46)); + + SOResponseWrapper identicalResponseWrapper = new SOResponseWrapper(response, requestId); assertEquals(responseWrapper, responseWrapper); assertEquals(responseWrapper, identicalResponseWrapper); @@ -81,25 +81,25 @@ public class TestSoResponseWrapper { assertEquals(new SOResponseWrapper(null, null), new SOResponseWrapper(null, null)); assertNotEquals(new SOResponseWrapper(null, null), identicalResponseWrapper); - assertNotEquals(0, new SOResponseWrapper(null, null).hashCode()); + assertNotEquals(0, new SOResponseWrapper(null, null).hashCode()); - identicalResponseWrapper.setSoResponse(new SOResponse()); + identicalResponseWrapper.setSoResponse(new SOResponse()); assertNotEquals(responseWrapper, identicalResponseWrapper); identicalResponseWrapper.setSoResponse(response); assertEquals(responseWrapper, identicalResponseWrapper); identicalResponseWrapper.setRequestID(UUID.randomUUID().toString()); assertNotEquals(responseWrapper, identicalResponseWrapper); - identicalResponseWrapper.setRequestID(requestID); + identicalResponseWrapper.setRequestID(requestId); assertEquals(responseWrapper, identicalResponseWrapper); responseWrapper.setRequestID(null); assertNotEquals(responseWrapper, identicalResponseWrapper); identicalResponseWrapper.setRequestID(null); assertEquals(responseWrapper, identicalResponseWrapper); - responseWrapper.setRequestID(requestID); + responseWrapper.setRequestID(requestId); assertNotEquals(responseWrapper, identicalResponseWrapper); - identicalResponseWrapper.setRequestID(requestID); + identicalResponseWrapper.setRequestID(requestId); assertEquals(responseWrapper, identicalResponseWrapper); - } + } } diff --git a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGRequest.java b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGRequest.java index 7bbaf3cbf..f4571d68c 100644 --- a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGRequest.java +++ b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGRequest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * trafficgenerator * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +20,12 @@ package org.onap.policy.vnf.trafficgenerator; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class PGRequest implements Serializable { - /** - * - */ private static final long serialVersionUID = -3283942659786236032L; @SerializedName("pg-streams") diff --git a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStream.java b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStream.java index a606eee4c..dad77e886 100644 --- a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStream.java +++ b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStream.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * trafficgenerator * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +20,12 @@ package org.onap.policy.vnf.trafficgenerator; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class PGStream implements Serializable { - /** - * - */ private static final long serialVersionUID = 5567635677419358210L; @SerializedName("id") diff --git a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStreams.java b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStreams.java index 2264c20a9..06117b9a3 100644 --- a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStreams.java +++ b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStreams.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * trafficgenerator * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,14 @@ package org.onap.policy.vnf.trafficgenerator; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.util.LinkedList; import java.util.List; -import com.google.gson.annotations.SerializedName; - public class PGStreams implements Serializable { - /** - * - */ private static final long serialVersionUID = 5567635677419358210L; @SerializedName("pg-stream") diff --git a/controlloop/common/model-impl/trafficgenerator/src/test/java/org/onap/policy/vnf/trafficgenerator/TestDemo.java b/controlloop/common/model-impl/trafficgenerator/src/test/java/org/onap/policy/vnf/trafficgenerator/TestDemo.java index 0ae5f134e..f35087794 100644 --- a/controlloop/common/model-impl/trafficgenerator/src/test/java/org/onap/policy/vnf/trafficgenerator/TestDemo.java +++ b/controlloop/common/model-impl/trafficgenerator/src/test/java/org/onap/policy/vnf/trafficgenerator/TestDemo.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * trafficgenerator * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ package org.onap.policy.vnf.trafficgenerator; - import org.junit.Test; + import org.onap.policy.vnf.trafficgenerator.PGRequest; import org.onap.policy.vnf.trafficgenerator.PGStream; import org.onap.policy.vnf.trafficgenerator.PGStreams; diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealActionVmInfo.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealActionVmInfo.java index a8004203e..0286a7d8b 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealActionVmInfo.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealActionVmInfo.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -18,37 +19,37 @@ package org.onap.policy.vfc; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class VFCHealActionVmInfo implements Serializable { - private static final long serialVersionUID = 3208673205100673119L; + private static final long serialVersionUID = 3208673205100673119L; - @SerializedName("vmid") - private String vmid; + @SerializedName("vmid") + private String vmid; - @SerializedName("vmname") - private String vmname; + @SerializedName("vmname") + private String vmname; - public VFCHealActionVmInfo() { - // Default constructor for VFCHealActionVmInfo - } + public VFCHealActionVmInfo() { + // Default constructor for VFCHealActionVmInfo + } - public String getVmid() { - return vmid; - } + public String getVmid() { + return vmid; + } - public void setVmid(String vmid) { - this.vmid = vmid; - } + public void setVmid(String vmid) { + this.vmid = vmid; + } - public String getVmname() { - return vmname; - } + public String getVmname() { + return vmname; + } - public void setVmname(String vmname) { - this.vmname = vmname; - } + public void setVmname(String vmname) { + this.vmname = vmname; + } } diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealAdditionalParams.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealAdditionalParams.java index 5c7555383..393e3761f 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealAdditionalParams.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealAdditionalParams.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -18,37 +19,37 @@ package org.onap.policy.vfc; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class VFCHealAdditionalParams implements Serializable { - private static final long serialVersionUID = 2656694137285096191L; + private static final long serialVersionUID = 2656694137285096191L; - @SerializedName("action") - private String action; + @SerializedName("action") + private String action; - @SerializedName("actionvminfo") - private VFCHealActionVmInfo actionInfo; + @SerializedName("actionvminfo") + private VFCHealActionVmInfo actionInfo; - public VFCHealAdditionalParams() { - // Default constructor for VFCHealAdditionalParams - } + public VFCHealAdditionalParams() { + // Default constructor for VFCHealAdditionalParams + } - public String getAction() { - return action; - } + public String getAction() { + return action; + } - public void setAction(String action) { - this.action = action; - } + public void setAction(String action) { + this.action = action; + } - public VFCHealActionVmInfo getActionInfo() { - return actionInfo; - } + public VFCHealActionVmInfo getActionInfo() { + return actionInfo; + } - public void setActionInfo(VFCHealActionVmInfo actionInfo) { - this.actionInfo = actionInfo; - } + public void setActionInfo(VFCHealActionVmInfo actionInfo) { + this.actionInfo = actionInfo; + } } diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealRequest.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealRequest.java index 11ea495a8..75b9566b1 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealRequest.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCHealRequest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -18,48 +19,48 @@ package org.onap.policy.vfc; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class VFCHealRequest implements Serializable { - private static final long serialVersionUID = -7341931593089709247L; + private static final long serialVersionUID = -7341931593089709247L; - @SerializedName("vnfInstanceId") - private String vnfInstanceId; + @SerializedName("vnfInstanceId") + private String vnfInstanceId; - @SerializedName("cause") - private String cause; + @SerializedName("cause") + private String cause; - @SerializedName("additionalParams") - private VFCHealAdditionalParams additionalParams; + @SerializedName("additionalParams") + private VFCHealAdditionalParams additionalParams; - public VFCHealRequest() { - // Default constructor for VFCHealRequest - } + public VFCHealRequest() { + // Default constructor for VFCHealRequest + } - public String getVnfInstanceId() { - return vnfInstanceId; - } + public String getVnfInstanceId() { + return vnfInstanceId; + } - public void setVnfInstanceId(String vnfInstanceId) { - this.vnfInstanceId = vnfInstanceId; - } + public void setVnfInstanceId(String vnfInstanceId) { + this.vnfInstanceId = vnfInstanceId; + } - public String getCause() { - return cause; - } + public String getCause() { + return cause; + } - public void setCause(String cause) { - this.cause = cause; - } + public void setCause(String cause) { + this.cause = cause; + } - public VFCHealAdditionalParams getAdditionalParams() { - return additionalParams; - } + public VFCHealAdditionalParams getAdditionalParams() { + return additionalParams; + } - public void setAdditionalParams(VFCHealAdditionalParams additionalParams) { - this.additionalParams = additionalParams; - } + public void setAdditionalParams(VFCHealAdditionalParams additionalParams) { + this.additionalParams = additionalParams; + } } diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCManager.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCManager.java index e5c9f5db9..1a8d603b5 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCManager.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCManager.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017-2018 Intel Corp, AT&T. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -46,6 +47,12 @@ public final class VFCManager implements Runnable { // The REST manager used for processing REST calls for this VFC manager private RESTManager restManager; + /** + * Constructor. + * + * @param wm Drools working memory + * @param request request + */ public VFCManager(WorkingMemory wm, VFCRequest request) { if (wm == null || request == null) { throw new IllegalArgumentException( @@ -61,6 +68,13 @@ public final class VFCManager implements Runnable { PolicyEngine.manager.getEnvironmentProperty("vfc.password")); } + /** + * Set the parameters. + * + * @param baseUrl base URL + * @param name username + * @param pwd password + */ public void setVFCParams(String baseUrl, String name, String pwd) { vfcUrlBase = baseUrl + "/api/nslcm/v1"; username = name; @@ -148,7 +162,7 @@ public final class VFCManager implements Runnable { } /** - * Protected setter for rest manager to allow mocked rest manager to be used for testing + * Protected setter for rest manager to allow mocked rest manager to be used for testing. * * @param restManager the test REST manager */ diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCRequest.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCRequest.java index 78802d641..cfcaf8039 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCRequest.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCRequest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -18,11 +19,11 @@ package org.onap.policy.vfc; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.util.UUID; -import com.google.gson.annotations.SerializedName; - public class VFCRequest implements Serializable { private static final long serialVersionUID = 3736300970326332512L; @@ -34,30 +35,30 @@ public class VFCRequest implements Serializable { private VFCHealRequest healRequest; public VFCRequest() { - // Default constructor for VFCRequest + // Default constructor for VFCRequest } - public String getNSInstanceId() { - return nsInstanceId; - } + public String getNSInstanceId() { + return nsInstanceId; + } - public void setNSInstanceId(String nsInstanceId) { - this.nsInstanceId = nsInstanceId; - } + public void setNSInstanceId(String nsInstanceId) { + this.nsInstanceId = nsInstanceId; + } - public UUID getRequestId() { - return requestId; - } + public UUID getRequestId() { + return requestId; + } - public void setRequestId(UUID requestId) { - this.requestId = requestId; - } + public void setRequestId(UUID requestId) { + this.requestId = requestId; + } - public VFCHealRequest getHealRequest() { - return healRequest; - } + public VFCHealRequest getHealRequest() { + return healRequest; + } - public void setHealRequest(VFCHealRequest healRequest) { - this.healRequest = healRequest; - } + public void setHealRequest(VFCHealRequest healRequest) { + this.healRequest = healRequest; + } } diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponse.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponse.java index 38b73b306..21e9472b7 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponse.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponse.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -18,10 +19,10 @@ package org.onap.policy.vfc; -import java.io.Serializable; - import com.google.gson.annotations.SerializedName; +import java.io.Serializable; + public class VFCResponse implements Serializable { private static final long serialVersionUID = 9151443891238218455L; @@ -35,30 +36,30 @@ public class VFCResponse implements Serializable { private transient String requestId; public VFCResponse() { - // Default constructor for VFCResponse + // Default constructor for VFCResponse } - public String getJobId() { - return jobId; - } + public String getJobId() { + return jobId; + } - public void setJobId(String jobId) { - this.jobId = jobId; - } + public void setJobId(String jobId) { + this.jobId = jobId; + } - public VFCResponseDescriptor getResponseDescriptor() { - return responseDescriptor; - } + public VFCResponseDescriptor getResponseDescriptor() { + return responseDescriptor; + } - public void setResponseDescriptor(VFCResponseDescriptor responseDescriptor) { - this.responseDescriptor = responseDescriptor; - } + public void setResponseDescriptor(VFCResponseDescriptor responseDescriptor) { + this.responseDescriptor = responseDescriptor; + } - public String getRequestId() { - return requestId; - } + public String getRequestId() { + return requestId; + } - public void setRequestId(String requestId) { - this.requestId = requestId; - } + public void setRequestId(String requestId) { + this.requestId = requestId; + } } diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponseDescriptor.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponseDescriptor.java index f237554fd..cdd4a39a9 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponseDescriptor.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/VFCResponseDescriptor.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -18,9 +19,10 @@ package org.onap.policy.vfc; +import com.google.gson.annotations.SerializedName; + import java.io.Serializable; import java.util.List; -import com.google.gson.annotations.SerializedName; public class VFCResponseDescriptor implements Serializable { @@ -45,54 +47,54 @@ public class VFCResponseDescriptor implements Serializable { private List responseHistoryList; public VFCResponseDescriptor() { - // Default constructor for VFCResponseDescriptor + // Default constructor for VFCResponseDescriptor } public String getStatus() { - return status; + return status; } - public String getProgress() { - return progress; - } + public String getProgress() { + return progress; + } - public void setProgress(String progress) { - this.progress = progress; - } + public void setProgress(String progress) { + this.progress = progress; + } - public String getStatusDescription() { - return statusDescription; - } + public String getStatusDescription() { + return statusDescription; + } - public void setStatusDescription(String statusDescription) { - this.statusDescription = statusDescription; - } + public void setStatusDescription(String statusDescription) { + this.statusDescription = statusDescription; + } - public String getErrorCode() { - return errorCode; - } + public String getErrorCode() { + return errorCode; + } - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } - public String getResponseId() { - return responseId; - } + public String getResponseId() { + return responseId; + } - public void setResponseId(String responseId) { - this.responseId = responseId; - } + public void setResponseId(String responseId) { + this.responseId = responseId; + } - public List getResponseHistoryList() { - return responseHistoryList; - } + public List getResponseHistoryList() { + return responseHistoryList; + } - public void setResponseHistoryList(List responseHistoryList) { - this.responseHistoryList = responseHistoryList; - } + public void setResponseHistoryList(List responseHistoryList) { + this.responseHistoryList = responseHistoryList; + } - public void setStatus(String status) { - this.status = status; - } + public void setStatus(String status) { + this.status = status; + } } diff --git a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/util/Serialization.java b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/util/Serialization.java index dc8662b84..2259296d2 100644 --- a/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/util/Serialization.java +++ b/controlloop/common/model-impl/vfc/src/main/java/org/onap/policy/vfc/util/Serialization.java @@ -22,11 +22,11 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; public final class Serialization { - private Serialization() { - } - - public static final Gson gsonPretty = new GsonBuilder().disableHtmlEscaping() - .setPrettyPrinting() - .create(); + private Serialization() { + } + + public static final Gson gsonPretty = new GsonBuilder().disableHtmlEscaping() + .setPrettyPrinting() + .create(); } diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestDemo.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestDemo.java index 69d3d5838..a5f40f30e 100644 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestDemo.java +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestDemo.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2017 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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. @@ -66,7 +67,7 @@ public class TestDemo { responseDescriptor.setErrorCode(null); responseDescriptor.setResponseId("11"); - response.getResponseDescriptor().setResponseHistoryList(new LinkedList<>()); + response.getResponseDescriptor().setResponseHistoryList(new LinkedList<>()); response.getResponseDescriptor().getResponseHistoryList().add(responseDescriptor); body = Serialization.gsonPretty.toJson(response); diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealActionVmInfo.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealActionVmInfo.java deleted file mode 100644 index ab57f6415..000000000 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealActionVmInfo.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * 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.vfc; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TestVFCHealActionVmInfo { - - @Test - public void testVFCHealActionVmInfo() { - VFCHealActionVmInfo actionInfo = new VFCHealActionVmInfo(); - assertNotNull(actionInfo); - assertNotEquals(0, actionInfo.hashCode()); - - String vmid = "ECity"; - actionInfo.setVmid(vmid); - assertEquals(vmid, actionInfo.getVmid()); - - String vmName = "Emerald City"; - actionInfo.setVmname(vmName); - assertEquals(vmName, actionInfo.getVmname()); - - assertNotEquals(0, actionInfo.hashCode()); - } -} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealAdditionalParams.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealAdditionalParams.java deleted file mode 100644 index 7fa8fd741..000000000 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealAdditionalParams.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * 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.vfc; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TestVFCHealAdditionalParams { - - @Test - public void testVFCHealAdditionalParameters() { - VFCHealAdditionalParams additionalParams = new VFCHealAdditionalParams(); - assertNotNull(additionalParams); - assertNotEquals(0, additionalParams.hashCode()); - - String action = "Go Home"; - additionalParams.setAction(action); - assertEquals(action, additionalParams.getAction()); - - VFCHealActionVmInfo actionInfo = new VFCHealActionVmInfo(); - additionalParams.setActionInfo(actionInfo ); - assertEquals(actionInfo, additionalParams.getActionInfo()); - - assertNotEquals(0, additionalParams.hashCode()); - } -} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealRequest.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealRequest.java deleted file mode 100644 index 5a78bfb0c..000000000 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCHealRequest.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * 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.vfc; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TestVFCHealRequest { - - @Test - public void testVFCHealRequest() { - VFCHealRequest request = new VFCHealRequest(); - assertNotNull(request); - assertNotEquals(0, request.hashCode()); - - String vnfInstanceId = "Go To Oz"; - request.setVnfInstanceId(vnfInstanceId); - assertEquals(vnfInstanceId, request.getVnfInstanceId()); - - String cause = "West Witch"; - request.setCause(cause); - assertEquals(cause, request.getCause()); - - VFCHealAdditionalParams additionalParams= new VFCHealAdditionalParams(); - request.setAdditionalParams(additionalParams); - assertEquals(additionalParams, request.getAdditionalParams()); - - assertNotEquals(0, request.hashCode()); - } -} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCManager.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCManager.java deleted file mode 100644 index fa2a1ee9f..000000000 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCManager.java +++ /dev/null @@ -1,275 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * Copyright (C) 2018 Ericsson, AT&T. 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.vfc; - -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.startsWith; -import static org.mockito.Mockito.*; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.drools.core.WorkingMemory; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.rest.RESTManager; -import org.onap.policy.rest.RESTManager.Pair; -import org.onap.policy.vfc.util.Serialization; - -public class TestVFCManager { - private static WorkingMemory mockedWorkingMemory; - - private RESTManager mockedRESTManager; - - private Pair httpResponsePutOK; - private Pair httpResponseGetOK; - private Pair httpResponseBadResponse; - private Pair httpResponseErr; - - private VFCRequest request; - private VFCResponse response; - - @BeforeClass - public static void beforeTestVFCManager() { - mockedWorkingMemory = mock(WorkingMemory.class); - } - - @Before - public void setupMockedRest() { - mockedRESTManager = mock(RESTManager.class); - - httpResponsePutOK = mockedRESTManager.new Pair<>(202, Serialization.gsonPretty.toJson(response)); - httpResponseGetOK = mockedRESTManager.new Pair<>(200, Serialization.gsonPretty.toJson(response)); - httpResponseBadResponse = mockedRESTManager.new Pair<>(202, Serialization.gsonPretty.toJson(null)); - httpResponseErr = mockedRESTManager.new Pair<>(200, null); - } - - @Before - public void createRequestAndResponse() { - VFCHealActionVmInfo actionInfo = new VFCHealActionVmInfo(); - actionInfo.setVmid("TheWizard"); - actionInfo.setVmname("The Wizard of Oz"); - - VFCHealAdditionalParams additionalParams = new VFCHealAdditionalParams(); - additionalParams.setAction("Go Home"); - additionalParams.setActionInfo(actionInfo); - - VFCHealRequest healRequest = new VFCHealRequest(); - healRequest.setAdditionalParams(additionalParams); - healRequest.setCause("WestWitch"); - healRequest.setVnfInstanceId("EmeraldCity"); - - UUID requestId = UUID.randomUUID(); - request = new VFCRequest(); - request.setHealRequest(healRequest); - request.setNSInstanceId("Dorothy"); - request.setRequestId(requestId); - - List responseHistoryList = new ArrayList<>();; - - VFCResponseDescriptor responseDescriptor = new VFCResponseDescriptor(); - responseDescriptor.setErrorCode("1234"); - responseDescriptor.setProgress("Follow The Yellow Brick Road"); - responseDescriptor.setResponseHistoryList(responseHistoryList); - responseDescriptor.setResponseId(UUID.randomUUID().toString()); - responseDescriptor.setStatus("finished"); - responseDescriptor.setStatusDescription("There's no place like home"); - - response = new VFCResponse(); - response.setJobId("1234"); - response.setRequestId(request.getRequestId().toString()); - response.setResponseDescriptor(responseDescriptor); - } - - @After - public void tearDown() { - PolicyEngine.manager.getEnvironment().remove("vfc.password"); - PolicyEngine.manager.getEnvironment().remove("vfc.username"); - PolicyEngine.manager.getEnvironment().remove("vfc.url"); - } - - @Test - public void testVFCInitiation() { - try { - new VFCManager(null, null); - fail("test should throw an exception here"); - } - catch (IllegalArgumentException e) { - assertEquals("the parameters \"wm\" and \"request\" on the VFCManager constructor may not be null", e.getMessage()); - } - - try { - new VFCManager(mockedWorkingMemory, null); - fail("test should throw an exception here"); - } - catch (IllegalArgumentException e) { - assertEquals("the parameters \"wm\" and \"request\" on the VFCManager constructor may not be null", e.getMessage()); - } - - try { - new VFCManager(mockedWorkingMemory, request); - fail("test should throw an exception here"); - } - catch (IllegalArgumentException e) { - assertEquals("The value of policy engine manager environment property \"vfc.url\" may not be null", e.getMessage()); - } - - // add url; username & password are not required - PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); - new VFCManager(mockedWorkingMemory, request); - - // url & username, but no password - PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); - - // url, username, and password - PolicyEngine.manager.getEnvironment().put("vfc.password", "Toto"); - new VFCManager(mockedWorkingMemory, request); - } - - @Test - public void testVFCExecutionException() throws InterruptedException { - PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); - PolicyEngine.manager.getEnvironment().put("vfc.password", "Exception"); - - VFCManager manager = new VFCManager(mockedWorkingMemory, request); - manager.setRestManager(mockedRESTManager); - - Thread managerThread = new Thread(manager); - managerThread.start(); - - when(mockedRESTManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Exception"), anyMap(), anyString(), anyString())) - .thenThrow(new RuntimeException("OzException")); - - while (managerThread.isAlive()) { - Thread.sleep(100); - } - - PolicyEngine.manager.getEnvironment().remove("vfc.password"); - PolicyEngine.manager.getEnvironment().remove("vfc.username"); - PolicyEngine.manager.getEnvironment().remove("vfc.url"); - } - - @Test - public void testVFCExecutionNull() throws InterruptedException { - PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); - PolicyEngine.manager.getEnvironment().put("vfc.password", "Null"); - - VFCManager manager = new VFCManager(mockedWorkingMemory, request); - manager.setRestManager(mockedRESTManager); - - Thread managerThread = new Thread(manager); - managerThread.start(); - - when(mockedRESTManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Null"), anyMap(), anyString(), anyString())) - .thenReturn(null); - - while (managerThread.isAlive()) { - Thread.sleep(100); - } - - PolicyEngine.manager.getEnvironment().remove("vfc.password"); - PolicyEngine.manager.getEnvironment().remove("vfc.username"); - PolicyEngine.manager.getEnvironment().remove("vfc.url"); - } - - @Test - public void testVFCExecutionError0() throws InterruptedException { - PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); - PolicyEngine.manager.getEnvironment().put("vfc.password", "Error0"); - - VFCManager manager = new VFCManager(mockedWorkingMemory, request); - manager.setRestManager(mockedRESTManager); - - Thread managerThread = new Thread(manager); - managerThread.start(); - - when(mockedRESTManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Error0"), anyMap(), anyString(), anyString())) - .thenReturn(httpResponseErr); - - while (managerThread.isAlive()) { - Thread.sleep(100); - } - - PolicyEngine.manager.getEnvironment().remove("vfc.password"); - PolicyEngine.manager.getEnvironment().remove("vfc.username"); - PolicyEngine.manager.getEnvironment().remove("vfc.url"); - } - - @Test - public void testVFCExecutionBadResponse() throws InterruptedException { - PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); - PolicyEngine.manager.getEnvironment().put("vfc.password", "BadResponse"); - - VFCManager manager = new VFCManager(mockedWorkingMemory, request); - manager.setRestManager(mockedRESTManager); - - Thread managerThread = new Thread(manager); - managerThread.start(); - - when(mockedRESTManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString())) - .thenReturn(httpResponseBadResponse); - - while (managerThread.isAlive()) { - Thread.sleep(100); - } - - PolicyEngine.manager.getEnvironment().remove("vfc.password"); - PolicyEngine.manager.getEnvironment().remove("vfc.username"); - PolicyEngine.manager.getEnvironment().remove("vfc.url"); - } - - @Test - public void testVFCExecutionOK() throws InterruptedException { - PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); - PolicyEngine.manager.getEnvironment().put("vfc.password", "OK"); - - VFCManager manager = new VFCManager(mockedWorkingMemory, request); - manager.setRestManager(mockedRESTManager); - - Thread managerThread = new Thread(manager); - managerThread.start(); - - when(mockedRESTManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString())) - .thenReturn(httpResponsePutOK); - - when(mockedRESTManager.get(endsWith("1234"), eq("Dorothy"), eq("OK"), anyMap())) - .thenReturn(httpResponseGetOK); - - while (managerThread.isAlive()) { - Thread.sleep(100); - } - - PolicyEngine.manager.getEnvironment().remove("vfc.password"); - PolicyEngine.manager.getEnvironment().remove("vfc.username"); - PolicyEngine.manager.getEnvironment().remove("vfc.url"); - } -} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCRequest.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCRequest.java deleted file mode 100644 index 64307fec8..000000000 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCRequest.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * 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.vfc; - -import static org.junit.Assert.*; - -import java.util.UUID; - -import org.junit.Test; - -public class TestVFCRequest { - - @Test - public void testVFCRequest() { - VFCRequest request = new VFCRequest(); - assertNotNull(request); - assertNotEquals(0, request.hashCode()); - - String nsInstanceId = "Dorothy"; - request.setNSInstanceId(nsInstanceId); - assertEquals(nsInstanceId, request.getNSInstanceId()); - - UUID requestId = UUID.randomUUID(); - request.setRequestId(requestId); - assertEquals(requestId, request.getRequestId()); - - VFCHealRequest healRequest = new VFCHealRequest(); - request.setHealRequest(healRequest); - assertEquals(healRequest, request.getHealRequest()); - - assertNotEquals(0, request.hashCode()); - } -} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponse.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponse.java deleted file mode 100644 index 36591a910..000000000 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponse.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * 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.vfc; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TestVFCResponse { - - @Test - public void testVFCResponse() { - VFCResponse response = new VFCResponse(); - assertNotNull(response); - assertNotEquals(0, response.hashCode()); - - String jobId = "GetToOz"; - response.setJobId(jobId); - assertEquals(jobId, response.getJobId()); - - String requestId = "Get Home"; - response.setRequestId(requestId); - assertEquals(requestId, response.getRequestId()); - - VFCResponseDescriptor responseDescriptor = new VFCResponseDescriptor(); - response.setResponseDescriptor(responseDescriptor); - assertEquals(responseDescriptor, response.getResponseDescriptor()); - - assertNotEquals(0, response.hashCode()); - } -} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponseDescriptor.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponseDescriptor.java deleted file mode 100644 index a2b59dd20..000000000 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVFCResponseDescriptor.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * 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.vfc; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -public class TestVFCResponseDescriptor { - - @Test - public void testVFCResponseDescriptor() { - VFCResponseDescriptor descriptor = new VFCResponseDescriptor(); - assertNotNull(descriptor); - assertNotEquals(0, descriptor.hashCode()); - - String errorCode = "WitchIsDead"; - descriptor.setErrorCode(errorCode); - assertEquals(errorCode, descriptor.getErrorCode()); - - String progress = "Visited Wizard"; - descriptor.setProgress(progress); - assertEquals(progress, descriptor.getProgress()); - - List responseHistoryList = new ArrayList<>(); - descriptor.setResponseHistoryList(responseHistoryList); - assertEquals(responseHistoryList, descriptor.getResponseHistoryList()); - - String responseId = "WishHard"; - descriptor.setResponseId(responseId); - assertEquals(responseId, descriptor.getResponseId()); - - String status = "Back in Kansas"; - descriptor.setStatus(status); - assertEquals(status, descriptor.getStatus()); - - String statusDescription = "Back on the prairie"; - descriptor.setStatusDescription(statusDescription); - assertEquals(statusDescription, descriptor.getStatusDescription()); - - assertNotEquals(0, descriptor.hashCode()); - } -} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealActionVmInfo.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealActionVmInfo.java new file mode 100644 index 000000000..55f9ab8d5 --- /dev/null +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealActionVmInfo.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * vfc + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class TestVfcHealActionVmInfo { + + @Test + public void testVfcHealActionVmInfo() { + VFCHealActionVmInfo actionInfo = new VFCHealActionVmInfo(); + assertNotNull(actionInfo); + assertNotEquals(0, actionInfo.hashCode()); + + String vmid = "ECity"; + actionInfo.setVmid(vmid); + assertEquals(vmid, actionInfo.getVmid()); + + String vmName = "Emerald City"; + actionInfo.setVmname(vmName); + assertEquals(vmName, actionInfo.getVmname()); + + assertNotEquals(0, actionInfo.hashCode()); + } +} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealAdditionalParams.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealAdditionalParams.java new file mode 100644 index 000000000..b74fe1a93 --- /dev/null +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealAdditionalParams.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * vfc + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class TestVfcHealAdditionalParams { + + @Test + public void testVfcHealAdditionalParameters() { + VFCHealAdditionalParams additionalParams = new VFCHealAdditionalParams(); + assertNotNull(additionalParams); + assertNotEquals(0, additionalParams.hashCode()); + + String action = "Go Home"; + additionalParams.setAction(action); + assertEquals(action, additionalParams.getAction()); + + VFCHealActionVmInfo actionInfo = new VFCHealActionVmInfo(); + additionalParams.setActionInfo(actionInfo ); + assertEquals(actionInfo, additionalParams.getActionInfo()); + + assertNotEquals(0, additionalParams.hashCode()); + } +} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealRequest.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealRequest.java new file mode 100644 index 000000000..4c442bc2c --- /dev/null +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcHealRequest.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * vfc + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class TestVfcHealRequest { + + @Test + public void testVfcHealRequest() { + VFCHealRequest request = new VFCHealRequest(); + assertNotNull(request); + assertNotEquals(0, request.hashCode()); + + String vnfInstanceId = "Go To Oz"; + request.setVnfInstanceId(vnfInstanceId); + assertEquals(vnfInstanceId, request.getVnfInstanceId()); + + String cause = "West Witch"; + request.setCause(cause); + assertEquals(cause, request.getCause()); + + VFCHealAdditionalParams additionalParams = new VFCHealAdditionalParams(); + request.setAdditionalParams(additionalParams); + assertEquals(additionalParams, request.getAdditionalParams()); + + assertNotEquals(0, request.hashCode()); + } +} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcManager.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcManager.java new file mode 100644 index 000000000..9913d39b8 --- /dev/null +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcManager.java @@ -0,0 +1,303 @@ +/*- + * ============LICENSE_START======================================================= + * vfc + * ================================================================================ + * Copyright (C) 2018 Ericsson, AT&T. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.endsWith; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.drools.core.WorkingMemory; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.rest.RESTManager; +import org.onap.policy.rest.RESTManager.Pair; +import org.onap.policy.vfc.util.Serialization; + +public class TestVfcManager { + private static WorkingMemory mockedWorkingMemory; + + private RESTManager mockedRestManager; + + private Pair httpResponsePutOk; + private Pair httpResponseGetOk; + private Pair httpResponseBadResponse; + private Pair httpResponseErr; + + private VFCRequest request; + private VFCResponse response; + + @BeforeClass + public static void beforeTestVfcManager() { + mockedWorkingMemory = mock(WorkingMemory.class); + } + + /** + * Set up the mocked REST manager. + */ + @Before + public void setupMockedRest() { + mockedRestManager = mock(RESTManager.class); + + httpResponsePutOk = mockedRestManager.new Pair<>(202, Serialization.gsonPretty.toJson(response)); + httpResponseGetOk = mockedRestManager.new Pair<>(200, Serialization.gsonPretty.toJson(response)); + httpResponseBadResponse = mockedRestManager.new Pair<>(202, Serialization.gsonPretty.toJson(null)); + httpResponseErr = mockedRestManager.new Pair<>(200, null); + } + + /** + * Create the request and response before. + */ + @Before + public void createRequestAndResponse() { + VFCHealActionVmInfo actionInfo = new VFCHealActionVmInfo(); + actionInfo.setVmid("TheWizard"); + actionInfo.setVmname("The Wizard of Oz"); + + VFCHealAdditionalParams additionalParams = new VFCHealAdditionalParams(); + additionalParams.setAction("Go Home"); + additionalParams.setActionInfo(actionInfo); + + VFCHealRequest healRequest = new VFCHealRequest(); + healRequest.setAdditionalParams(additionalParams); + healRequest.setCause("WestWitch"); + healRequest.setVnfInstanceId("EmeraldCity"); + + final UUID requestId = UUID.randomUUID(); + request = new VFCRequest(); + request.setHealRequest(healRequest); + request.setNSInstanceId("Dorothy"); + request.setRequestId(requestId); + + List responseHistoryList = new ArrayList<>();; + + VFCResponseDescriptor responseDescriptor = new VFCResponseDescriptor(); + responseDescriptor.setErrorCode("1234"); + responseDescriptor.setProgress("Follow The Yellow Brick Road"); + responseDescriptor.setResponseHistoryList(responseHistoryList); + responseDescriptor.setResponseId(UUID.randomUUID().toString()); + responseDescriptor.setStatus("finished"); + responseDescriptor.setStatusDescription("There's no place like home"); + + response = new VFCResponse(); + response.setJobId("1234"); + response.setRequestId(request.getRequestId().toString()); + response.setResponseDescriptor(responseDescriptor); + } + + /** + * Remove the environnment. + */ + @After + public void tearDown() { + PolicyEngine.manager.getEnvironment().remove("vfc.password"); + PolicyEngine.manager.getEnvironment().remove("vfc.username"); + PolicyEngine.manager.getEnvironment().remove("vfc.url"); + } + + @Test + public void testVfcInitiation() { + try { + new VFCManager(null, null); + fail("test should throw an exception here"); + } + catch (IllegalArgumentException e) { + assertEquals("the parameters \"wm\" and \"request\" on the VFCManager constructor may not be null", + e.getMessage()); + } + + try { + new VFCManager(mockedWorkingMemory, null); + fail("test should throw an exception here"); + } + catch (IllegalArgumentException e) { + assertEquals("the parameters \"wm\" and \"request\" on the VFCManager constructor may not be null", + e.getMessage()); + } + + try { + new VFCManager(mockedWorkingMemory, request); + fail("test should throw an exception here"); + } + catch (IllegalArgumentException e) { + assertEquals("The value of policy engine manager environment property \"vfc.url\" may not be null", + e.getMessage()); + } + + // add url; username & password are not required + PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); + new VFCManager(mockedWorkingMemory, request); + + // url & username, but no password + PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); + + // url, username, and password + PolicyEngine.manager.getEnvironment().put("vfc.password", "Toto"); + new VFCManager(mockedWorkingMemory, request); + } + + @Test + public void testVfcExecutionException() throws InterruptedException { + PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); + PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); + PolicyEngine.manager.getEnvironment().put("vfc.password", "Exception"); + + VFCManager manager = new VFCManager(mockedWorkingMemory, request); + manager.setRestManager(mockedRestManager); + + Thread managerThread = new Thread(manager); + managerThread.start(); + + when(mockedRestManager.post( + startsWith("http://somewhere.over.the.rainbow"), + eq("Dorothy"), + eq("Exception"), + anyMap(), + anyString(), + anyString())) + .thenThrow(new RuntimeException("OzException")); + + while (managerThread.isAlive()) { + Thread.sleep(100); + } + + PolicyEngine.manager.getEnvironment().remove("vfc.password"); + PolicyEngine.manager.getEnvironment().remove("vfc.username"); + PolicyEngine.manager.getEnvironment().remove("vfc.url"); + } + + @Test + public void testVfcExecutionNull() throws InterruptedException { + PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); + PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); + PolicyEngine.manager.getEnvironment().put("vfc.password", "Null"); + + VFCManager manager = new VFCManager(mockedWorkingMemory, request); + manager.setRestManager(mockedRestManager); + + Thread managerThread = new Thread(manager); + managerThread.start(); + + when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), + eq("Dorothy"), eq("Null"), anyMap(), anyString(), anyString())) + .thenReturn(null); + + while (managerThread.isAlive()) { + Thread.sleep(100); + } + + PolicyEngine.manager.getEnvironment().remove("vfc.password"); + PolicyEngine.manager.getEnvironment().remove("vfc.username"); + PolicyEngine.manager.getEnvironment().remove("vfc.url"); + } + + @Test + public void testVfcExecutionError0() throws InterruptedException { + PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); + PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); + PolicyEngine.manager.getEnvironment().put("vfc.password", "Error0"); + + VFCManager manager = new VFCManager(mockedWorkingMemory, request); + manager.setRestManager(mockedRestManager); + + Thread managerThread = new Thread(manager); + managerThread.start(); + + when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), + eq("Dorothy"), eq("Error0"), anyMap(), anyString(), anyString())) + .thenReturn(httpResponseErr); + + while (managerThread.isAlive()) { + Thread.sleep(100); + } + + PolicyEngine.manager.getEnvironment().remove("vfc.password"); + PolicyEngine.manager.getEnvironment().remove("vfc.username"); + PolicyEngine.manager.getEnvironment().remove("vfc.url"); + } + + @Test + public void testVfcExecutionBadResponse() throws InterruptedException { + PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); + PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); + PolicyEngine.manager.getEnvironment().put("vfc.password", "BadResponse"); + + VFCManager manager = new VFCManager(mockedWorkingMemory, request); + manager.setRestManager(mockedRestManager); + + Thread managerThread = new Thread(manager); + managerThread.start(); + + when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), + eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString())) + .thenReturn(httpResponseBadResponse); + + while (managerThread.isAlive()) { + Thread.sleep(100); + } + + PolicyEngine.manager.getEnvironment().remove("vfc.password"); + PolicyEngine.manager.getEnvironment().remove("vfc.username"); + PolicyEngine.manager.getEnvironment().remove("vfc.url"); + } + + @Test + public void testVfcExecutionOk() throws InterruptedException { + PolicyEngine.manager.getEnvironment().put("vfc.url", "http://somewhere.over.the.rainbow"); + PolicyEngine.manager.getEnvironment().put("vfc.username", "Dorothy"); + PolicyEngine.manager.getEnvironment().put("vfc.password", "OK"); + + VFCManager manager = new VFCManager(mockedWorkingMemory, request); + manager.setRestManager(mockedRestManager); + + Thread managerThread = new Thread(manager); + managerThread.start(); + + when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), + eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString())) + .thenReturn(httpResponsePutOk); + + when(mockedRestManager.get(endsWith("1234"), eq("Dorothy"), eq("OK"), anyMap())) + .thenReturn(httpResponseGetOk); + + while (managerThread.isAlive()) { + Thread.sleep(100); + } + + PolicyEngine.manager.getEnvironment().remove("vfc.password"); + PolicyEngine.manager.getEnvironment().remove("vfc.username"); + PolicyEngine.manager.getEnvironment().remove("vfc.url"); + } +} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcRequest.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcRequest.java new file mode 100644 index 000000000..0ec5d7d82 --- /dev/null +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcRequest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * vfc + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; + +import org.junit.Test; + +public class TestVfcRequest { + + @Test + public void testVfcRequest() { + VFCRequest request = new VFCRequest(); + assertNotNull(request); + assertNotEquals(0, request.hashCode()); + + String nsInstanceId = "Dorothy"; + request.setNSInstanceId(nsInstanceId); + assertEquals(nsInstanceId, request.getNSInstanceId()); + + UUID requestId = UUID.randomUUID(); + request.setRequestId(requestId); + assertEquals(requestId, request.getRequestId()); + + VFCHealRequest healRequest = new VFCHealRequest(); + request.setHealRequest(healRequest); + assertEquals(healRequest, request.getHealRequest()); + + assertNotEquals(0, request.hashCode()); + } +} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponse.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponse.java new file mode 100644 index 000000000..698459ad2 --- /dev/null +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponse.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * vfc + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class TestVfcResponse { + + @Test + public void testVfcResponse() { + VFCResponse response = new VFCResponse(); + assertNotNull(response); + assertNotEquals(0, response.hashCode()); + + String jobId = "GetToOz"; + response.setJobId(jobId); + assertEquals(jobId, response.getJobId()); + + String requestId = "Get Home"; + response.setRequestId(requestId); + assertEquals(requestId, response.getRequestId()); + + VFCResponseDescriptor responseDescriptor = new VFCResponseDescriptor(); + response.setResponseDescriptor(responseDescriptor); + assertEquals(responseDescriptor, response.getResponseDescriptor()); + + assertNotEquals(0, response.hashCode()); + } +} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponseDescriptor.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponseDescriptor.java new file mode 100644 index 000000000..927306fd8 --- /dev/null +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/TestVfcResponseDescriptor.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * vfc + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. 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.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class TestVfcResponseDescriptor { + + @Test + public void testVfcResponseDescriptor() { + VFCResponseDescriptor descriptor = new VFCResponseDescriptor(); + assertNotNull(descriptor); + assertNotEquals(0, descriptor.hashCode()); + + String errorCode = "WitchIsDead"; + descriptor.setErrorCode(errorCode); + assertEquals(errorCode, descriptor.getErrorCode()); + + String progress = "Visited Wizard"; + descriptor.setProgress(progress); + assertEquals(progress, descriptor.getProgress()); + + List responseHistoryList = new ArrayList<>(); + descriptor.setResponseHistoryList(responseHistoryList); + assertEquals(responseHistoryList, descriptor.getResponseHistoryList()); + + String responseId = "WishHard"; + descriptor.setResponseId(responseId); + assertEquals(responseId, descriptor.getResponseId()); + + String status = "Back in Kansas"; + descriptor.setStatus(status); + assertEquals(status, descriptor.getStatus()); + + String statusDescription = "Back on the prairie"; + descriptor.setStatusDescription(statusDescription); + assertEquals(statusDescription, descriptor.getStatusDescription()); + + assertNotEquals(0, descriptor.hashCode()); + } +} diff --git a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/util/TestSerialization.java b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/util/TestSerialization.java index 3c4f6154e..b66806213 100644 --- a/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/util/TestSerialization.java +++ b/controlloop/common/model-impl/vfc/src/test/java/org/onap/policy/vfc/util/TestSerialization.java @@ -3,6 +3,7 @@ * vfc * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Corporation. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,14 +21,14 @@ package org.onap.policy.vfc.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.junit.Test; public class TestSerialization { - @Test - public void test() { - assertNotNull(Serialization.gsonPretty); - } + @Test + public void test() { + assertNotNull(Serialization.gsonPretty); + } } 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 27c9bf8cd..45ff1847b 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,7 +101,7 @@ public class ControlLoopCompiler implements Serializable { && callback != null) { callback.onError("Missing controlLoopName"); } - if ((!controlLoop.getVersion().contentEquals(ControlLoop.getVERSION())) && callback != null) { + if ((!controlLoop.getVersion().contentEquals(ControlLoop.getCompilerVersion())) && callback != null) { callback.onError("Unsupported version for this compiler"); } if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) { 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 2897fde26..4cee39cb4 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 @@ -20,8 +20,8 @@ package org.onap.policy.controlloop.guard.compiler; - import java.io.InputStream; + import java.util.HashSet; import java.util.List; import java.util.Set; @@ -43,24 +43,40 @@ public class ControlLoopGuardCompiler { // Private Constructor } - public static ControlLoopGuard compile(ControlLoopGuard cLGuard, + /** + * Compile the control loop guard. + * + * @param clGuard the guard + * @param callback callback routine + * @return the guard object + * @throws CompilerException compilation exception + */ + public static ControlLoopGuard compile(ControlLoopGuard clGuard, ControlLoopCompilerCallback callback) throws CompilerException { // // Ensure ControlLoopGuard has at least one guard policies // - validateControlLoopGuard(cLGuard, callback); + validateControlLoopGuard(clGuard, callback); // // Ensure each guard policy has at least one constraints and all guard policies are unique // - validateGuardPolicies(cLGuard.getGuards(), callback); + validateGuardPolicies(clGuard.getGuards(), callback); // // Ensure constraints for each guard policy are unique // - validateConstraints(cLGuard.getGuards(), callback); + validateConstraints(clGuard.getGuards(), callback); - return cLGuard; + return clGuard; } + /** + * Compile the control loop guard. + * + * @param yamlSpecification yaml specification as a stream + * @param callback callback method + * @return guard object + * @throws CompilerException throws compile exception + */ public static ControlLoopGuard compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); @@ -74,22 +90,22 @@ public class ControlLoopGuardCompiler { return ControlLoopGuardCompiler.compile((ControlLoopGuard) obj, callback); } - private static void validateControlLoopGuard(ControlLoopGuard cLGuard, + private static void validateControlLoopGuard(ControlLoopGuard clGuard, ControlLoopCompilerCallback callback) throws CompilerException { - if (cLGuard == null) { + if (clGuard == null) { if (callback != null) { callback.onError("ControlLoop Guard cannot be null"); } throw new CompilerException("ControlLoop Guard cannot be null"); } - if (cLGuard.getGuard() == null && callback != null) { + if (clGuard.getGuard() == null && callback != null) { callback.onError("Guard version cannot be null"); } - if (cLGuard.getGuards() == null) { + if (clGuard.getGuards() == null) { if (callback != null) { callback.onError("ControlLoop Guard should have at least one guard policies"); } - } else if (cLGuard.getGuards().isEmpty() && callback != null) { + } else if (clGuard.getGuards().isEmpty() && callback != null) { callback.onError("ControlLoop Guard should have at least one guard policies"); } } 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 fc835dd51..a8edf7a81 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public class ControlLoop { // Empty Constructor. } - public static String getVERSION() { + public static String getCompilerVersion() { return ControlLoop.COMPILER_VERSION; } @@ -112,6 +112,11 @@ public class ControlLoop { this.pnf = pnf; } + /** + * Constructor. + * + * @param controlLoop copy object + */ public ControlLoop(ControlLoop controlLoop) { this.controlLoopName = controlLoop.controlLoopName; this.services = new LinkedList<>(); diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java index e0c5839b1..161fe1def 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,23 +60,30 @@ public class ControlLoopPolicy { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } ControlLoopPolicy other = (ControlLoopPolicy) obj; if (controlLoop == null) { - if (other.controlLoop != null) + if (other.controlLoop != null) { return false; - } else if (!controlLoop.equals(other.controlLoop)) + } + } else if (!controlLoop.equals(other.controlLoop)) { return false; + } if (policies == null) { - if (other.policies != null) + if (other.policies != null) { return false; - } else if (!policies.equals(other.policies)) + } + } else if (!policies.equals(other.policies)) { return false; + } return true; } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java index b9fdc2e6d..473b102e7 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java @@ -58,6 +58,12 @@ public enum FinalResult { this.result = result; } + /** + * Converts to a result object. + * + * @param result input string + * @return result object + */ public static FinalResult toResult(String result) { if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { return FINAL_SUCCESS; @@ -83,6 +89,13 @@ public enum FinalResult { return null; } + /** + * Check if the result really is a result. + * + * @param result string + * @param finalResult result object + * @return true if a result + */ public static boolean isResult(String result, FinalResult finalResult) { FinalResult toResult = FinalResult.toResult(result); if (toResult == null) { diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java index 4d0f03a06..594c42023 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,6 @@ import java.io.Serializable; public class OperationsAccumulateParams implements Serializable { - /** - * - */ private static final long serialVersionUID = -3597358159130168247L; private String period; @@ -75,25 +72,33 @@ public class OperationsAccumulateParams implements Serializable { result = prime * result + ((limit == null) ? 0 : limit.hashCode()); return result; } + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } OperationsAccumulateParams other = (OperationsAccumulateParams) obj; if (period == null) { - if (other.period != null) + if (other.period != null) { return false; - } else if (!period.equals(other.period)) + } + } else if (!period.equals(other.period)) { return false; + } if (limit == null) { - if (other.limit != null) + if (other.limit != null) { return false; - } else if (!limit.equals(other.limit)) + } + } else if (!limit.equals(other.limit)) { return false; + } return true; } 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 4e0a0c99b..8585b674b 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 @@ -180,6 +180,15 @@ public class Policy { this.id = id; } + /** + * Constructor. + * + * @param name name + * @param actor actor + * @param recipe recipe + * @param payload payload + * @param target target + */ public Policy(String name, String actor, String recipe, Map payload, Target target) { this.name = name; this.actor = actor; @@ -190,6 +199,17 @@ public class Policy { } } + /** + * Constructor. + * + * @param name name + * @param actor actor + * @param recipe recipe + * @param payload payload + * @param target target + * @param retries retries + * @param timeout timeout + */ public Policy(String name, String actor, String recipe, Map payload, Target target, Integer retries, Integer timeout) { this(name, actor, recipe, payload, target); @@ -197,6 +217,19 @@ public class Policy { this.timeout = timeout; } + /** + * Constructor. + * + * @param id id + * @param name name + * @param description description + * @param actor actor + * @param payload payload + * @param target target + * @param recipe recipe + * @param retries retries + * @param timeout timeout + */ public Policy(String id, String name, String description, String actor, Map payload, Target target, String recipe, Integer retries, Integer timeout) { this(name, actor, recipe, payload, target, retries, timeout); @@ -204,6 +237,11 @@ public class Policy { this.description = description; } + /** + * Constructor. + * + * @param policy copy object + */ public Policy(Policy policy) { this.id = policy.id; this.name = policy.name; diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java index 574e14225..d9e1557d4 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,6 +58,12 @@ public enum PolicyResult { return this.result; } + /** + * Convert to a result. + * + * @param result result string + * @return Result object + */ public static PolicyResult toResult(String result) { if (result.equalsIgnoreCase(SUCCESS.toString())) { return SUCCESS; diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java index bc5b934b2..61d1ae285 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,9 @@ import java.io.Serializable; public class Target implements Serializable { - /** - * - */ private static final long serialVersionUID = 2180988443264988319L; - private String resourceID; + private String resourceId; private TargetType type; public Target() { @@ -37,11 +34,11 @@ public class Target implements Serializable { } public String getResourceID() { - return resourceID; + return resourceId; } - public void setResourceID(String resourceID) { - this.resourceID = resourceID; + public void setResourceID(String resourceId) { + this.resourceId = resourceId; } public TargetType getType() { @@ -56,23 +53,23 @@ public class Target implements Serializable { this.type = type; } - public Target(String resourceID) { - this.resourceID = resourceID; + public Target(String resourceId) { + this.resourceId = resourceId; } - public Target(TargetType type, String resourceID) { + public Target(TargetType type, String resourceId) { this.type = type; - this.resourceID = resourceID; + this.resourceId = resourceId; } public Target(Target target) { this.type = target.type; - this.resourceID = target.resourceID; + this.resourceId = target.resourceId; } @Override public String toString() { - return "Target [type=" + type + ", resourceID=" + resourceID + "]"; + return "Target [type=" + type + ", resourceId=" + resourceId + "]"; } @Override @@ -80,28 +77,36 @@ public class Target implements Serializable { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((resourceID == null) ? 0 : resourceID.hashCode()); + result = prime * result + ((resourceId == null) ? 0 : resourceId.hashCode()); return result; } + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Target other = (Target) obj; if (type == null) { - if (other.type != null) + if (other.type != null) { return false; - } else if (!type.equals(other.type)) + } + } else if (!type.equals(other.type)) { return false; - if (resourceID == null) { - if (other.resourceID != null) + } + if (resourceId == null) { + if (other.resourceId != null) { return false; - } else if (!resourceID.equals(other.resourceID)) + } + } else if (!resourceId.equals(other.resourceId)) { return false; + } return true; } } 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 4e034cb0e..9d00793b9 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,68 +35,79 @@ import org.onap.policy.sdc.Service; public interface ControlLoopPolicyBuilder { /** - * Adds one or more services to the ControlLoop + * Adds one or more services to the ControlLoop. * - * - * @param service - * @return - * @throws BuilderException + * @param services service to add + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException; /** - * @param services - * @return - * @throws BuilderException + * Remove service. + * + * @param services to remove + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException; /** - * @return - * @throws BuilderException + * Remove all the services. + * + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder removeAllServices() throws BuilderException; /** - * Adds one or more resources to the ControlLoop - * + * Adds one or more resources to the ControlLoop. * - * @param resource - * @return - * @throws BuilderException + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException; /** - * @param resources - * @return - * @throws BuilderException + * Remove the resources. + * + * @param resources resources to be removed + * @return object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException; /** - * @return - * @throws BuilderException + * Remove all resources. + * + * @return object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder removeAllResources() throws BuilderException; /** - * @param pnf - * @return - * @throws BuilderException + * Set the PNF. + * + * @param pnf input pnf + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder setPNF(Pnf pnf) throws BuilderException; /** - * @return - * @throws BuilderException + * Remove PNF. + * + * @return the object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder removePNF() throws BuilderException; /** - * @param abatement - * @return - * @throws BuilderException + * Set the abatement. + * + * @param abatement whether abatement is possible + * @return object + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException; @@ -105,9 +116,9 @@ public interface ControlLoopPolicyBuilder { * Sets the overall timeout value for the Control Loop. If any operational policies have retries * and timeouts, then this overall timeout value should exceed all those values. * - * @param timeout - * @return - * @throws BuilderException + * @param timeout timeout value + * @return control loop policy builder + * @throws BuilderException builder exception */ public ControlLoopPolicyBuilder setTimeout(Integer timeout) throws BuilderException; @@ -124,38 +135,40 @@ public interface ControlLoopPolicyBuilder { * Platform. * * - * @param name - * @param description - * @param actor - * @param target - * @param recipe - * @param retries - * @param timeout - * @return Policy - * @throws BuilderException + * @param name name + * @param description description + * @param actor actor + * @param target target + * @param recipe recipe + * @param retries retries + * @param timeout timeout + * @return Policy object + * @throws BuilderException builder exception */ public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, Map payload, Integer retries, Integer timeout) throws BuilderException; /** - * * Changes the trigger policy to point to another existing Policy. * - * - * @param id - * @return ControlLoop - * @throws BuilderException + * @param id the id + * @return ControlLoop object + * @throws BuilderException build exception */ public ControlLoop setTriggerPolicy(String id) throws BuilderException; /** - * @return + * Is an open loop. + * + * @return true or false */ public boolean isOpenLoop(); /** - * @return - * @throws BuilderException + * Get the trigger policy. + * + * @return the policy object + * @throws BuilderException if there is a builder exception */ public Policy getTriggerPolicy() throws BuilderException; @@ -170,35 +183,33 @@ public interface ControlLoopPolicyBuilder { /** * Creates a policy that is chained to the result of another Policy. * - * - * @param name - * @param description - * @param actor - * @param target - * @param recipe - * @param retries - * @param timeout - * @param policyID - * @param results - * @return - * @throws BuilderException + * @param name name + * @param description description + * @param actor actor + * @param target target + * @param recipe recipe + * @param retries retries + * @param timeout timeout + * @param policyId id + * @param results results + * @return Policy that was set + * @throws BuilderException builder exception */ public Policy setPolicyForPolicyResult(String name, String description, String actor, Target target, String recipe, - Map payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) + Map payload, Integer retries, Integer timeout, String policyId, PolicyResult... results) throws BuilderException; /** * Sets the policy result(s) to an existing Operational Policy. * - * - * @param policyResultID - * @param policyID - * @param results - * @return - * @throws BuilderException + * @param policyResultId result ID + * @param policyId id + * @param results results + * @return Policy that was set + * @throws BuilderException builder exception */ - public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) + public Policy setPolicyForPolicyResult(String policyResultId, String policyId, PolicyResult... results) throws BuilderException; /** @@ -207,17 +218,16 @@ public interface ControlLoopPolicyBuilder { * their result reset to the appropriate default FINAL_* result. * * - * @param policyID - * @return - * @throws BuilderException + * @param policyID id for the policy + * @return true if removed else false + * @throws BuilderException builder exception */ public boolean removePolicy(String policyID) throws BuilderException; /** * Resets a policy's results to defualt FINAL_* codes. * - * - * @return Policy + * @return Policy object * @throws BuilderException - Policy does not exist */ public Policy resetPolicyResults(String policyID) throws BuilderException; @@ -230,7 +240,7 @@ public interface ControlLoopPolicyBuilder { public ControlLoopPolicyBuilder removeAllPolicies(); /** - * Adds an operationsAccumulateParams to an existing operational policy + * Adds an operationsAccumulateParams to an existing operational policy. * * @return Policy * @throws BuilderException - Policy does not exist @@ -280,7 +290,7 @@ public interface ControlLoopPolicyBuilder { * @param services - Zero or more services associated with this resource. Should come from * ASDC, but if not available use serviceName to distinguish. * @return ControlLoopPolicyBuilder object - * @throws BuilderException + * @throws BuilderException builder exception */ public static ControlLoopPolicyBuilder buildControlLoop(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { @@ -288,12 +298,14 @@ public interface ControlLoopPolicyBuilder { } /** - * @param controlLoopName - * @param timeout - * @param service - * @param resources - * @return - * @throws BuilderException + * Build the control loop. + * + * @param controlLoopName control loop id + * @param timeout timeout + * @param service service + * @param resources resources + * @return builder object + * @throws BuilderException builder exception */ public static ControlLoopPolicyBuilder buildControlLoop(String controlLoopName, Integer timeout, Service service, Resource... resources) throws BuilderException { @@ -301,12 +313,14 @@ public interface ControlLoopPolicyBuilder { } /** + * Build control loop. + * * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. * @param timeout - Overall timeout for the Closed Loop to execute. * @param pnf - Physical Network Function. Should come from AIC, but if not available use * well-known name to distinguish. Eg. eNodeB * @return ControlLoopPolicyBuilder object - * @throws BuilderException + * @throws BuilderException builder exception */ public static ControlLoopPolicyBuilder buildControlLoop(String controlLoopName, Integer timeout, Pnf pnf) throws BuilderException { diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java index ffd63d691..bfe6fc080 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,8 @@ package org.onap.policy.controlloop.policy.builder; public enum MessageLevel { - INFO, - WARNING, - ERROR, - EXCEPTION - ; - + INFO, + WARNING, + ERROR, + EXCEPTION; } 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 adbf12748..ba434356a 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,6 +54,12 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { private static Logger logger = LoggerFactory.getLogger(ControlLoopPolicyBuilderImpl.class.getName()); private ControlLoopPolicy controlLoopPolicy; + /** + * Constructor. + * + * @param controlLoopName control loop id + * @param timeout timeout value + */ public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) { controlLoopPolicy = new ControlLoopPolicy(); ControlLoop controlLoop = new ControlLoop(); @@ -62,6 +68,15 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { controlLoopPolicy.setControlLoop(controlLoop); } + /** + * Constructor. + * + * @param controlLoopName control loop id + * @param timeout timeout value + * @param resource resource + * @param services services + * @throws BuilderException builder exception + */ public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { this(controlLoopName, timeout); @@ -74,6 +89,15 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { this.setPNF(pnf); } + /** + * Constructor. + * + * @param controlLoopName control loop id + * @param timeout timeout + * @param service service + * @param resources resources + * @throws BuilderException builder exception + */ public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources) throws BuilderException { this(controlLoopName, timeout); @@ -137,7 +161,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { if (resource == null) { throw new BuilderException("Resource must not be null"); } - if (resource.getResourceUUID() == null && Strings.isNullOrEmpty(resource.getResourceName())) { + if (resource.getResourceUuid() == null && Strings.isNullOrEmpty(resource.getResourceName())) { throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); } if (controlLoopPolicy.getControlLoop().getResources() == null) { @@ -191,16 +215,30 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { return new Policy(trigger); } + @Override + public ControlLoop setTriggerPolicy(String id) throws BuilderException { + if (id == null) { + throw new BuilderException("Id must not be null"); + } + Policy trigger = this.findPolicy(id); + if (trigger == null) { + throw new BuilderException(UNKNOWN_POLICY + id); + } else { + this.controlLoopPolicy.getControlLoop().setTrigger_policy(id); + } + return new ControlLoop(this.controlLoopPolicy.getControlLoop()); + } + @Override public Policy setPolicyForPolicyResult(String name, String description, String actor, Target target, String recipe, - Map payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) + Map payload, Integer retries, Integer timeout, String policyId, PolicyResult... results) throws BuilderException { // // Find the existing policy // - Policy existingPolicy = this.findPolicy(policyID); + Policy existingPolicy = this.findPolicy(policyId); if (existingPolicy == null) { - throw new BuilderException(UNKNOWN_POLICY + policyID); + throw new BuilderException(UNKNOWN_POLICY + policyId); } // // Create the new Policy @@ -244,6 +282,49 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { return new Policy(newPolicy); } + @Override + public Policy setPolicyForPolicyResult(String policyResultId, String policyId, PolicyResult... results) + throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyId); + if (existingPolicy == null) { + throw new BuilderException(policyId + " does not exist"); + } + if (this.findPolicy(policyResultId) == null) { + throw new BuilderException("Operational policy " + policyResultId + " does not exist"); + } + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.setFailure(policyResultId); + break; + case FAILURE_EXCEPTION: + existingPolicy.setFailure_exception(policyResultId); + break; + case FAILURE_RETRIES: + existingPolicy.setFailure_retries(policyResultId); + break; + case FAILURE_TIMEOUT: + existingPolicy.setFailure_timeout(policyResultId); + break; + case FAILURE_GUARD: + existingPolicy.setFailure_guard(policyResultId); + break; + case SUCCESS: + existingPolicy.setSuccess(policyResultId); + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + return new Policy(this.findPolicy(policyResultId)); + } + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { private ResultsImpl results = new ResultsImpl(); @@ -318,7 +399,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { if (resource == null) { throw new BuilderException("Resource must not be null"); } - if (resource.getResourceUUID() == null && Strings.isNullOrEmpty(resource.getResourceName())) { + if (resource.getResourceUuid() == null && Strings.isNullOrEmpty(resource.getResourceName())) { throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); } boolean removed = controlLoopPolicy.getControlLoop().getResources().remove(resource); @@ -344,20 +425,6 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { return Integer.valueOf(sum); } - @Override - public ControlLoop setTriggerPolicy(String id) throws BuilderException { - if (id == null) { - throw new BuilderException("Id must not be null"); - } - Policy trigger = this.findPolicy(id); - if (trigger == null) { - throw new BuilderException(UNKNOWN_POLICY + id); - } else { - this.controlLoopPolicy.getControlLoop().setTrigger_policy(id); - } - return new ControlLoop(this.controlLoopPolicy.getControlLoop()); - } - @Override public boolean isOpenLoop() { return this.controlLoopPolicy.getControlLoop().getTrigger_policy() @@ -379,61 +446,18 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { } @Override - public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) - throws BuilderException { - // - // Find the existing policy - // - Policy existingPolicy = this.findPolicy(policyID); - if (existingPolicy == null) { - throw new BuilderException(policyID + " does not exist"); - } - if (this.findPolicy(policyResultID) == null) { - throw new BuilderException("Operational policy " + policyResultID + " does not exist"); - } - // - // Connect the results - // - for (PolicyResult result : results) { - switch (result) { - case FAILURE: - existingPolicy.setFailure(policyResultID); - break; - case FAILURE_EXCEPTION: - existingPolicy.setFailure_exception(policyResultID); - break; - case FAILURE_RETRIES: - existingPolicy.setFailure_retries(policyResultID); - break; - case FAILURE_TIMEOUT: - existingPolicy.setFailure_timeout(policyResultID); - break; - case FAILURE_GUARD: - existingPolicy.setFailure_guard(policyResultID); - break; - case SUCCESS: - existingPolicy.setSuccess(policyResultID); - break; - default: - throw new BuilderException("Invalid PolicyResult " + result); - } - } - return new Policy(this.findPolicy(policyResultID)); - } - - @Override - public boolean removePolicy(String policyID) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); + 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.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(policyID)) { + if (this.controlLoopPolicy.getControlLoop().getTrigger_policy().equals(policyId)) { this.controlLoopPolicy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); } else { - updateChainedPoliciesForPolicyRemoval(policyID); + updateChainedPoliciesForPolicyRemoval(policyId); } // // remove the policy @@ -443,7 +467,7 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { private void updateChainedPoliciesForPolicyRemoval(String idOfPolicyBeingRemoved) { for (Policy policy : this.controlLoopPolicy.getPolicies()) { - int index = this.controlLoopPolicy.getPolicies().indexOf(policy); + final int index = this.controlLoopPolicy.getPolicies().indexOf(policy); if (policy.getSuccess().equals(idOfPolicyBeingRemoved)) { policy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); } @@ -467,10 +491,10 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { } @Override - public Policy resetPolicyResults(String policyID) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); + 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 @@ -498,11 +522,11 @@ public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { } @Override - public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) + public Policy addOperationsAccumulateParams(String policyId, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); + 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/guard/Constraint.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java index e53f3e40f..6931de430 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 @@ -75,9 +75,15 @@ public class Constraint { this.blacklist = blacklist; } + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow time window + */ public Constraint(Integer freqLimitPerTarget, Map timeWindow) { this.freqLimitPerTarget = freqLimitPerTarget; - if(timeWindow!=null){ + if (timeWindow != null) { this.timeWindow = Collections.unmodifiableMap(timeWindow); } } @@ -86,12 +92,26 @@ public class Constraint { this.blacklist = new LinkedList<>(blacklist); } + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow time window + * @param blacklist blacklist + */ public Constraint(Integer freqLimitPerTarget, Map timeWindow, List blacklist) { this.freqLimitPerTarget = freqLimitPerTarget; this.timeWindow = Collections.unmodifiableMap(timeWindow); this.blacklist = new LinkedList<>(blacklist); } + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow time window + * @param activeTimeRange active time range + */ public Constraint(Integer freqLimitPerTarget, Map timeWindow, Map activeTimeRange) { this(freqLimitPerTarget, timeWindow); if (activeTimeRange != null) { @@ -99,17 +119,30 @@ public class Constraint { } } + /** + * Constructor. + * + * @param freqLimitPerTarget frequency limit + * @param timeWindow the time window + * @param activeTimeRange active time range + * @param blacklist incoming blacklist + */ public Constraint(Integer freqLimitPerTarget, Map timeWindow, Map activeTimeRange, List blacklist) { this(freqLimitPerTarget, timeWindow); if (activeTimeRange != null) { this.activeTimeRange = Collections.unmodifiableMap(activeTimeRange); } - if(blacklist != null){ + if (blacklist != null) { this.blacklist = new LinkedList<>(blacklist); } } + /** + * Constructor. + * + * @param constraint objec to copy + */ public Constraint(Constraint constraint) { this.freqLimitPerTarget = constraint.freqLimitPerTarget; this.timeWindow = constraint.timeWindow; @@ -143,23 +176,26 @@ public class Constraint { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Constraint other = (Constraint) obj; return equalsMayBeNull(freqLimitPerTarget, other.freqLimitPerTarget) - && equalsMayBeNull(timeWindow, other.timeWindow) - && equalsMayBeNull(activeTimeRange, other.activeTimeRange) - && equalsMayBeNull(blacklist, other.blacklist); + && equalsMayBeNull(timeWindow, other.timeWindow) + && equalsMayBeNull(activeTimeRange, other.activeTimeRange) + && equalsMayBeNull(blacklist, other.blacklist); } - private boolean equalsMayBeNull(final Object obj1, final Object obj2){ - if ( obj1 == null ) { + private boolean equalsMayBeNull(final Object obj1, final Object obj2) { + if (obj1 == null) { return obj2 == null; } - return obj1.equals(obj2); + return obj1.equals(obj2); } } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java index 6fb0ca9f0..66ac3e612 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,9 +48,9 @@ public class ControlLoopGuard { this.guards = guards; } - public ControlLoopGuard(ControlLoopGuard cLGuard) { + public ControlLoopGuard(ControlLoopGuard clGuard) { this.guard = new Guard(); - this.guards = new LinkedList<>(cLGuard.guards); + this.guards = new LinkedList<>(clGuard.guards); } @Override @@ -69,23 +69,30 @@ public class ControlLoopGuard { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } ControlLoopGuard other = (ControlLoopGuard) obj; if (guard == null) { - if (other.guard != null) + if (other.guard != null) { return false; - } else if (!guard.equals(other.guard)) + } + } else if (!guard.equals(other.guard)) { return false; + } if (guards == null) { - if (other.guards != null) + if (other.guards != null) { return false; - } else if (!guards.equals(other.guards)) + } + } else if (!guards.equals(other.guards)) { return false; + } return true; } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java index 291004611..dcce13597 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,6 +42,7 @@ public class Guard { public String toString() { return "Guard [version=" + version + "]"; } + @Override public int hashCode() { final int prime = 31; @@ -49,20 +50,26 @@ public class Guard { result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Guard other = (Guard) obj; if (version == null) { - if (other.version != null) + if (other.version != null) { return false; - } else if (!version.equals(other.version)) + } + } else if (!version.equals(other.version)) { return false; + } return true; } } 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 759a0533d..799c5fcd7 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 @@ -85,12 +85,27 @@ public class GuardPolicy { this.matchParameters = matchParameters; } + /** + * Constructor. + * + * @param id id + * @param name name + * @param description description + * @param matchParameters match parameters + */ public GuardPolicy(String id, String name, String description, MatchParameters matchParameters) { this(name, matchParameters); this.id = id; this.description = description; } + /** + * Constructor. + * + * @param name name + * @param matchParameters match parameters + * @param limitConstraints limit constraints + */ public GuardPolicy(String name, MatchParameters matchParameters, List limitConstraints) { this(name, matchParameters); if (limitConstraints != null) { @@ -110,6 +125,11 @@ public class GuardPolicy { this.id = id; } + /** + * Constructor. + * + * @param policy copy object + */ public GuardPolicy(GuardPolicy policy) { this.id = policy.id; this.name = policy.name; 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 445e00f38..1bf10734d 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,6 +71,13 @@ public class MatchParameters { this.recipe = recipe; } + /** + * Constructor. + * + * @param actor actor + * @param recipe recipe + * @param targets targets + */ public MatchParameters(String actor, String recipe, List targets) { this(actor, recipe); if (targets != null) { @@ -83,6 +90,11 @@ public class MatchParameters { this.controlLoopName = controlLoopName; } + /** + * Constructor. + * + * @param matchParameters match parameters + */ public MatchParameters(MatchParameters matchParameters) { this.controlLoopName = matchParameters.controlLoopName; @@ -112,24 +124,27 @@ public class MatchParameters { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } MatchParameters other = (MatchParameters) obj; return equalsMayBeNull(actor, other.actor) - && equalsMayBeNull(controlLoopName, other.controlLoopName) - && equalsMayBeNull(recipe, other.recipe) - && equalsMayBeNull(targets, other.targets); + && equalsMayBeNull(controlLoopName, other.controlLoopName) + && equalsMayBeNull(recipe, other.recipe) + && equalsMayBeNull(targets, other.targets); } - private boolean equalsMayBeNull(final Object obj1, final Object obj2){ - if ( obj1 == null ) { + private boolean equalsMayBeNull(final Object obj1, final Object obj2) { + if (obj1 == null) { return obj2 == null; } - return obj1.equals(obj2); + 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 77651dcbf..850b487a7 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 @@ -31,64 +31,57 @@ import org.onap.policy.controlloop.policy.guard.builder.impl.ControlLoopGuardBui public interface ControlLoopGuardBuilder { /** - * Adds one or more guard policies to the Control Loop Guard + * Adds one or more guard policies to the Control Loop Guard. * - * - * @param policies - * @return - * @throws BuilderException + * @param policies policies to add + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; /** - * Removes one or more guard policies from the Control Loop Guard - * + * Removes one or more guard policies from the Control Loop Guard. * - * @param policies - * @return - * @throws BuilderException + * @param policies policies to add + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; /** - * Removes all guard policies from the Control Loop Guard - * + * Removes all guard policies from the Control Loop Guard. * - * @param - * @return - * @throws BuilderException + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; /** - * Adds one or more time limit constraints to the guard policy - * + * Adds one or more time limit constraints to the guard policy. * * @param id (guard policy id) - * @param constraints - * @return - * @throws BuilderException + * @param constraints the constraints to add + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException; /** - * Removes one or more time limit constraints from the guard policy - * + * Removes one or more time limit constraints from the guard policy. * * @param id (guard policy id) - * @param constraints - * @return - * @throws BuilderException + * @param constraints constraints to remove + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; /** - * Removes all time limit constraints from the guard policy - * + * Removes all time limit constraints from the guard policy. * * @param id (guard policy id) - * @return - * @throws BuilderException + * @return builder object + * @throws BuilderException builder exception */ public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException; 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 b4d251e7f..f995ba4c6 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 @@ -46,11 +46,11 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { 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; + private ControlLoopGuard clGuard; public ControlLoopGuardBuilderImpl(Guard guard) { - cLGuard = new ControlLoopGuard(); - cLGuard.setGuard(guard); + clGuard = new ControlLoopGuard(); + clGuard.setGuard(guard); } @Override @@ -62,10 +62,10 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { if (!policy.isValid()) { throw new BuilderException("Invalid guard policy - some required fields are missing"); } - if (cLGuard.getGuards() == null) { - cLGuard.setGuards(new LinkedList<>()); + if (clGuard.getGuards() == null) { + clGuard.setGuards(new LinkedList<>()); } - cLGuard.getGuards().add(policy); + clGuard.getGuards().add(policy); } return this; } @@ -75,14 +75,14 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { if (policies == null) { throw new BuilderException("GuardPolicy must not be null"); } - if (cLGuard.getGuards() == null) { + if (clGuard.getGuards() == null) { throw new BuilderException("No existing guard policies to remove"); } for (GuardPolicy policy : policies) { if (!policy.isValid()) { throw new BuilderException("Invalid guard policy - some required fields are missing"); } - boolean removed = cLGuard.getGuards().remove(policy); + boolean removed = clGuard.getGuards().remove(policy); if (!removed) { throw new BuilderException("Unknown guard policy: " + policy.getName()); } @@ -92,7 +92,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { @Override public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException { - cLGuard.getGuards().clear(); + clGuard.getGuards().clear(); return this; } @@ -112,7 +112,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { private boolean addLimitConstraints(String id, Constraint... constraints) throws BuilderException { boolean exist = false; - for (GuardPolicy policy: cLGuard.getGuards()) { + for (GuardPolicy policy: clGuard.getGuards()) { // // We could have only one guard policy matching the id // @@ -149,7 +149,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { private boolean removeConstraints(String id, Constraint... constraints) throws BuilderException { boolean exist = false; - for (GuardPolicy policy: cLGuard.getGuards()) { + for (GuardPolicy policy: clGuard.getGuards()) { // // We could have only one guard policy matching the id // @@ -172,14 +172,14 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { @Override public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException { - if (cLGuard.getGuards() == null || cLGuard.getGuards().isEmpty()) { + if (clGuard.getGuards() == null || clGuard.getGuards().isEmpty()) { throw new BuilderException("No guard policies exist"); } if (id == null) { throw new BuilderException(THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL); } boolean exist = false; - for (GuardPolicy policy: cLGuard.getGuards()) { + for (GuardPolicy policy: clGuard.getGuards()) { if (policy.getId().equals(id)) { exist = true; policy.getLimit_constraints().clear(); @@ -211,7 +211,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { @Override public ControlLoopGuard getControlLoopGuard() { - return new ControlLoopGuard(this.cLGuard); + return new ControlLoopGuard(this.clGuard); } @@ -224,7 +224,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { options.setDefaultFlowStyle(FlowStyle.BLOCK); options.setPrettyFlow(true); Yaml yaml = new Yaml(options); - String dumpedYaml = yaml.dump(cLGuard); + String dumpedYaml = yaml.dump(clGuard); // // This is our callback class for our compiler // @@ -233,7 +233,7 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { // Compile it // try { - ControlLoopGuardCompiler.compile(cLGuard, callback); + ControlLoopGuardCompiler.compile(clGuard, callback); } catch (CompilerException e) { logger.error(e.getMessage() + e); callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); 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 b69343862..56b695b96 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 @@ -20,7 +20,9 @@ package org.onap.policy.controlloop.compiler; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -166,6 +168,14 @@ public class ControlLoopCompilerTest { return test(testFile, null); } + /** + * Does the actual test. + * + * @param testFile test file + * @param controlLoopCompilerCallback callback method + * @return the policy object + * @throws Exception exception + */ public ControlLoopPolicy test(String testFile, ControlLoopCompilerCallback controlLoopCompilerCallback) throws Exception { try (InputStream is = new FileInputStream(new File(testFile))) { diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java index 54c4eccff..28e59d9ad 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java @@ -88,6 +88,12 @@ public class ControlLoopGuardCompilerTest { } } + /** + * Does the actual test. + * + * @param testFile input test file + * @throws Exception exception thrown + */ public void test(String testFile) throws Exception { try (InputStream is = new FileInputStream(new File(testFile))) { ControlLoopGuardCompiler.compile(is, null); 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 3133273f9..90ce96b62 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-yaml unit test * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,30 +69,30 @@ public class ControlLoopPolicyBuilderTest { // // Test add services // - Service vSCP = new Service("vSCP"); - Service vUSP = new Service("vUSP"); - Service vTrinity = new Service("Trinity"); - builder = builder.addService(vSCP, vUSP, vTrinity); + Service scp = new Service("vSCP"); + Service usp = new Service("vUSP"); + Service trinity = new Service("Trinity"); + builder = builder.addService(scp, usp, trinity); assertTrue(builder.getControlLoop().getServices().size() == 3); // // Test remove services // - builder = builder.removeService(vSCP); + builder = builder.removeService(scp); assertTrue(builder.getControlLoop().getServices().size() == 2); builder = builder.removeAllServices(); assertTrue(builder.getControlLoop().getServices().size() == 0); // // Test add resources // - Resource vCTS = new Resource("vCTS", ResourceType.VF); - Resource vCOM = new Resource("vCTS", ResourceType.VF); - Resource vRAR = new Resource("vCTS", ResourceType.VF); - builder = builder.addResource(vCTS, vCOM, vRAR); + Resource cts = new Resource("vCTS", ResourceType.VF); + Resource com = new Resource("vCTS", ResourceType.VF); + Resource rar = new Resource("vCTS", ResourceType.VF); + builder = builder.addResource(cts, com, rar); assertTrue(builder.getControlLoop().getResources().size() == 3); // // Test remove resources // - builder = builder.removeResource(vCTS); + builder = builder.removeResource(cts); assertTrue(builder.getControlLoop().getResources().size() == 2); builder = builder.removeAllResources(); assertTrue(builder.getControlLoop().getResources().size() == 0); @@ -120,12 +120,12 @@ public class ControlLoopPolicyBuilderTest { } @Test - public void testAddServiceWithUUID() throws BuilderException { + 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); + Service serviceWithUuid = new Service(uuid); + builder.addService(serviceWithUuid); assertTrue(builder.getControlLoop().getServices().size() == 1); } @@ -149,15 +149,15 @@ public class ControlLoopPolicyBuilderTest { } @Test - public void testAddAndRemoveResourceWithUUID() throws BuilderException { + 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); + Resource resourceWithUuid = new Resource(uuid); + builder.addResource(resourceWithUuid); assertTrue(builder.getControlLoop().getResources().size() == 1); - builder.removeResource(resourceWithUUID); + builder.removeResource(resourceWithUuid); assertTrue(builder.getControlLoop().getResources().size() == 0); } @@ -207,11 +207,11 @@ public class ControlLoopPolicyBuilderTest { @Test public void testControlLoopWithInitialResourceAndServices() { try { - Resource vCTS = new Resource("vCTS", ResourceType.VF); - Service vSCP = new Service("vSCP"); - Service vUSP = new Service("vUSP"); + Resource cts = new Resource("vCTS", ResourceType.VF); + Service scp = new Service("vSCP"); + Service usp = new Service("vUSP"); ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory - .buildControlLoop(UUID.randomUUID().toString(), 2400, vCTS, vSCP, vUSP); + .buildControlLoop(UUID.randomUUID().toString(), 2400, cts, scp, usp); assertTrue(builder.getControlLoop().getResources().size() == 1); assertTrue(builder.getControlLoop().getServices().size() == 2); } catch (BuilderException e) { @@ -222,11 +222,11 @@ public class ControlLoopPolicyBuilderTest { @Test public void testControlLoopWithInitialResourcesAndService() { try { - Resource vCTS = new Resource("vCTS", ResourceType.VF); - Resource vCOM = new Resource("vCTS", ResourceType.VF); - Service vSCP = new Service("vSCP"); + Resource cts = new Resource("vCTS", ResourceType.VF); + Resource com = new Resource("vCTS", ResourceType.VF); + Service scp = new Service("vSCP"); ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory - .buildControlLoop(UUID.randomUUID().toString(), 2400, vSCP, vCTS, vCOM); + .buildControlLoop(UUID.randomUUID().toString(), 2400, scp, cts, com); assertTrue(builder.getControlLoop().getServices().size() == 1); assertTrue(builder.getControlLoop().getResources().size() == 2); } catch (BuilderException e) { @@ -459,7 +459,7 @@ public class ControlLoopPolicyBuilderTest { // // Create another policy and chain it to the results of trigger policy // - Policy onRestartFailurePolicy2 = + final Policy onRestartFailurePolicy2 = builder.setPolicyForPolicyResult("Rebuild VM", "If the restart fails, rebuild it.", "APPC", new Target(TargetType.VM), "Rebuild", null, 2, 600, triggerPolicy.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT); @@ -475,25 +475,25 @@ public class ControlLoopPolicyBuilderTest { // // Test set the policy results to an existing operational policy // - onRestartFailurePolicy2 = + Policy onRestartFailurePolicy3 = builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT); - assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId())); - assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId())); - assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy3.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy3.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy3.getId())); // // Test set the policy result for success to an existing operational policy // - onRestartFailurePolicy2 = + Policy onRestartFailurePolicy4 = 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())); + assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy4.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy4.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy4.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy4.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy4.getId())); + assertTrue(builder.getTriggerPolicy().getSuccess().equals(onRestartFailurePolicy4.getId())); // // Test remove all existing operational policies @@ -588,30 +588,30 @@ public class ControlLoopPolicyBuilderTest { // // Set the first invalid trigger policy // - Policy policy1 = builder.setTriggerPolicy("Restart the VM", + final Policy policy1 = builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", null, null, "Instantiate", null, 2, 300); Results results = builder.buildSpecification(); // // Check that ERRORs are in results for invalid policy arguments // - boolean invalid_actor = false; - boolean invalid_recipe = false; - boolean invalid_target = false; + boolean invalidActor = false; + boolean invalidRecipe = false; + boolean invalidTarget = false; for (Message m : results.getMessages()) { if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) { - invalid_actor = true; + invalidActor = true; } if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) { - invalid_recipe = true; + invalidRecipe = true; } if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) { - invalid_target = true; + invalidTarget = true; } } // - assertTrue(invalid_actor); - assertTrue(invalid_recipe); - assertTrue(invalid_target); + assertTrue(invalidActor); + assertTrue(invalidRecipe); + assertTrue(invalidTarget); // // Remove the invalid policy // @@ -622,12 +622,12 @@ public class ControlLoopPolicyBuilderTest { // // Set a valid trigger policy // - policy1 = builder.setTriggerPolicy("Rebuild VM", "If the restart fails, rebuild it.", "APPC", + Policy policy1a = builder.setTriggerPolicy("Rebuild VM", "If the restart fails, rebuild it.", "APPC", new Target(TargetType.VM), "Rebuild", null, 1, 600); // // Set a second valid trigger policy // - Policy policy2 = + final Policy policy2 = builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC", new Target(TargetType.VM), "Restart", null, 2, 300); // @@ -636,7 +636,7 @@ public class ControlLoopPolicyBuilderTest { results = builder.buildSpecification(); boolean unreachable = false; for (Message m : results.getMessages()) { - if (m.getMessage().equals("Policy " + policy1.getId() + " is not reachable.") + if (m.getMessage().equals("Policy " + policy1a.getId() + " is not reachable.") && m.getLevel() == MessageLevel.WARNING) { unreachable = true; break; @@ -644,21 +644,21 @@ public class ControlLoopPolicyBuilderTest { } assertTrue(unreachable); // - // Set policy1 for the failure results of policy2 + // Set policy1a for the failure results of policy2 // - policy1 = builder.setPolicyForPolicyResult(policy1.getId(), policy2.getId(), PolicyResult.FAILURE, + policy1a = builder.setPolicyForPolicyResult(policy1a.getId(), policy2.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT); results = builder.buildSpecification(); - boolean invalid_timeout = false; + boolean invalidTimeout = false; for (Message m : results.getMessages()) { if (m.getMessage() .equals("controlLoop overall timeout is less than the sum of operational policy timeouts.") && m.getLevel() == MessageLevel.ERROR) { - invalid_timeout = true; + invalidTimeout = true; break; } } - assertTrue(invalid_timeout); + assertTrue(invalidTimeout); // // Remove policy2 (revert controlLoop back to open loop) // @@ -684,7 +684,7 @@ public class ControlLoopPolicyBuilderTest { @Test - public void test() { + public void test1() { this.test("src/test/resources/v1.0.0/policy_Test.yaml"); } @@ -707,6 +707,11 @@ public class ControlLoopPolicyBuilderTest { } } + /** + * Does the actual test. + * + * @param testFile input file + */ 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/ControlLoopPolicyTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java index 6212b17f4..fcfe1dcfe 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java @@ -20,7 +20,9 @@ package org.onap.policy.controlloop.policy; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -41,7 +43,7 @@ public class ControlLoopPolicyTest { private static final Logger logger = LoggerFactory.getLogger(ControlLoopPolicyTest.class); @Test - public void test() { + public void test1() { this.test("src/test/resources/v1.0.0/policy_Test.yaml"); } @@ -56,26 +58,31 @@ public class ControlLoopPolicyTest { } @Test - public void testvDNS() { + public void testvdns() { this.test("src/test/resources/v2.0.0/policy_ONAP_demo_vDNS.yaml"); } @Test public void testvFirewall() { // Chenfei to fix this. - // this.test("src/test/resources/v2.0.0/policy_ONAP_demo_vFirewall.yaml"); + // this.test("src/test/resources/v2.0.0/policy_ONAP_demo_vFirewall.yaml"); } @Test - public void testvCPE() { + public void testvcpe() { this.test("src/test/resources/v2.0.0/policy_ONAP_UseCase_vCPE.yaml"); } @Test - public void testVOLTE() { + public void testvolte() { this.test("src/test/resources/v2.0.0/policy_ONAP_UseCase_VOLTE.yaml"); } + /** + * Does the actual test. + * + * @param testFile input file + */ 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/ControlLoopTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java index cc5a903ad..daab1a26b 100644 --- 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 @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,18 +109,18 @@ public class ControlLoopTest { 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); + Service controlLoop2Service1 = new Service("service1"); + Service controlLoop2Service2 = new Service("service2"); + List controlLoop2Services = new ArrayList<>(); + controlLoop2Services.add(controlLoop2Service1); + controlLoop2Services.add(controlLoop2Service2); + controlLoop2.setServices(controlLoop2Services); + Resource controlLoop2Resource1 = new Resource("resource1", ResourceType.VF); + Resource controlLoop2Resource2 = new Resource("resource2", ResourceType.VFC); + List controlLoop2Resources = new ArrayList<>(); + controlLoop2Resources.add(controlLoop2Resource1); + controlLoop2Resources.add(controlLoop2Resource2); + controlLoop2.setResources(controlLoop2Resources); controlLoop2.setPnf(pnf); controlLoop2.setTrigger_policy(triggerPolicy); controlLoop2.setTimeout(timeout); 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 index adf85af3a..9e68a7389 100644 --- 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 @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +19,10 @@ package org.onap.policy.controlloop.policy; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -78,8 +82,8 @@ public class OperationsAccumulateParamsTest { @Test public void testEqualsAndHashCode() { - String period = "15m"; - Integer limit = 10; + final String period = "15m"; + final Integer limit = 10; OperationsAccumulateParams operationsAccumulateParams1 = new OperationsAccumulateParams(); OperationsAccumulateParams operationsAccumulateParams2 = new OperationsAccumulateParams(); 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 index 14e46b6bf..2d497ac4b 100644 --- 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 @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +19,10 @@ package org.onap.policy.controlloop.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; @@ -62,7 +66,7 @@ public class ConstraintTest { activeTimeRange.put("timeWindowKey", "timeWindowValue"); Constraint constraint = new Constraint(); constraint.setActive_time_range(activeTimeRange);; - assertEquals(activeTimeRange, constraint.getActive_time_range()); + assertEquals(activeTimeRange, constraint.getActive_time_range()); } @Test @@ -71,7 +75,7 @@ public class ConstraintTest { blacklist.add("blacklist item"); Constraint constraint = new Constraint(); constraint.setBlacklist(blacklist); - assertEquals(blacklist, constraint.getBlacklist()); + assertEquals(blacklist, constraint.getBlacklist()); } @Test @@ -164,7 +168,7 @@ public class ConstraintTest { @Test public void testIsValid() { Integer freqLimitPerTarget = 10; - Map timeWindow = new HashMap<>(); + final Map timeWindow = new HashMap<>(); Constraint constraint = new Constraint(); assertTrue(constraint.isValid()); @@ -197,8 +201,8 @@ public class ConstraintTest { @Test public void testEquals() { Integer freqLimitPerTarget = 10; - Map timeWindow = new HashMap<>(); - Map activeTimeRange = new HashMap<>(); + final Map timeWindow = new HashMap<>(); + final Map activeTimeRange = new HashMap<>(); List blacklist = new ArrayList<>(); blacklist.add("blacklist item"); diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java index 45e9c4202..782f6d5e8 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java @@ -59,15 +59,15 @@ public class ControlLoopGuardBuilderTest { // Assert there is no guard policies yet // Results results = builder.buildSpecification(); - boolean no_guard_policies = false; + boolean noGuardPolicies = false; for (Message m : results.getMessages()) { if (m.getMessage().equals("ControlLoop Guard should have at least one guard policies") && m.getLevel() == MessageLevel.ERROR) { - no_guard_policies = true; + noGuardPolicies = true; break; } } - assertTrue(no_guard_policies); + assertTrue(noGuardPolicies); // // Add a guard policy without limit constraint // @@ -83,28 +83,28 @@ public class ControlLoopGuardBuilderTest { // Assert there is no limit constraint associated with the only guard policy // results = builder.buildSpecification(); - boolean no_constraint = false; + boolean noConstraint = false; for (Message m : results.getMessages()) { if (m.getMessage().equals("Guard policy guardpolicy1 does not have any limit constraint") && m.getLevel() == MessageLevel.ERROR) { - no_constraint = true; + noConstraint = true; break; } } - assertTrue(no_constraint); + assertTrue(noConstraint); // // Add a constraint to policy1 // - Map active_time_range = new HashMap(); - active_time_range.put("start", "00:00:00-05:00"); - active_time_range.put("end", "23:59:59-05:00"); + Map activeTimeRange = new HashMap(); + activeTimeRange.put("start", "00:00:00-05:00"); + activeTimeRange.put("end", "23:59:59-05:00"); List blacklist = new LinkedList(); blacklist.add("eNodeB_common_id1"); blacklist.add("eNodeB_common_id2"); - Map time_window = new HashMap(); - time_window.put("value", "10"); - time_window.put("units", "minute"); - Constraint cons = new Constraint(5, time_window, active_time_range, blacklist); + Map timeWindow = new HashMap(); + timeWindow.put("value", "10"); + timeWindow.put("units", "minute"); + Constraint cons = new Constraint(5, timeWindow, activeTimeRange, blacklist); builder = builder.addLimitConstraint(policy1.getId(), cons); // // Add a duplicate constraint to policy1 @@ -114,15 +114,15 @@ public class ControlLoopGuardBuilderTest { // Assert there are duplicate constraints associated with the only guard policy // results = builder.buildSpecification(); - boolean duplicate_constraint = false; + boolean duplicateConstraint = false; for (Message m : results.getMessages()) { if (m.getMessage().equals("Guard policy guardpolicy1 has duplicate limit constraints") && m.getLevel() == MessageLevel.WARNING) { - duplicate_constraint = true; + duplicateConstraint = true; break; } } - assertTrue(duplicate_constraint); + assertTrue(duplicateConstraint); // // Remove the duplicate constraint // @@ -136,15 +136,15 @@ public class ControlLoopGuardBuilderTest { // Assert there are duplicate guard policies // results = builder.buildSpecification(); - boolean duplicate_guard_policy = false; + boolean duplicateGuardPolicy = false; for (Message m : results.getMessages()) { if (m.getMessage().equals("There are duplicate guard policies") && m.getLevel() == MessageLevel.WARNING) { - duplicate_guard_policy = true; + duplicateGuardPolicy = true; break; } } - assertTrue(duplicate_guard_policy); + assertTrue(duplicateGuardPolicy); // // Remove the duplicate guard policy // @@ -170,6 +170,11 @@ public class ControlLoopGuardBuilderTest { this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); } + /** + * Do the actual test. + * + * @param testFile input test file + */ 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/ControlLoopGuardTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java index 81c76c76a..1a5b5e92a 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 @@ -20,7 +20,11 @@ package org.onap.policy.controlloop.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -42,17 +46,17 @@ public class ControlLoopGuardTest { private static final Logger logger = LoggerFactory.getLogger(ControlLoopGuardTest.class); @Test - public void testGuardvDNS() { + public void testGuardvdns() { this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); } @Test - public void testGuardvUSP() { + public void testGuardvusp() { this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); } @Test - public void testConstructorControlLoopGuard(){ + public void testConstructorControlLoopGuard() { Guard guard1 = new Guard(); GuardPolicy guardPolicy1 = new GuardPolicy(); GuardPolicy guardPolicy2 = new GuardPolicy(); @@ -71,7 +75,7 @@ public class ControlLoopGuardTest { @Test public void testEqualsAndHashCode() { - Guard guard1 = new Guard(); + final Guard guard1 = new Guard(); GuardPolicy guardPolicy1 = new GuardPolicy(); GuardPolicy guardPolicy2 = new GuardPolicy(); LinkedList guardPolicies = new LinkedList<>(); @@ -115,6 +119,11 @@ public class ControlLoopGuardTest { assertFalse(controlLoopGuard.equals("")); } + /** + * Does the actual test. + * + * @param testFile input file + */ 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 index d80fecf2b..7019595b3 100644 --- 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 @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -211,9 +212,9 @@ public class GuardPolicyTest { @Test public void testEquals() { - String id = "guard id"; - String name = "guard name"; - String description = "guard description"; + final String id = "guard id"; + final String name = "guard name"; + final String description = "guard description"; GuardPolicy guardPolicy1 = new GuardPolicy(id); GuardPolicy guardPolicy2 = new GuardPolicy(); assertFalse(guardPolicy1.equals(guardPolicy2)); diff --git a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java index 4e0654df1..4fce837b9 100644 --- a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java +++ b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java @@ -22,6 +22,7 @@ package org.onap.policy.simulators; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; + import java.util.HashMap; import java.util.UUID; import org.junit.AfterClass; diff --git a/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml index c27ced3ac..590b19d25 100644 --- a/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml +++ b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml @@ -18,57 +18,100 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - + + Policy for frequency limiter. + + + + - ${clname} - - + ${clname} + + - - - ${actor} - - - - ${recipe} - - - - - - - DENY - only if target is in black list and guard is active. - - - - - - - - - - - - - - - ${blackListElement} - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - + + + ${actor} + + + + ${recipe} + + + + + + + DENY - only if target is in black list and guard is + active. + + + + + + + + + + + + + + + ${blackListElement} + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + diff --git a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml index 9e44ae846..34aa1af69 100644 --- a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml +++ b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml @@ -18,60 +18,110 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - - + + Policy for frequency limiter. + + + + + - ${clname} - - + ${clname} + + - - - ${actor} - - - - ${recipe} - - - - - ${targets} - - - - - - - - DENY - only if number of operations performed in the past is larger than the limit and the Guard is active. - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - - ${limit} - - + + + ${actor} + + + + ${recipe} + + + + + ${targets} + + + + + + + + DENY - only if number of operations performed in + the past is larger than the limit and the Guard is active. + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + + ${limit} + + diff --git a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml index 0bc182e71..b41fdb3f2 100644 --- a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml +++ b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml @@ -18,46 +18,84 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - - ${actor} - - - - ${recipe} - - - - - - - DENY - only if number of operations performed in the past is larger than the limit and the Guard is active. - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - - ${limit} - - + + Policy for frequency limiter. + + + + + ${actor} + + + + ${recipe} + + + + + + + DENY - only if number of operations performed in + the past is larger than the limit and the Guard is active. + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + + ${limit} + + diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java index 584a8e349..31b6b2e30 100644 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java @@ -62,7 +62,7 @@ import org.slf4j.LoggerFactory; public class ControlLoopFailureTest implements TopicListener { - private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class); + private static final Logger logger = LoggerFactory.getLogger(ControlLoopFailureTest.class); private static List noopTopics; @@ -75,11 +75,14 @@ public class ControlLoopFailureTest implements TopicListener { static { /* Set environment properties */ - Util.setAAIProps(); + Util.setAaiProps(); Util.setGuardProps(); - Util.setPUProp(); + Util.setPuProp(); } + /** + * Setup simulator. + */ @BeforeClass public static void setUpSimulator() { PolicyEngine.manager.configure(new Properties()); @@ -112,7 +115,8 @@ public class ControlLoopFailureTest implements TopicListener { */ try { kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", + "../archetype-cl-amsterdam/src/main/resources/archetype-resources" + + "/src/main/resources/__closedLoopControlName__.drl", "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml", "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE", "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); @@ -123,6 +127,9 @@ public class ControlLoopFailureTest implements TopicListener { } } + /** + * Tear down simulator. + */ @AfterClass public static void tearDownSimulator() { /* @@ -176,12 +183,12 @@ public class ControlLoopFailureTest implements TopicListener { * Simulate an onset event the policy engine will receive from DCAE to kick off processing * through the rules */ - sendEvent(pair.a, requestId, ControlLoopEventStatus.ONSET, "vnf01"); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vnf01"); /* * Send a second event requesting an action for a different target entity */ - sendEvent(pair.a, requestId2, ControlLoopEventStatus.ONSET, "vnf02"); + sendEvent(pair.first, requestId2, ControlLoopEventStatus.ONSET, "vnf02"); /* * Send a second event for a different target to ensure there are no problems with obtaining @@ -210,7 +217,7 @@ public class ControlLoopFailureTest implements TopicListener { * @param policyName name of the policy * @param policyVersion version of the policy * @return the kieSession to be used to insert facts - * @throws IOException + * @throws IOException throws IO exception */ private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, String policyName, String policyVersion) throws IOException { @@ -220,23 +227,24 @@ public class ControlLoopFailureTest implements TopicListener { */ pair = Util.loadYaml(yamlFile); assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); /* * Construct a kie session */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); /* * Retrieve the Policy Engine */ logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); logger.debug("============"); return kieSession; @@ -294,9 +302,9 @@ public class ControlLoopFailureTest implements TopicListener { assertNotNull(notification.getMessage()); assertTrue(notification.getMessage().startsWith("actor=APPC")); if (requestId.equals(notification.getRequestId())) { - sendEvent(pair.a, requestId, ControlLoopEventStatus.ABATED, "vnf01"); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED, "vnf01"); } else if (requestId2.equals(notification.getRequestId())) { - sendEvent(pair.a, requestId2, ControlLoopEventStatus.ABATED, "vnf02"); + sendEvent(pair.first, requestId2, ControlLoopEventStatus.ABATED, "vnf02"); } } else if (policyName.endsWith("EVENT.MANAGER")) { logger.debug("Rule Fired: " + notification.getPolicyName()); @@ -341,7 +349,7 @@ public class ControlLoopFailureTest implements TopicListener { * will be denied */ if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) { - sendEvent(pair.a, requestId3, ControlLoopEventStatus.ONSET, "vnf01"); + sendEvent(pair.first, requestId3, ControlLoopEventStatus.ONSET, "vnf01"); } kieSession.insert(dmaapResponse); } @@ -354,12 +362,12 @@ public class ControlLoopFailureTest implements TopicListener { * @param policy the controlLoopName comes from the policy * @param requestID the requestId for this event * @param status could be onset or abated - * @param target, the target entity to take an action on + * @param target the target entity to take an action on */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String target) { + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String target) { VirtualControlLoopEvent event = new VirtualControlLoopEvent(); event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); + event.setRequestId(requestId); event.setTarget("generic-vnf.vnf-id"); event.setClosedLoopAlarmStart(Instant.now()); event.setAai(new HashMap<>()); diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java index b69369181..4ec51772f 100644 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * demo * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,8 @@ package org.onap.policy.template.demo; import static org.junit.Assert.fail; +import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -44,9 +46,9 @@ import org.kie.api.builder.Results; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.controlloop.policy.ControlLoopPolicy; import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.guard.PolicyGuardYamlToXacml; import org.slf4j.Logger; @@ -54,135 +56,159 @@ import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; -import com.att.research.xacml.util.XACMLProperties; public final class Util { - private static final String OPSHISTPUPROP = "OperationsHistoryPU"; - private static final Logger logger = LoggerFactory.getLogger(Util.class); - - public static class Pair { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - } - - public static Pair loadYaml(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(contents); - - //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas"); - logger.debug(contents); - //for(Policy policy : ((ControlLoopPolicy)obj).policies){ - - return new Pair((ControlLoopPolicy) obj, contents); - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } - return null; - } - - public static ControlLoopGuard loadYamlGuard(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(contents); - return (ControlLoopGuard) obj; - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } - return null; - } - - public static HttpServletServer buildAaiSim() throws InterruptedException, IOException { - return org.onap.policy.simulators.Util.buildAaiSim(); - } - - public static HttpServletServer buildSoSim() throws InterruptedException, IOException { - return org.onap.policy.simulators.Util.buildSoSim(); - } - - public static HttpServletServer buildVfcSim() throws InterruptedException, IOException { - return org.onap.policy.simulators.Util.buildVfcSim(); - } - - public static HttpServletServer buildGuardSim() throws InterruptedException, IOException { + private static final String OPSHISTPUPROP = "OperationsHistoryPU"; + private static final Logger logger = LoggerFactory.getLogger(Util.class); + + public static class Pair { + public final A first; + public final B second; + + public Pair(A first, B second) { + this.first = first; + this.second = second; + } + } + + /** + * Load YAML. + * + * @param testFile test file to load + * @return the Pair of a policy and the yaml contents + */ + public static Pair loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + + logger.debug(contents); + + return new Pair((ControlLoopPolicy) obj, contents); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + + /** + * Load the YAML guard policy. + * + * @param testFile the test file to load + * @return return the guard object + */ + public static ControlLoopGuard loadYamlGuard(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(contents); + return (ControlLoopGuard) obj; + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + + public static HttpServletServer buildAaiSim() throws InterruptedException, IOException { + return org.onap.policy.simulators.Util.buildAaiSim(); + } + + public static HttpServletServer buildSoSim() throws InterruptedException, IOException { + return org.onap.policy.simulators.Util.buildSoSim(); + } + + public static HttpServletServer buildVfcSim() throws InterruptedException, IOException { + return org.onap.policy.simulators.Util.buildVfcSim(); + } + + public static HttpServletServer buildGuardSim() throws InterruptedException, IOException { return org.onap.policy.simulators.Util.buildGuardSim(); } - - private static String generatePolicy(String ruleContents, - String closedLoopControlName, - String policyScope, - String policyName, - String policyVersion, - String controlLoopYaml) { - - Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}"); - Matcher m = p.matcher(ruleContents); - ruleContents = m.replaceAll(closedLoopControlName); - - p = Pattern.compile("\\$\\{policyScope\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyScope); - - p = Pattern.compile("\\$\\{policyName\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyName); - - p = Pattern.compile("\\$\\{policyVersion\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyVersion); - - p = Pattern.compile("\\$\\{controlLoopYaml\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(controlLoopYaml); - - return ruleContents; - } - - public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException { - // - // Get our Drools Kie factory - // + + private static String generatePolicy(String ruleContents, + String closedLoopControlName, + String policyScope, + String policyName, + String policyVersion, + String controlLoopYaml) { + + Pattern pattern = Pattern.compile("\\$\\{closedLoopControlName\\}"); + Matcher matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(closedLoopControlName); + + pattern = Pattern.compile("\\$\\{policyScope\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(policyScope); + + pattern = Pattern.compile("\\$\\{policyName\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(policyName); + + pattern = Pattern.compile("\\$\\{policyVersion\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(policyVersion); + + pattern = Pattern.compile("\\$\\{controlLoopYaml\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(controlLoopYaml); + + return ruleContents; + } + + /** + * Build the container. + * + * @param droolsTemplate template + * @param closedLoopControlName control loop id + * @param policyScope policy scope + * @param policyName policy name + * @param policyVersion policy version + * @param yamlSpecification incoming yaml specification + * @return the Kie session + * @throws IOException if the container cannot be built + */ + public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, + String policyScope, String policyName, String policyVersion, + String yamlSpecification) throws IOException { + // + // Get our Drools Kie factory + // KieServices ks = KieServices.Factory.get(); - - KieModuleModel kModule = ks.newKieModuleModel(); - - logger.debug("KMODULE:" + System.lineSeparator() + kModule.toXML()); - + + KieModuleModel kieModule = ks.newKieModuleModel(); + + logger.debug("KMODULE:" + System.lineSeparator() + kieModule.toXML()); + // // Generate our drools rule from our template // KieFileSystem kfs = ks.newKieFileSystem(); - - kfs.writeKModuleXML(kModule.toXML()); + + kfs.writeKModuleXML(kieModule.toXML()); { - Path rule = Paths.get(droolsTemplate); - String ruleTemplate = new String(Files.readAllBytes(rule)); - String drlContents = generatePolicy(ruleTemplate, - closedLoopControlName, - policyScope, - policyName, - policyVersion, - yamlSpecification); - - kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes())); + Path rule = Paths.get(droolsTemplate); + String ruleTemplate = new String(Files.readAllBytes(rule)); + String drlContents = generatePolicy(ruleTemplate, + closedLoopControlName, + policyScope, + policyName, + policyVersion, + yamlSpecification); + + kfs.write("src/main/resources/" + policyName + ".drl", + ks.getResources().newByteArrayResource(drlContents.getBytes())); } // // Compile the rule @@ -190,95 +216,112 @@ public final class Util { KieBuilder builder = ks.newKieBuilder(kfs).buildAll(); Results results = builder.getResults(); if (results.hasMessages(Message.Level.ERROR)) { - for (Message msg : results.getMessages()) { - logger.error(msg.toString()); - } - throw new RuntimeException("Drools Rule has Errors"); + for (Message msg : results.getMessages()) { + logger.error(msg.toString()); + } + throw new RuntimeException("Drools Rule has Errors"); + } + for (Message msg : results.getMessages()) { + logger.debug(msg.toString()); } - for (Message msg : results.getMessages()) { - logger.debug(msg.toString()); - } - // - // Create our kie Session and container - // + // + // Create our kie Session and container + // ReleaseId releaseId = ks.getRepository().getDefaultReleaseId(); logger.debug(releaseId.toString()); - KieContainer kContainer = ks.newKieContainer(releaseId); - - return setupSession(kContainer.newKieSession()); - } - - private static KieSession setupSession (KieSession kieSession) { - - - // - // Create XACML Guard policy from YAML - // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm) - // - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_modifyconfig.yaml", + KieContainer keyContainer = ks.newKieContainer(releaseId); + + return setupSession(keyContainer.newKieSession()); + } + + private static KieSession setupSession(KieSession kieSession) { + + + // + // Create XACML Guard policy from YAML + // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm) + // + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_modifyconfig.yaml", "src/main/resources/frequency_limiter_template.xml", "src/test/resources/xacml/autogenerated_frequency_limiter_modifyconfig.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist("src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml", - "src/main/resources/blacklist_template.xml", - "src/test/resources/xacml/autogenerated_blacklist.xml"); - - // - // Creating an embedded XACML PDP - // - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties"); - - return kieSession; - } - - public static void setAAIProps(){ - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist( + "src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml", + "src/main/resources/blacklist_template.xml", + "src/test/resources/xacml/autogenerated_blacklist.xml"); + + // + // Creating an embedded XACML PDP + // + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties"); + + return kieSession; + } + + /** + * Set the A&AI properties. + */ + public static void setAaiProps() { + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - } - - public static void setSOProps(){ - PolicyEngine.manager.setEnvironmentProperty("so.url", "http://localhost:6667"); + } + + /** + * Set the SO properties. + */ + public static void setSoProps() { + PolicyEngine.manager.setEnvironmentProperty("so.url", "http://localhost:6667"); PolicyEngine.manager.setEnvironmentProperty("so.username", "SO"); PolicyEngine.manager.setEnvironmentProperty("so.password", "SO"); - } - - public static void setGuardProps(){ - /* - * Guard PDP-x connection Properties - */ - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, "http://localhost:6669/pdp/api/getDecision"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, "python"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, "test"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, "python"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, "test"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, "TEST"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_DISABLED, "false"); } - - public static void setVFCProps() { - PolicyEngine.manager.setEnvironmentProperty("vfc.url", "http://localhost:6668"); + + /** + * Set the Guard properties. + */ + public static void setGuardProps() { + /* + * Guard PDP-x connection Properties + */ + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, "http://localhost:6669/pdp/api/getDecision"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, "python"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, "test"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, "python"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, "test"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, "TEST"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_DISABLED, "false"); + } + + /** + * Set the VFC properties. + */ + public static void setVfcProps() { + PolicyEngine.manager.setEnvironmentProperty("vfc.url", "http://localhost:6668"); PolicyEngine.manager.setEnvironmentProperty("vfc.username", "VFC"); PolicyEngine.manager.setEnvironmentProperty("vfc.password", "VFC"); - } - public static void setPUProp(){ - System.setProperty(OPSHISTPUPROP, "TestOperationsHistoryPU"); - } + } + + /** + * Set the operation history properties. + */ + public static void setPuProp() { + System.setProperty(OPSHISTPUPROP, "TestOperationsHistoryPU"); + } } diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java deleted file mode 100644 index 785be9907..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java +++ /dev/null @@ -1,399 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.appclcm.LcmRequest; -import org.onap.policy.appclcm.LcmRequestWrapper; -import org.onap.policy.appclcm.LcmResponse; -import org.onap.policy.appclcm.LcmResponseWrapper; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.ControlLoopTargetType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VCPEControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper"); - noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", - "org.onap.policy.appclcm.util.Serialization,gson"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", - "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111); - try { - Util.buildAaiSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - /* - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml", - "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE", - "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void aaiGetFailTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail", false); - - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } else if ("APPC-LCM-READ".equals(topic)) { - obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.appclcm.LcmRequestWrapper.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("APPC.LCM.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - kieSession.halt(); - } else { - assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); - kieSession.halt(); - } - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof LcmRequestWrapper) { - /* - * The request should be of type LcmRequestWrapper and the subrequestid should be 1 - */ - LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj; - LcmRequest appcRequest = dmaapRequest.getBody(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1")); - assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id")); - - logger.debug("\n============ APPC received the request!!! ===========\n"); - - /* - * Simulate a success response from APPC and insert the response into the working memory - */ - LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); - LcmResponse appcResponse = new LcmResponse(appcRequest); - appcResponse.getStatus().setCode(400); - appcResponse.getStatus().setMessage("AppC success"); - dmaapResponse.setBody(appcResponse); - kieSession.insert(dmaapResponse); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName"); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfName, - boolean isEnriched) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setTargetType(ControlLoopTargetType.VNF); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", vnfName); - if (isEnriched) { - event.getAai().put("generic-vnf.in-maint", "false"); - event.getAai().put("generic-vnf.is-closed-loop-disabled", "false"); - event.getAai().put("generic-vnf.orchestration-status", "Created"); - event.getAai().put("generic-vnf.prov-status", "ACTIVE"); - event.getAai().put("generic-vnf.resource-version", "1"); - event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd"); - event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9"); - event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0"); - } - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method will dump all the facts in the working memory. - * - * @param kieSession the session containing the facts - */ - public void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: {}", kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: {}", handle); - } - } - -} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java deleted file mode 100644 index 630ade8c5..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java +++ /dev/null @@ -1,403 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.onap.policy.so.SORequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VDNSControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VDNSControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setSOProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - - try { - Util.buildAaiSim(); - Util.buildSoSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - - /* - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void namedQueryFailTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error"); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void aaiGetFailTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail"); - - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail(e.getMessage()); - } - - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=SO")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("SO.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=SO")); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("error".equals(notification.getAai().get("vserver.vserver-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else { - assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); - } - kieSession.halt(); - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof SORequest) { - logger.debug("\n============ SO received the request!!! ===========\n"); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("vserver.vserver-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("vserver.vserver-name", "dfw1lb01lb01"); - event.getAai().put("vserver.is-closed-loop-disabled", "false"); - event.getAai().put("vserver.prov-status", "ACTIVE"); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, - String vserverName) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("vserver.vserver-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("vserver.vserver-name", vserverName); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method will dump all the facts in the working memory. - * - * @param kieSession the session containing the facts - */ - public void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: {}", kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: {}", handle); - } - } -} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java deleted file mode 100644 index 6f11bc65c..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java +++ /dev/null @@ -1,362 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * Copyright (C) 2017-2018 Intel Corp. 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.ControlLoopTargetType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.onap.policy.vfc.VFCRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class VFCControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VFCControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setVFCProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - - try { - Util.buildAaiSim(); - Util.buildVfcSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - /* - * - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() throws IOException { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void nullRequestTest() throws IOException { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - event.setRequestId(UUID.randomUUID()); - event.setClosedLoopEventClient("tca.instance00009"); - event.setTargetType(ControlLoopTargetType.VM); - event.setTarget("vserver.vserver-name"); - event.setFrom("DCAE"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap()); - event.getAai().put("vserver.vserver-name", "nullRequest"); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - kieSession.insert(event); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=VFC")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("VFC.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=VFC")); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else { - assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); - } - kieSession.halt(); - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof VFCRequest) { - logger.debug("\n============ VFC received the request!!! ===========\n"); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(UUID.randomUUID()); - event.setClosedLoopEventClient("tca.instance00009"); - event.setTargetType(ControlLoopTargetType.VM); - event.setTarget("vserver.vserver-name"); - event.setFrom("DCAE"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap()); - event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); - event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1"); - event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1"); - event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1"); - event.getAai().put("vserver.is-closed-loop-disabled", "false"); - event.getAai().put("vserver.prov-status", "ACTIVE"); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - kieSession.insert(event); - } - - public static void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: " + kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: " + handle); - } - } - -} - diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java deleted file mode 100644 index 756fb202f..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java +++ /dev/null @@ -1,427 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.appc.Request; -import org.onap.policy.appc.Response; -import org.onap.policy.appc.ResponseCode; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VFWControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response"); - noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", - "org.onap.policy.appc.util.Serialization,gsonPretty"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", - "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111); - - try { - Util.buildAaiSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - - /* - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_vFW.yaml", - "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW", - "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET); - - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail("fail"); - } - - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void aaiFailTests() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error"); - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail(e.getMessage()); - } - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail"); - - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail(e.getMessage()); - } - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } else if ("APPC-CL".equals(topic)) { - obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, - org.onap.policy.appc.Request.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("APPC.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - assertEquals("Target vnf-id could not be found", notification.getMessage()); - } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else { - assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); - } - kieSession.halt(); - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof Request) { - assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1")); - assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id")); - - logger.debug("\n============ APPC received the request!!! ===========\n"); - - /* - * Simulate a success response from APPC and insert the response into the working memory - */ - Response appcResponse = new Response((Request) obj); - appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue()); - appcResponse.getStatus().setValue("SUCCESS"); - kieSession.insert(appcResponse); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID"); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfId) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", vnfId); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method will dump all the facts in the working memory. - * - * @param kieSession the session containing the facts - */ - public void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: {}", kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: {}", handle); - } - } -} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java new file mode 100644 index 000000000..c1e8e1e66 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java @@ -0,0 +1,407 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.appclcm.LcmRequest; +import org.onap.policy.appclcm.LcmRequestWrapper; +import org.onap.policy.appclcm.LcmResponse; +import org.onap.policy.appclcm.LcmResponseWrapper; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopTargetType; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VcpeControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VcpeControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper"); + noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", + "org.onap.policy.appclcm.util.Serialization,gson"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", + "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111); + try { + Util.buildAaiSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + /* + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources" + + "/src/main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml", + "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE", + "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void aaiGetFailTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail", false); + + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } else if ("APPC-LCM-READ".equals(topic)) { + obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.appclcm.LcmRequestWrapper.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("APPC.LCM.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + kieSession.halt(); + } else { + assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); + kieSession.halt(); + } + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof LcmRequestWrapper) { + /* + * The request should be of type LcmRequestWrapper and the subrequestid should be 1 + */ + LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj; + LcmRequest appcRequest = dmaapRequest.getBody(); + assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1")); + assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id")); + + logger.debug("\n============ APPC received the request!!! ===========\n"); + + /* + * Simulate a success response from APPC and insert the response into the working memory + */ + LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); + LcmResponse appcResponse = new LcmResponse(appcRequest); + appcResponse.getStatus().setCode(400); + appcResponse.getStatus().setMessage("AppC success"); + dmaapResponse.setBody(appcResponse); + kieSession.insert(dmaapResponse); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName"); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfName, + boolean isEnriched) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setTargetType(ControlLoopTargetType.VNF); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", vnfName); + if (isEnriched) { + event.getAai().put("generic-vnf.in-maint", "false"); + event.getAai().put("generic-vnf.is-closed-loop-disabled", "false"); + event.getAai().put("generic-vnf.orchestration-status", "Created"); + event.getAai().put("generic-vnf.prov-status", "ACTIVE"); + event.getAai().put("generic-vnf.resource-version", "1"); + event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd"); + event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9"); + event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0"); + } + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method will dump all the facts in the working memory. + * + * @param kieSession the session containing the facts + */ + public void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: {}", kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: {}", handle); + } + } + +} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java new file mode 100644 index 000000000..d1fb29e0a --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java @@ -0,0 +1,411 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.onap.policy.so.SORequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VdnsControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VdnsControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setSoProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + + try { + Util.buildAaiSim(); + Util.buildSoSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + + /* + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources/" + + "src/main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void namedQueryFailTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error"); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void aaiGetFailTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail"); + + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail(e.getMessage()); + } + + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO Exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=SO")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("SO.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=SO")); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("error".equals(notification.getAai().get("vserver.vserver-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else { + assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); + } + kieSession.halt(); + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof SORequest) { + logger.debug("\n============ SO received the request!!! ===========\n"); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("vserver.vserver-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("vserver.vserver-name", "dfw1lb01lb01"); + event.getAai().put("vserver.is-closed-loop-disabled", "false"); + event.getAai().put("vserver.prov-status", "ACTIVE"); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, + String vserverName) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("vserver.vserver-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("vserver.vserver-name", vserverName); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method will dump all the facts in the working memory. + * + * @param kieSession the session containing the facts + */ + public void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: {}", kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: {}", handle); + } + } +} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java new file mode 100644 index 000000000..449a90fe0 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java @@ -0,0 +1,376 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * Copyright (C) 2017-2018 Intel Corp. All rights reserved. + * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopTargetType; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.onap.policy.vfc.VFCRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class VfcControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VfcControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setVfcProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + + try { + Util.buildAaiSim(); + Util.buildVfcSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + /* + * + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources/" + + "src/main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() throws IOException { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void nullRequestTest() throws IOException { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName()); + event.setRequestId(UUID.randomUUID()); + event.setClosedLoopEventClient("tca.instance00009"); + event.setTargetType(ControlLoopTargetType.VM); + event.setTarget("vserver.vserver-name"); + event.setFrom("DCAE"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap()); + event.getAai().put("vserver.vserver-name", "nullRequest"); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + kieSession.insert(event); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO Exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=VFC")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("VFC.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=VFC")); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else { + assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); + } + kieSession.halt(); + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof VFCRequest) { + logger.debug("\n============ VFC received the request!!! ===========\n"); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(UUID.randomUUID()); + event.setClosedLoopEventClient("tca.instance00009"); + event.setTargetType(ControlLoopTargetType.VM); + event.setTarget("vserver.vserver-name"); + event.setFrom("DCAE"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap()); + event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); + event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1"); + event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1"); + event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1"); + event.getAai().put("vserver.is-closed-loop-disabled", "false"); + event.getAai().put("vserver.prov-status", "ACTIVE"); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + kieSession.insert(event); + } + + /** + * Dumps the kie session facts. + * + * @param kieSession input session + */ + public static void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: " + kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: " + handle); + } + } + +} + diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java new file mode 100644 index 000000000..b06f4c695 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java @@ -0,0 +1,435 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VfwControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VfwControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response"); + noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", + "org.onap.policy.appc.util.Serialization,gsonPretty"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", + "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111); + + try { + Util.buildAaiSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + + /* + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/" + + "main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_vFW.yaml", + "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW", + "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET); + + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail("fail"); + } + + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void aaiFailTests() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error"); + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail(e.getMessage()); + } + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail"); + + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail(e.getMessage()); + } + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO Exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } else if ("APPC-CL".equals(topic)) { + obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, + org.onap.policy.appc.Request.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("APPC.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + assertEquals("Target vnf-id could not be found", notification.getMessage()); + } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else { + assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); + } + kieSession.halt(); + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof Request) { + assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1")); + assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id")); + + logger.debug("\n============ APPC received the request!!! ===========\n"); + + /* + * Simulate a success response from APPC and insert the response into the working memory + */ + Response appcResponse = new Response((Request) obj); + appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue()); + appcResponse.getStatus().setValue("SUCCESS"); + kieSession.insert(appcResponse); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID"); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfId) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", vnfId); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method will dump all the facts in the working memory. + * + * @param kieSession the session containing the facts + */ + public void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: {}", kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: {}", handle); + } + } +} diff --git a/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml b/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml index ec956a274..808cef9b6 100644 --- a/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml +++ b/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml @@ -19,23 +19,30 @@ ============LICENSE_END========================================================= --> + xmlns="http://xmlns.jcp.org/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> - - - org.eclipse.persistence.jpa.PersistenceProvider - org.onap.policy.controlloop.eventmanager.OperationsHistoryDbEntry - - - - - - - - - + + + org.eclipse.persistence.jpa.PersistenceProvider + org.onap.policy.controlloop.eventmanager.OperationsHistoryDbEntry + + + + + + + + + -- cgit 1.2.3-korg