From cd68fc9bae7d6258f77ff59c1431e4f925f61a4c Mon Sep 17 00:00:00 2001 From: liamfallon Date: Thu, 13 Sep 2018 23:48:50 +0100 Subject: Address sonar/Checkstyle Issues Sweep through Apex codebase to fix most ceheckstyle and straightforward sonar issues. Issue-ID: POLICY-1034 Change-Id: I149d9a94ad893affc93573e8de5e3304b6bdde2d Signed-off-by: liamfallon --- .../apex/auth/clieditor/CommandLineEditorLoop.java | 11 +- .../client/deployment/rest/ApexDeploymentRest.java | 4 +- .../deployment/rest/ApexDeploymentRestMain.java | 31 +- .../rest/ApexDeploymentRestParameterParser.java | 2 +- .../rest/ApexDeploymentRestParameters.java | 73 +- .../rest/ApexDeploymentRestResource.java | 5 - .../policy/apex/client/editor/rest/ApexEditor.java | 4 +- .../apex/client/editor/rest/ApexEditorMain.java | 31 +- .../editor/rest/ApexEditorParameterParser.java | 2 +- .../client/editor/rest/ApexEditorParameters.java | 12 +- .../client/editor/rest/ApexEditorRestResource.java | 888 ++++++++++----------- .../policy/apex/client/editor/rest/RestUtils.java | 25 +- .../apex/client/editor/rest/RestInterfaceTest.java | 16 +- .../client/editor/rest/TestApexEditorStartup.java | 14 +- .../apex/client/full/rest/ApexServicesRest.java | 4 +- .../client/full/rest/ApexServicesRestMain.java | 31 +- .../full/rest/ApexServicesRestParameterParser.java | 2 +- .../full/rest/ApexServicesRestParameters.java | 21 +- .../client/monitoring/rest/ApexMonitoringRest.java | 4 +- .../monitoring/rest/ApexMonitoringRestMain.java | 31 +- .../rest/ApexMonitoringRestParameterParser.java | 2 +- .../rest/ApexMonitoringRestParameters.java | 14 +- .../rest/ApexMonitoringRestResource.java | 103 +-- .../aadm/model/AadmDomainModelFactory.java | 699 ++++++++-------- .../examples/aadm/model/AadmDomainModelSaver.java | 7 +- .../model/mvel/AADMDoSProvenActTaskTaskLogic.mvel | 80 ++ .../model/mvel/AADMDoSProvenActTask_TaskLogic.mvel | 80 -- .../mvel/AADMDoSSuggestionActTaskTaskLogic.mvel | 106 +++ .../mvel/AADMDoSSuggestionActTask_TaskLogic.mvel | 106 --- .../aadm/model/mvel/AADMMatchTaskTaskLogic.mvel | 75 ++ .../aadm/model/mvel/AADMMatchTask_TaskLogic.mvel | 75 -- .../aadm/model/mvel/AADMNoActTaskTaskLogic.mvel | 55 ++ .../aadm/model/mvel/AADMNoActTask_TaskLogic.mvel | 55 -- .../mvel/AADMPolicyActTaskSelectionLogic.mvel | 67 ++ .../mvel/AADMPolicy_Act_TaskSelectionLogic.mvel | 67 -- .../examples/aadm/model/mvel/DefaultTaskLogic.mvel | 23 + .../aadm/model/mvel/DefaultTaskSelectionLogic.mvel | 23 + .../aadm/model/mvel/Default_TaskLogic.mvel | 23 - .../model/mvel/Default_TaskSelectionLogic.mvel | 23 - .../aadm/model/mvel/PeriodicActTaskTaskLogic.mvel | 40 + .../aadm/model/mvel/PeriodicActTask_TaskLogic.mvel | 40 - .../aadm/model/mvel/SAPCActTaskTaskLogic.mvel | 79 ++ .../aadm/model/mvel/SAPCActTask_TaskLogic.mvel | 79 -- .../aadm/model/mvel/SAPCMatchTaskTaskLogic.mvel | 52 ++ .../aadm/model/mvel/SAPCMatchTask_TaskLogic.mvel | 52 -- .../aadm/model/mvel/VMMEActTaskTaskLogic.mvel | 44 + .../aadm/model/mvel/VMMEActTask_TaskLogic.mvel | 44 - .../aadm/model/mvel/VMMEMatchTaskTaskLogic.mvel | 47 ++ .../aadm/model/mvel/VMMEMatchTask_TaskLogic.mvel | 47 -- .../adaptive/concepts/AnomalyDetection.java | 2 +- .../apex/examples/adaptive/concepts/AutoLearn.java | 9 +- .../adaptive/model/AdaptiveDomainModelFactory.java | 526 ++++++------ .../adaptive/model/AdaptiveDomainModelSaver.java | 15 +- ...alyDetectionPolicyDecideTaskSelectionLogic.java | 410 ++++++++++ ...yDetectionPolicy_Decide_TaskSelectionLogic.java | 406 ---------- .../AutoLearnPolicyDecideTaskSelectionLogic.java | 157 ++++ .../AutoLearnPolicy_Decide_TaskSelectionLogic.java | 151 ---- .../model/mvel/AutoLearnDecideTask0TaskLogic.mvel | 40 + .../model/mvel/AutoLearnDecideTask0_TaskLogic.mvel | 40 - .../model/mvel/AutoLearnDecideTask1TaskLogic.mvel | 40 + .../model/mvel/AutoLearnDecideTask1_TaskLogic.mvel | 40 - .../model/mvel/AutoLearnDecideTask2TaskLogic.mvel | 40 + .../model/mvel/AutoLearnDecideTask2_TaskLogic.mvel | 40 - .../model/mvel/AutoLearnDecideTask3TaskLogic.mvel | 40 + .../model/mvel/AutoLearnDecideTask3_TaskLogic.mvel | 40 - .../model/mvel/AutoLearnDecideTask4TaskLogic.mvel | 40 + .../model/mvel/AutoLearnDecideTask4_TaskLogic.mvel | 40 - .../model/mvel/AutoLearnDecideTask5TaskLogic.mvel | 40 + .../model/mvel/AutoLearnDecideTask5_TaskLogic.mvel | 40 - .../model/mvel/AutoLearnDecideTask6TaskLogic.mvel | 40 + .../model/mvel/AutoLearnDecideTask6_TaskLogic.mvel | 40 - .../myfirstpolicy/model/MfpDomainModelSaver.java | 6 +- .../examples/pcvs/model/PcvsDomainModelSaver.java | 15 +- .../policymodel/handling/PolicyLogicReader.java | 12 +- .../handling/TestPolicyLogicReader.java | 8 +- ...ogicParentLocalNameLogicInstanceName.funkylogic | 21 + ...gicParentLocalName_LogicInstanceName.funkylogic | 21 - .../carrier/restserver/RestServerEndpoint.java | 52 +- testsuites/integration/integration-common/pom.xml | 2 +- .../test/common/model/EvalDomainModelFactory.java | 501 ------------ .../common/model/SampleDomainModelFactory.java | 717 ----------------- .../test/common/model/SampleDomainModelSaver.java | 82 -- .../test/common/model/java/DefaultState_Logic.java | 43 - .../test/common/model/java/DefaultTask_Logic.java | 71 -- .../test/common/model/java/EvalState_Logic.java | 42 - .../test/common/model/java/EvalTask_Logic.java | 50 -- .../apex/test/common/model/java/package-info.java | 26 - .../apex/test/common/model/package-info.java | 26 - .../common/model/EvalDomainModelFactory.java | 585 ++++++++++++++ .../common/model/SampleDomainModelFactory.java | 776 ++++++++++++++++++ .../common/model/SampleDomainModelSaver.java | 92 +++ .../common/model/java/DefaultStateLogic.java | 41 + .../common/model/java/DefaultTaskLogic.java | 74 ++ .../common/model/java/EvalStateLogic.java | 40 + .../common/model/java/EvalTaskLogic.java | 56 ++ .../common/model/java/package-info.java | 26 + .../integration/common/model/package-info.java | 26 + .../model/javascript/DefaultState_Logic.javascript | 27 - .../model/javascript/DefaultTask_Logic.javascript | 34 - .../model/javascript/EvalState_Logic.javascript | 25 - .../model/javascript/EvalTask_Logic.javascript | 29 - .../common/model/jruby/DefaultState_Logic.jruby | 24 - .../common/model/jruby/DefaultTask_Logic.jruby | 33 - .../test/common/model/jruby/EvalState_Logic.jruby | 23 - .../test/common/model/jruby/EvalTask_Logic.jruby | 32 - .../common/model/jython/DefaultState_Logic.jython | 27 - .../common/model/jython/DefaultTask_Logic.jython | 35 - .../common/model/jython/EvalState_Logic.jython | 25 - .../test/common/model/jython/EvalTask_Logic.jython | 32 - .../test/common/model/mvel/DefaultState_Logic.mvel | 23 - .../test/common/model/mvel/DefaultTask_Logic.mvel | 30 - .../test/common/model/mvel/EvalState_Logic.mvel | 23 - .../test/common/model/mvel/EvalTask_Logic.mvel | 26 - .../model/javascript/DefaultStateLogic.javascript | 27 + .../model/javascript/DefaultTaskLogic.javascript | 34 + .../model/javascript/EvalStateLogic.javascript | 25 + .../model/javascript/EvalTaskLogic.javascript | 29 + .../common/model/jruby/DefaultStateLogic.jruby | 24 + .../common/model/jruby/DefaultTaskLogic.jruby | 33 + .../common/model/jruby/EvalStateLogic.jruby | 23 + .../common/model/jruby/EvalTaskLogic.jruby | 32 + .../common/model/jython/DefaultStateLogic.jython | 27 + .../common/model/jython/DefaultTaskLogic.jython | 35 + .../common/model/jython/EvalStateLogic.jython | 25 + .../common/model/jython/EvalTaskLogic.jython | 32 + .../common/model/mvel/DefaultStateLogic.mvel | 23 + .../common/model/mvel/DefaultTaskLogic.mvel | 30 + .../common/model/mvel/EvalStateLogic.mvel | 23 + .../common/model/mvel/EvalTaskLogic.mvel | 26 + .../test/locking/TestConcurrentContext.java | 374 --------- .../integration/context/TestConcurrentContext.java | 443 ++++++++++ .../test/script/engine/TestApexActionListener.java | 101 --- .../test/script/engine/TestApexEngine.java | 129 --- .../test/script/engine/TestApexEngineJRuby.java | 94 --- .../test/script/engine/TestApexEngineJava.java | 97 --- .../script/engine/TestApexEngineJavascript.java | 93 --- .../test/script/engine/TestApexEngineJython.java | 92 --- .../test/script/engine/TestApexEngineMvel.java | 92 --- .../test/script/event/TestEventInstantiation.java | 234 ------ .../test/script/handling/TestApexModelExport.java | 114 --- .../handling/TestApexPolicyModelAnalysis.java | 38 - .../TestApexSamplePolicyCreateModelFiles.java | 73 -- .../handling/TestApexSamplePolicyDBWrite.java | 59 -- .../script/handling/TestApexSamplePolicyModel.java | 81 -- .../handling/TestApexSamplePolicyModelCreator.java | 61 -- .../handling/TestContextUpdateDifferentModels.java | 148 ---- .../script/handling/TestContextUpdateModel.java | 202 ----- .../executor/engine/TestApexActionListener.java | 101 +++ .../executor/engine/TestApexEngine.java | 129 +++ .../executor/engine/TestApexEngineJRuby.java | 103 +++ .../executor/engine/TestApexEngineJava.java | 103 +++ .../executor/engine/TestApexEngineJavascript.java | 102 +++ .../executor/engine/TestApexEngineJython.java | 101 +++ .../executor/engine/TestApexEngineMvel.java | 101 +++ .../executor/event/TestEventInstantiation.java | 238 ++++++ .../executor/handling/TestApexModelExport.java | 114 +++ .../handling/TestApexPolicyModelAnalysis.java | 38 + .../TestApexSamplePolicyCreateModelFiles.java | 73 ++ .../handling/TestApexSamplePolicyDbWrite.java | 77 ++ .../handling/TestApexSamplePolicyModel.java | 114 +++ .../handling/TestApexSamplePolicyModelCreator.java | 83 ++ .../handling/TestContextUpdateDifferentModels.java | 161 ++++ .../executor/handling/TestContextUpdateModel.java | 233 ++++++ .../uservice/test/adapt/events/EventGenerator.java | 501 ------------ .../uservice/test/adapt/file/TestFile2File.java | 78 -- .../test/adapt/file/TestFile2FileFiltered.java | 108 --- .../test/adapt/file/TestFile2FileIgnore.java | 75 -- .../uservice/test/adapt/jms/JMSEventProducer.java | 127 --- .../test/adapt/jms/JMSEventSubscriber.java | 113 --- .../apps/uservice/test/adapt/jms/TestContext.java | 191 ----- .../test/adapt/jms/TestInitialContextFactory.java | 48 -- .../apps/uservice/test/adapt/jms/TestJMS2JMS.java | 154 ---- .../apps/uservice/test/adapt/jms/TestPing.java | 97 --- .../test/adapt/kafka/KafkaEventProducer.java | 166 ---- .../test/adapt/kafka/KafkaEventSubscriber.java | 111 --- .../uservice/test/adapt/kafka/TestKafka2Kafka.java | 185 ----- .../adapt/kafka/TestKafkaXMLEventProducer.java | 63 -- .../test/adapt/restclient/TestFile2REST.java | 205 ----- .../test/adapt/restclient/TestREST2File.java | 188 ----- .../adapt/restclient/TestRESTClientEndpoint.java | 123 --- .../test/adapt/restserver/TestRESTServer.java | 343 -------- .../adapt/restserver/TestRESTServerVPNContext.java | 136 ---- .../apps/uservice/test/adapt/sampletypes/Foo.java | 48 -- .../uservice/test/adapt/sampletypes/FooMap.java | 48 -- .../test/adapt/websocket/TestWs2WsClient.java | 71 -- .../test/adapt/websocket/TestWs2WsServer.java | 71 -- .../websocket/WebSocketEventProducerClient.java | 176 ---- .../websocket/WebSocketEventProducerServer.java | 174 ---- .../websocket/WebSocketEventSubscriberClient.java | 104 --- .../websocket/WebSocketEventSubscriberServer.java | 106 --- .../test/context/EventAlbumContextTest.java | 122 --- .../uservice/test/engdep/EngDepMessagingTest.java | 219 ----- .../uservice/test/engdep/EngineTestServer.java | 269 ------- .../uservice/adapt/events/EventGenerator.java | 610 ++++++++++++++ .../uservice/adapt/file/TestFile2File.java | 78 ++ .../uservice/adapt/file/TestFile2FileFiltered.java | 112 +++ .../uservice/adapt/file/TestFile2FileIgnore.java | 96 +++ .../uservice/adapt/jms/JmsEventProducer.java | 162 ++++ .../uservice/adapt/jms/JmsEventSubscriber.java | 137 ++++ .../uservice/adapt/jms/TestContext.java | 282 +++++++ .../adapt/jms/TestInitialContextFactory.java | 54 ++ .../uservice/adapt/jms/TestJms2Jms.java | 198 +++++ .../integration/uservice/adapt/jms/TestPing.java | 147 ++++ .../uservice/adapt/kafka/KafkaEventProducer.java | 201 +++++ .../uservice/adapt/kafka/KafkaEventSubscriber.java | 137 ++++ .../uservice/adapt/kafka/TestKafka2Kafka.java | 185 +++++ .../adapt/kafka/TestKafkaXmlEventProducer.java | 70 ++ .../uservice/adapt/restclient/TestFile2Rest.java | 266 ++++++ .../uservice/adapt/restclient/TestRest2File.java | 251 ++++++ .../adapt/restclient/TestRestClientEndpoint.java | 163 ++++ .../uservice/adapt/restserver/TestRestServer.java | 447 +++++++++++ .../adapt/restserver/TestRestServerVpnContext.java | 136 ++++ .../uservice/adapt/sampletypes/Foo.java | 48 ++ .../uservice/adapt/sampletypes/FooMap.java | 48 ++ .../uservice/adapt/websocket/TestWs2WsClient.java | 71 ++ .../uservice/adapt/websocket/TestWs2WsServer.java | 94 +++ .../websocket/WebSocketEventProducerClient.java | 176 ++++ .../websocket/WebSocketEventProducerServer.java | 174 ++++ .../websocket/WebSocketEventSubscriberClient.java | 104 +++ .../websocket/WebSocketEventSubscriberServer.java | 106 +++ .../uservice/context/EventAlbumContextTest.java | 122 +++ .../uservice/engdep/EngDepMessagingTest.java | 227 ++++++ .../uservice/engdep/EngineTestServer.java | 269 +++++++ .../test/resources/policymodels/JMSTestModel.json | 8 +- .../test/resources/prodcons/JMS2JMSJsonEvent.json | 4 +- .../resources/prodcons/JMS2JMSObjectEvent.json | 4 +- .../engine/benchmark/ApexBaseBenchMarkTest.java | 139 ---- .../engine/benchmark/ApexEngineBenchmark.java | 137 ---- .../engine/benchmark/TestApexEventListener.java | 92 --- .../policy/apex/service/engine/main/BaseTest.java | 120 --- .../service/engine/main/TestAsyncEventMIMO.java | 36 - .../service/engine/main/TestAsyncEventMISO.java | 33 - .../service/engine/main/TestAsyncEventSIMO.java | 36 - .../service/engine/main/TestAsyncEventSISO.java | 33 - .../service/engine/main/TestSyncEventMIMO.java | 36 - .../service/engine/main/TestSyncEventSISO.java | 33 - .../engine/runtime/ApexServiceModelUpdateTest.java | 363 --------- .../service/engine/runtime/ApexServiceTest.java | 474 ----------- .../policy/apex/service/engine/utils/Utils.java | 40 - .../engine/benchmark/ApexBaseBenchMarkTest.java | 175 ++++ .../engine/benchmark/ApexEngineBenchmark.java | 183 +++++ .../engine/benchmark/TestApexEventListener.java | 126 +++ .../benchmark/engine/main/BaseTest.java | 122 +++ .../benchmark/engine/main/TestAsyncEventMimo.java | 43 + .../benchmark/engine/main/TestAsyncEventMiso.java | 33 + .../benchmark/engine/main/TestAsyncEventSimo.java | 43 + .../benchmark/engine/main/TestAsyncEventSiso.java | 33 + .../benchmark/engine/main/TestSyncEventMimo.java | 43 + .../benchmark/engine/main/TestSyncEventSiso.java | 33 + .../engine/runtime/ApexServiceModelUpdateTest.java | 362 +++++++++ .../benchmark/engine/runtime/ApexServiceTest.java | 477 +++++++++++ .../performance/benchmark/engine/utils/Utils.java | 55 ++ .../context/metrics/ConcurrentContextMetrics.java | 322 -------- .../apex/plugins/context/metrics/package-info.java | 27 - .../context/metrics/ConcurrentContextMetrics.java | 323 ++++++++ .../performance/context/metrics/package-info.java | 27 + .../apex/plugins/context/metrics/TestMetrics.java | 80 -- .../performance/context/metrics/TestMetrics.java | 94 +++ .../apex/tools/model/generator/KeyInfoGetter.java | 6 +- .../apex/tools/model/generator/SchemaUtils.java | 5 - .../tools/model/generator/model2cli/Model2Cli.java | 38 +- .../model2event/Model2JsonEventSchema.java | 42 +- .../apex/tools/simple/wsclient/SimpleConsole.java | 2 +- 263 files changed, 14889 insertions(+), 13341 deletions(-) create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicyActTaskSelectionLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicy_Act_TaskSelectionLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskSelectionLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskSelectionLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTask_TaskLogic.mvel create mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTaskTaskLogic.mvel delete mode 100644 examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTask_TaskLogic.mvel create mode 100644 examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java delete mode 100644 examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java create mode 100644 examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java delete mode 100644 examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicy_Decide_TaskSelectionLogic.java create mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask0TaskLogic.mvel delete mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask0_TaskLogic.mvel create mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask1TaskLogic.mvel delete mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask1_TaskLogic.mvel create mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask2TaskLogic.mvel delete mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask2_TaskLogic.mvel create mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask3TaskLogic.mvel delete mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask3_TaskLogic.mvel create mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask4TaskLogic.mvel delete mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask4_TaskLogic.mvel create mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask5TaskLogic.mvel delete mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask5_TaskLogic.mvel create mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask6TaskLogic.mvel delete mode 100644 examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask6_TaskLogic.mvel create mode 100644 model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParentLogicParentLocalNameLogicInstanceName.funkylogic delete mode 100644 model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParent_LogicParentLocalName_LogicInstanceName.funkylogic delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/EvalDomainModelFactory.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelFactory.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelSaver.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultState_Logic.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultTask_Logic.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalState_Logic.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalTask_Logic.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/package-info.java delete mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/package-info.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelFactory.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelSaver.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultStateLogic.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalStateLogic.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/package-info.java create mode 100644 testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/package-info.java delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultState_Logic.javascript delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultTask_Logic.javascript delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalState_Logic.javascript delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalTask_Logic.javascript delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultState_Logic.jruby delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultTask_Logic.jruby delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalState_Logic.jruby delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalTask_Logic.jruby delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultState_Logic.jython delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultTask_Logic.jython delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalState_Logic.jython delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalTask_Logic.jython delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultState_Logic.mvel delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultTask_Logic.mvel delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalState_Logic.mvel delete mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalTask_Logic.mvel create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultStateLogic.javascript create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultTaskLogic.javascript create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalStateLogic.javascript create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalTaskLogic.javascript create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultStateLogic.jruby create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultTaskLogic.jruby create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalStateLogic.jruby create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalTaskLogic.jruby create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultStateLogic.jython create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultTaskLogic.jython create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalStateLogic.jython create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalTaskLogic.jython create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultStateLogic.mvel create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultTaskLogic.mvel create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalStateLogic.mvel create mode 100644 testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalTaskLogic.mvel delete mode 100644 testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/plugins/context/test/locking/TestConcurrentContext.java create mode 100644 testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/testsuites/integration/context/TestConcurrentContext.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexActionListener.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngine.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJRuby.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJava.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJavascript.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJython.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMvel.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/event/TestEventInstantiation.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexModelExport.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexPolicyModelAnalysis.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyCreateModelFiles.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyDBWrite.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModel.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModelCreator.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateDifferentModels.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateModel.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexActionListener.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngine.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJRuby.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJava.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJavascript.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJython.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineMvel.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/event/TestEventInstantiation.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexModelExport.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexPolicyModelAnalysis.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyDbWrite.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModel.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModelCreator.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateDifferentModels.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateModel.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java delete mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java create mode 100644 testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexBaseBenchMarkTest.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexEngineBenchmark.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/TestApexEventListener.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/BaseTest.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMIMO.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMISO.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSIMO.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSISO.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventMIMO.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventSISO.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceModelUpdateTest.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceTest.java delete mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/utils/Utils.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexBaseBenchMarkTest.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexEngineBenchmark.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/TestApexEventListener.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/BaseTest.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMimo.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMiso.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSimo.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSiso.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventMimo.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventSiso.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceModelUpdateTest.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceTest.java create mode 100644 testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/utils/Utils.java delete mode 100644 testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/ConcurrentContextMetrics.java delete mode 100644 testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/package-info.java create mode 100644 testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/ConcurrentContextMetrics.java create mode 100644 testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/package-info.java delete mode 100644 testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/plugins/context/metrics/TestMetrics.java create mode 100644 testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/testsuites/performance/context/metrics/TestMetrics.java diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java index 7a34ce7c1..513f31e67 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java @@ -51,6 +51,9 @@ import org.onap.policy.apex.model.utilities.TreeMapUtils; * @author Liam Fallon (liam.fallon@ericsson.com) */ public class CommandLineEditorLoop { + // Recurring string constants + private static final String COMMAND = "command "; + // The model handler that is handling the API towards the Apex model being editied private final ApexModelHandler modelHandler; @@ -325,11 +328,11 @@ public class CommandLineEditorLoop { for (final Entry argument : getCommandArguments(commandWords)) { final List> foundArguments = TreeMapUtils .findMatchingEntries(argumentValues, argument.getKey()); - if (foundArguments.size() == 0) { - throw new CommandLineException("command " + stringAL2String(commandWords) + ": " + " argument \"" + if (foundArguments.isEmpty()) { + throw new CommandLineException(COMMAND + stringAL2String(commandWords) + ": " + " argument \"" + argument.getKey() + "\" not allowed on command"); } else if (foundArguments.size() > 1) { - throw new CommandLineException("command " + stringAL2String(commandWords) + ": " + " argument " + throw new CommandLineException(COMMAND + stringAL2String(commandWords) + ": " + " argument " + argument + " matches multiple arguments [" + argumentAL2String(foundArguments) + ']'); } @@ -343,7 +346,7 @@ public class CommandLineEditorLoop { // Argument values are null by default so if this argument is not nullable it is // mandatory if (!argumentValue.isSpecified() && !argumentValue.getCliArgument().isNullable()) { - throw new CommandLineException("command " + stringAL2String(commandWords) + ": " + throw new CommandLineException(COMMAND + stringAL2String(commandWords) + ": " + " mandatory argument \"" + argumentValue.getCliArgument().getArgumentName() + "\" not specified"); } diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRest.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRest.java index 1fb7a2259..0ebeec446 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRest.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRest.java @@ -59,14 +59,14 @@ public class ApexDeploymentRest { // Create a resource configuration that scans for JAX-RS resources and providers // in org.onap.policy.apex.client.deployment.rest package - final ResourceConfig rc = new ResourceConfig().packages(parameters.getRESTPackages()); + final ResourceConfig rc = new ResourceConfig().packages(parameters.getRestPackages()); // Add MultiPartFeature class for jersey-media-multipart rc.register(MultiPartFeature.class); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI - server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseURI(), rc); + server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseUri(), rc); // Add static content server.getServerConfiguration().addHttpHandler(new org.glassfish.grizzly.http.server.CLStaticHttpHandler( diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java index a0e6641db..73374053f 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java @@ -22,12 +22,21 @@ package org.onap.policy.apex.client.deployment.rest; import java.io.PrintStream; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + /** * The main class for ApexDeploymentRest. * * @author Michael Watkins (michael.watkins@ericsson.com) */ public class ApexDeploymentRestMain { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexDeploymentRestMain.class); + + // Recurring string constants + private static final String REST_ENDPOINT_PREFIX = "Apex Services REST endpoint ("; + // Services state public enum ServicesState { STOPPED, READY, INITIALIZING, RUNNING @@ -54,7 +63,7 @@ public class ApexDeploymentRestMain { final ApexDeploymentRestMain restMain = new ApexDeploymentRestMain(args, System.out); restMain.init(); } catch (final Exception e) { - System.err.println(e.getMessage()); + LOGGER.error("start failed", e); } } @@ -76,7 +85,7 @@ public class ApexDeploymentRestMain { parameters = parser.parse(args); } catch (final ApexDeploymentRestParameterException e) { throw new ApexDeploymentRestParameterException( - "Apex Services REST endpoint (" + this.toString() + ") parameter error, " + e.getMessage() + '\n' + REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n' + parser.getHelp(ApexDeploymentRestMain.class.getCanonicalName())); } @@ -89,7 +98,7 @@ public class ApexDeploymentRestMain { final String validationMessage = parameters.validate(); if (validationMessage.length() > 0) { throw new ApexDeploymentRestParameterException( - "Apex Services REST endpoint (" + this.toString() + ") parameters invalid, " + validationMessage + REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage + '\n' + parser.getHelp(ApexDeploymentRestMain.class.getCanonicalName())); } @@ -100,8 +109,8 @@ public class ApexDeploymentRestMain { * Initialize the rest service. */ public void init() { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") starting at " - + parameters.getBaseURI().toString() + " . . ."); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + + parameters.getBaseUri().toString() + " . . ."); try { state = ServicesState.INITIALIZING; @@ -115,10 +124,10 @@ public class ApexDeploymentRestMain { state = ServicesState.RUNNING; if (parameters.getTimeToLive() == ApexDeploymentRestParameters.INFINITY_TIME_TO_LIVE) { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") started at " - + parameters.getBaseURI().toString()); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at " + + parameters.getBaseUri().toString()); } else { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") started"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started"); } // Find out how long is left to wait @@ -134,7 +143,7 @@ public class ApexDeploymentRestMain { } } catch (final Exception e) { outStream.println( - "Apex Services REST endpoint (" + this.toString() + ") failed at with error: " + e.getMessage()); + REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage()); } finally { if (apexDeploymentRest != null) { apexDeploymentRest.shutdown(); @@ -167,11 +176,11 @@ public class ApexDeploymentRestMain { */ public void shutdown() { if (apexDeploymentRest != null) { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") shutting down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down"); apexDeploymentRest.shutdown(); } state = ServicesState.STOPPED; - outStream.println("Apex Services REST endpoint (" + this.toString() + ") shut down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down"); } /** diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameterParser.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameterParser.java index 564be435c..7e305788f 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameterParser.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameterParser.java @@ -81,7 +81,7 @@ public class ApexDeploymentRestParameterParser { } try { if (commandLine.hasOption('p')) { - parameters.setRESTPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); + parameters.setRestPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); } } catch (final ParseException e) { throw new ApexDeploymentRestParameterException("error parsing argument \"port\" :" + e.getMessage(), e); diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameters.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameters.java index af8cc5ab4..cadc3ef4e 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameters.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestParameters.java @@ -44,6 +44,11 @@ public class ApexDeploymentRestParameters { private int restPort = DEFAULT_REST_PORT; private long timeToLive = INFINITY_TIME_TO_LIVE; + /** + * Validate the parameters. + * + * @return the result of the validation + */ public String validate() { String validationMessage = ""; validationMessage += validatePort(); @@ -52,18 +57,38 @@ public class ApexDeploymentRestParameters { return validationMessage; } - public URI getBaseURI() { + /** + * Gets the base uri. + * + * @return the base uri + */ + public URI getBaseUri() { return URI.create(DEFAULT_SERVER_URI_ROOT + restPort + DEFAULT_REST_PATH); } - public String[] getRESTPackages() { + /** + * Gets the rest packages. + * + * @return the rest packages + */ + public String[] getRestPackages() { return DEFAULT_PACKAGES; } + /** + * Gets the static path. + * + * @return the static path + */ public String getStaticPath() { return DEFAULT_STATIC_PATH; } + /** + * Validate port. + * + * @return the string + */ private String validatePort() { if (restPort < 1024 || restPort > 65535) { return "port must be greater than 1023 and less than 65536\n"; @@ -72,6 +97,11 @@ public class ApexDeploymentRestParameters { } } + /** + * Validate time to live. + * + * @return the string + */ private String validateTimeToLive() { if (timeToLive < -1) { return "time to live must be greater than -1 (set to -1 to wait forever)\n"; @@ -80,34 +110,67 @@ public class ApexDeploymentRestParameters { } } + /** + * Checks if is help set. + * + * @return true, if is help set + */ public boolean isHelpSet() { return helpSet; } + /** + * Sets the help. + * + * @param helpSet the new help + */ public void setHelp(final boolean helpSet) { this.helpSet = helpSet; } - public int getRESTPort() { + /** + * Gets the rest port. + * + * @return the rest port + */ + public int getRestPort() { return restPort; } - public void setRESTPort(final int restPort) { + /** + * Sets the rest port. + * + * @param restPort the new rest port + */ + public void setRestPort(final int restPort) { this.restPort = restPort; } + /** + * Gets the time to live. + * + * @return the time to live + */ public long getTimeToLive() { return timeToLive; } + /** + * Sets the time to live. + * + * @param timeToLive the new time to live + */ public void setTimeToLive(final long timeToLive) { this.timeToLive = timeToLive; } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ @Override public String toString() { final StringBuilder ret = new StringBuilder(); - ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseURI()).append(", TTL=") + ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseUri()).append(", TTL=") .append(this.getTimeToLive()).append("sec"); return ret.toString(); } diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java index 18aae5001..d3a7d654a 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestResource.java @@ -59,11 +59,6 @@ public class ApexDeploymentRestResource { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexDeploymentRestResource.class); - /** - * Constructor, a new resource director is created for each request. - */ - public ApexDeploymentRestResource() {} - /** * Query the engine service for data. * diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditor.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditor.java index cb5e8f6b6..4ce73b750 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditor.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditor.java @@ -56,11 +56,11 @@ public class ApexEditor { // Create a resource configuration that scans for JAX-RS resources and providers // in org.onap.policy.apex.client.editor.rest package - final ResourceConfig rc = new ResourceConfig().packages(parameters.getRESTPackages()); + final ResourceConfig rc = new ResourceConfig().packages(parameters.getRestPackages()); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI - server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseURI(), rc); + server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseUri(), rc); // Add static content server.getServerConfiguration().addHttpHandler(new org.glassfish.grizzly.http.server.CLStaticHttpHandler( diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorMain.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorMain.java index 0fa8011c5..3f54467cd 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorMain.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorMain.java @@ -22,11 +22,20 @@ package org.onap.policy.apex.client.editor.rest; import java.io.PrintStream; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + /** * This class is the main class that is used to launch the Apex editor from the command line. * */ public class ApexEditorMain { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorMain.class); + + // Recurring string constants + private static final String REST_ENDPOINT_PREFIX = "Apex Editor REST endpoint ("; + /** * The Enum EditorState holds the current state of the editor. */ @@ -65,7 +74,7 @@ public class ApexEditorMain { final ApexEditorMain editorMain = new ApexEditorMain(args, System.out); editorMain.init(); } catch (final Exception e) { - System.err.println(e.getMessage()); + LOGGER.error("start failed", e); } } @@ -87,7 +96,7 @@ public class ApexEditorMain { parameters = parser.parse(args); } catch (final ApexEditorParameterException e) { throw new ApexEditorParameterException( - "Apex Editor REST endpoint (" + this.toString() + ") parameter error, " + e.getMessage() + '\n' + REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n' + parser.getHelp(ApexEditorMain.class.getCanonicalName())); } @@ -99,7 +108,7 @@ public class ApexEditorMain { final String validationMessage = parameters.validate(); if (validationMessage.length() > 0) { throw new ApexEditorParameterException( - "Apex Editor REST endpoint (" + this.toString() + ") parameters invalid, " + validationMessage + REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage + '\n' + parser.getHelp(ApexEditorMain.class.getCanonicalName())); } @@ -110,8 +119,8 @@ public class ApexEditorMain { * Initialize the Apex editor. */ public void init() { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") starting at " - + parameters.getBaseURI().toString() + " . . ."); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + + parameters.getBaseUri().toString() + " . . ."); try { state = EditorState.INITIALIZING; @@ -125,10 +134,10 @@ public class ApexEditorMain { state = EditorState.RUNNING; if (parameters.getTimeToLive() == ApexEditorParameters.INFINITY_TIME_TO_LIVE) { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") started at " - + parameters.getBaseURI().toString()); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at " + + parameters.getBaseUri().toString()); } else { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") started"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started"); } // Find out how long is left to wait @@ -144,7 +153,7 @@ public class ApexEditorMain { } } catch (final Exception e) { outStream.println( - "Apex Editor REST endpoint (" + this.toString() + ") failed at with error: " + e.getMessage()); + REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage()); } finally { if (apexEditor != null) { apexEditor.shutdown(); @@ -181,11 +190,11 @@ public class ApexEditorMain { */ public void shutdown() { if (apexEditor != null) { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") shutting down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down"); apexEditor.shutdown(); } state = EditorState.STOPPED; - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") shut down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down"); } /** diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameterParser.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameterParser.java index beb589dca..d67c6b1c6 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameterParser.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameterParser.java @@ -88,7 +88,7 @@ public class ApexEditorParameterParser { } try { if (commandLine.hasOption('p')) { - parameters.setRESTPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); + parameters.setRestPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); } } catch (final ParseException e) { throw new ApexEditorParameterException("error parsing argument \"port\" :" + e.getMessage(), e); diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameters.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameters.java index e0a2cf727..55d10c1a1 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameters.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorParameters.java @@ -75,7 +75,7 @@ public class ApexEditorParameters { * * @return the base URI */ - public URI getBaseURI() { + public URI getBaseUri() { return URI.create(DEFAULT_SERVER_URI_PREFIX + listenAddress + ':' + restPort + DEFAULT_REST_PATH); } @@ -84,7 +84,7 @@ public class ApexEditorParameters { * * @return the REST packages */ - public String[] getRESTPackages() { + public String[] getRestPackages() { return DEFAULT_PACKAGES; } @@ -117,7 +117,7 @@ public class ApexEditorParameters { */ private String validateUrl() { try { - new URI(getBaseURI().toString()).parseServerAuthority(); + new URI(getBaseUri().toString()).parseServerAuthority(); return ""; } catch (final URISyntaxException e) { return "listen address is not valid. " + e.getMessage() + "\n"; @@ -160,7 +160,7 @@ public class ApexEditorParameters { * * @return the REST port */ - public int getRESTPort() { + public int getRestPort() { return restPort; } @@ -169,7 +169,7 @@ public class ApexEditorParameters { * * @param incomingRestPort the REST port */ - public void setRESTPort(final int incomingRestPort) { + public void setRestPort(final int incomingRestPort) { this.restPort = incomingRestPort; } @@ -199,7 +199,7 @@ public class ApexEditorParameters { @Override public String toString() { final StringBuilder ret = new StringBuilder(); - ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseURI()).append(", TTL=") + ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseUri()).append(", TTL=") .append(this.getTimeToLive()).append("sec"); return ret.toString(); } diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorRestResource.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorRestResource.java index cd52035a5..8bed63d28 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorRestResource.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/ApexEditorRestResource.java @@ -70,40 +70,52 @@ import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** - * The class represents the root resource exposed at the base URL
- * The url to access this resource would be in the form {@code /rest//....}
- * For example: a PUT request to the following URL - * {@code http://localhost:8080/apex/rest/109/ContextSchema/Update}, with a JSON string payload - * containing the new {@code Schema} in the body, can be explained as: - *
    - *
  • The server or servlet is running at the base URL {@code http://localhost:8080/apex} - *
  • This resource {@code ApexRestEditorResource} is used because the path {@code rest/109} - * matches the {@code Path} filter specification for this Resource - * ({@code @Path("rest/{session}")}), where the {@code int} path parameter {@code session} is - * assigned the {@code int} value {@code 109} - *
  • The path {@code ContextSchema/Update} redirects this call to the method - * {@link #updateContextSchema(String)}, which should be a {@link javax.ws.rs.PUT}, with a single - * String in the body/payload which gets mapped to the single String parameter for the method. - *
  • So, in summary, the REST request updates a {@code ContextSchema} as specified in the payload - * for {@code session} number {@code 109} - *
+ * The class represents the root resource exposed at the base URL
The url to access this resource would be in the + * form {@code /rest//....}
For example: a PUT request to the following URL + * {@code http://localhost:8080/apex/rest/109/ContextSchema/Update}, with a JSON string payload containing the new + * {@code Schema} in the body, can be explained as:
  • The server or servlet is running at the base URL + * {@code http://localhost:8080/apex}
  • This resource {@code ApexRestEditorResource} is used because the path + * {@code rest/109} matches the {@code Path} filter specification for this Resource ({@code @Path("rest/{session}")}), + * where the {@code int} path parameter {@code session} is assigned the {@code int} value {@code 109}
  • The path + * {@code ContextSchema/Update} redirects this call to the method {@link #updateContextSchema(String)}, which should be + * a {@link javax.ws.rs.PUT}, with a single String in the body/payload which gets mapped to the single String parameter + * for the method.
  • So, in summary, the REST request updates a {@code ContextSchema} as specified in the payload for + * {@code session} number {@code 109}
* - * Note: An allocated {@code Session} identifier must be included in (almost) all requests. - * Models for different {@code Session} identifiers are completely isolated from one another. + * Note: An allocated {@code Session} identifier must be included in (almost) all requests. Models for different + * {@code Session} identifiers are completely isolated from one another. * - * Note: To create a new {@code Session}, and have a new session ID allocated use - * {@link javax.ws.rs.GET} request to {@code /rest/-1/Session/Create} (for example: - * {@code http://localhost:8080/apex/rest/-1/Session/Create} ) + * Note: To create a new {@code Session}, and have a new session ID allocated use {@link javax.ws.rs.GET} request + * to {@code /rest/-1/Session/Create} (for example: {@code http://localhost:8080/apex/rest/-1/Session/Create} ) * */ @Path("editor/{session}") -@Produces({MediaType.APPLICATION_JSON}) -@Consumes({MediaType.APPLICATION_JSON}) +@Produces( + { MediaType.APPLICATION_JSON }) +@Consumes( + { MediaType.APPLICATION_JSON }) public class ApexEditorRestResource { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorRestResource.class); + // Recurring string constants + private static final String IN_TASK = "\" in task "; + private static final String POLICY_STATE_CREATED_OTHER_ERROR = + "\". The policy and state were created, but there was an error adding the"; + private static final String IN_STATE = "\" in state \""; + private static final String POLICY_CREATED_STATE_ERROR = + "\". The policy was created, but there was an error adding the state."; + private static final String FOR_POLICY = "\" for policy \""; + private static final String NOT_OK = ": Not OK"; + private static final String TASK_PARTIALLY_DEFINED = " The task has only been partially defined."; + private static final String POLICY_PARTIALLY_DEFINED = " The policy has only been partially defined."; + private static final String POLICY_WAS_CREATED = "\". The policy was created, "; + private static final String VERSION = "version"; + private static final String POLICY_KEY = "policyKey"; + private static final String DESCRIPTION = "description"; + private static final String APEX_KEY_INFO = "apexKeyInfo"; + // The next session will have this number, stating at 0 private static int nextSession = 0; @@ -112,79 +124,77 @@ public class ApexEditorRestResource { // The ID of this session. This gets injected from the URL. @PathParam("session") - private int sessionID = -1; + private int sessionId = -1; // The Apex model for the session private ApexModel sessionApexModel = null; /** - * This method sets the Apex model for the current editor session. Don't forget to call - * {@link #commitChanges()} when finished! This makes requests atomic. + * This method sets the Apex model for the current editor session. Don't forget to call {@link #commitChanges()} + * when finished! This makes requests atomic. * * @return the result of finding the session Apex model and setting it */ private ApexApiResult initialiseSessionForChanges() { - if (sessionID < 0) { - return new ApexApiResult(Result.FAILED, "Session ID \"" + sessionID + "\" is negative"); + if (sessionId < 0) { + return new ApexApiResult(Result.FAILED, "Session ID \"" + sessionId + "\" is negative"); } - if (!SESSIONMODELMAP.containsKey(sessionID)) { - return new ApexApiResult(Result.FAILED, "A session with session ID \"" + sessionID + "\" does not exist"); + if (!SESSIONMODELMAP.containsKey(sessionId)) { + return new ApexApiResult(Result.FAILED, "A session with session ID \"" + sessionId + "\" does not exist"); } if (sessionApexModel == null) { - sessionApexModel = SESSIONMODELMAP.get(sessionID).clone(); + sessionApexModel = SESSIONMODELMAP.get(sessionId).clone(); } return new ApexApiResult(); } /** - * This method sets the Apex model for the current editor session. Don't make any changes to the - * model. + * This method sets the Apex model for the current editor session. Don't make any changes to the model. * * @return the result of finding the session Apex model and setting it */ private ApexApiResult initialiseSessionForReadOnly() { - if (sessionID < 0) { - return new ApexApiResult(Result.FAILED, "Session ID \"" + sessionID + "\" is negative"); + if (sessionId < 0) { + return new ApexApiResult(Result.FAILED, "Session ID \"" + sessionId + "\" is negative"); } - if (!SESSIONMODELMAP.containsKey(sessionID)) { - return new ApexApiResult(Result.FAILED, "A session with session ID \"" + sessionID + "\" does not exist"); + if (!SESSIONMODELMAP.containsKey(sessionId)) { + return new ApexApiResult(Result.FAILED, "A session with session ID \"" + sessionId + "\" does not exist"); } if (sessionApexModel == null) { - sessionApexModel = SESSIONMODELMAP.get(sessionID); + sessionApexModel = SESSIONMODELMAP.get(sessionId); } return new ApexApiResult(); } /** - * This method commits changes to the Apex model for the current editor session. This should - * only be called once, at the end of a successful change to the model for this session + * This method commits changes to the Apex model for the current editor session. This should only be called once, at + * the end of a successful change to the model for this session * * @return the result of committing the session Apex model */ private ApexApiResult commitChanges() { if (sessionApexModel == null) { - return new ApexApiResult(Result.FAILED, "Cannot commit a changes for Session ID \"" + sessionID - + "\", because it has not been initialised / started"); + return new ApexApiResult(Result.FAILED, "Cannot commit a changes for Session ID \"" + sessionId + + "\", because it has not been initialised / started"); } - SESSIONMODELMAP.put(sessionID, sessionApexModel); + SESSIONMODELMAP.put(sessionId, sessionApexModel); return new ApexApiResult(); } /** - * Creates a new session. Always call this method with sessionID -1, whereby a new sessionID - * will be allocated. If successful the new sessionID will be available in the first message in - * the result. + * Creates a new session. Always call this method with sessionID -1, whereby a new sessionID will be allocated. If + * successful the new sessionID will be available in the first message in the result. * - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}. - * This includes the session id for this session. + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}. This includes the session id + * for this session. */ @GET @Path("Session/Create") @@ -192,39 +202,39 @@ public class ApexEditorRestResource { ApexApiResult ret = null; LOGGER.entry(); try { - if (sessionID != -1) { - ret = new ApexApiResult(Result.FAILED, "Session ID must be set to -1 to create sessions: " + sessionID); + if (sessionId != -1) { + ret = new ApexApiResult(Result.FAILED, "Session ID must be set to -1 to create sessions: " + sessionId); return ret; } - final int newSessionID = nextSession; + final int newSessionId = nextSession; - if (SESSIONMODELMAP.containsKey(newSessionID)) { - ret = new ApexApiResult(Result.FAILED, "Session already exists for session: " + newSessionID); + if (SESSIONMODELMAP.containsKey(newSessionId)) { + ret = new ApexApiResult(Result.FAILED, "Session already exists for session: " + newSessionId); return ret; } - SESSIONMODELMAP.put(newSessionID, new ApexModelFactory().createApexModel(null, true)); - nextSession++; + SESSIONMODELMAP.put(newSessionId, new ApexModelFactory().createApexModel(null, true)); + incrementNextSession(); - ret = new ApexApiResult(Result.SUCCESS, Integer.toString(newSessionID)); + ret = new ApexApiResult(Result.SUCCESS, Integer.toString(newSessionId)); return ret; } catch (final Exception e) { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Session/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + String result = "Session/Create" + (ret != null && ret.isOk() ? ": OK" : NOT_OK); + LOGGER.exit(result); } } /** * Load the model from a JSON string for this session. * - * @param jsonString the JSON string to be parsed. The returned value(s) will be similar to - * {@link AxPolicyModel}, with merged {@linkplain AxKeyInfo} for the root object. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @param jsonString the JSON string to be parsed. The returned value(s) will be similar to {@link AxPolicyModel}, + * with merged {@linkplain AxKeyInfo} for the root object. + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @PUT @Path("/Model/Load") @@ -246,17 +256,17 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/Load" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + String result = "Model/Load" + (ret != null && ret.isOk() ? ": OK" : NOT_OK); + LOGGER.exit(result); } } /** - * Analyse the model and return analysis results. If successful the analysis results will be - * available in the messages in the result. + * Analyse the model and return analysis results. If successful the analysis results will be available in the + * messages in the result. * - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Model/Analyse") @@ -275,17 +285,16 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/Analyse" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Model/Analyse" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * Validate the model and return validation results. If successful the validation results will - * be available in the messages in the result. + * Validate the model and return validation results. If successful the validation results will be available in the + * messages in the result. * - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Model/Validate") @@ -306,18 +315,16 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/Validate" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Model/Validate" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** * Creates the new model model for this session. * - * @param jsonString the JSON string to be parsed containing the new model. See - * {@linkplain BeanModel} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @param jsonString the JSON string to be parsed containing the new model. See {@linkplain BeanModel} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @POST @Path("Model/Create") @@ -330,9 +337,9 @@ public class ApexEditorRestResource { return ret; } - final BeanModel jsonbean = RestUtils.getJSONParameters(jsonString, BeanModel.class); + final BeanModel jsonbean = RestUtils.getJsonParameters(jsonString, BeanModel.class); ret = sessionApexModel.createModel(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getUuid(), - jsonbean.getDescription()); + jsonbean.getDescription()); if (ret.isOk()) { ret = addKeyInfo2Messages(ret); @@ -345,18 +352,16 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Model/Create" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** * Update the model for this session. * - * @param jsonString the JSON string to be parsed containing the updated model. See - * {@linkplain BeanModel} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @param jsonString the JSON string to be parsed containing the updated model. See {@linkplain BeanModel} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @PUT @Path("Model/Update") @@ -369,9 +374,9 @@ public class ApexEditorRestResource { return ret; } - final BeanModel jsonbean = RestUtils.getJSONParameters(jsonString, BeanModel.class); + final BeanModel jsonbean = RestUtils.getJsonParameters(jsonString, BeanModel.class); ret = sessionApexModel.updateModel(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getUuid(), - jsonbean.getDescription()); + jsonbean.getDescription()); if (ret.isOk()) { commitChanges(); } @@ -380,17 +385,16 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Model/Update" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * Gets the key for the model for this session. If successful the model key will be available in - * the first message in the result. See {@linkplain AxKey} + * Gets the key for the model for this session. If successful the model key will be available in the first message + * in the result. See {@linkplain AxKey} * - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Model/GetKey") @@ -409,18 +413,17 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/GetKey" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Model/GetKey" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * Retrieve the model for this session. If successful the model will be available in the first - * message in the result. The returned value will be similar to a {@link AxPolicyModel}, with - * merged {@linkplain AxKeyInfo} for the root object. + * Retrieve the model for this session. If successful the model will be available in the first message in the + * result. The returned value will be similar to a {@link AxPolicyModel}, with merged {@linkplain AxKeyInfo} for the + * root object. * - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Model/Get") @@ -444,8 +447,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Model/Get" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -476,18 +478,16 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - if (ret != null) { - LOGGER.exit(ret.isOk()); - } - LOGGER.info("Model/Download" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + String result = "Model/Download" + (ret != null && ret.isOk() ? ": OK" : NOT_OK); + LOGGER.exit(result); } } /** * Delete the model for this session. * - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @DELETE @Path("Model/Delete") @@ -509,24 +509,23 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Model/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Model/Delete" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * List key information with the given key names/versions. If successful the result(s) will be - * available in the result messages. See {@linkplain AxKeyInfo} + * List key information with the given key names/versions. If successful the result(s) will be available in the + * result messages. See {@linkplain AxKeyInfo} * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("KeyInformation/Get") public ApexApiResult listKeyInformation(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -550,8 +549,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("KeyInformation/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("KeyInformation/Get" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -559,8 +557,8 @@ public class ApexEditorRestResource { * Creates a context schema with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextSchema} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @POST @Path("ContextSchema/Create") @@ -573,10 +571,10 @@ public class ApexEditorRestResource { return ret; } - final BeanContextSchema jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextSchema.class); + final BeanContextSchema jsonbean = RestUtils.getJsonParameters(jsonString, BeanContextSchema.class); ret = sessionApexModel.createContextSchema(jsonbean.getName(), jsonbean.getVersion(), - jsonbean.getSchemaFlavour(), jsonbean.getSchemaDefinition(), jsonbean.getUuid(), - jsonbean.getDescription()); + jsonbean.getSchemaFlavour(), jsonbean.getSchemaDefinition(), jsonbean.getUuid(), + jsonbean.getDescription()); if (ret.isOk()) { commitChanges(); } @@ -585,8 +583,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextSchema/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextSchema/Create" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -594,8 +591,8 @@ public class ApexEditorRestResource { * Update a context schema with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextSchema} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @PUT @Path("ContextSchema/Update") @@ -608,11 +605,11 @@ public class ApexEditorRestResource { return ret; } - final BeanContextSchema jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextSchema.class); + final BeanContextSchema jsonbean = RestUtils.getJsonParameters(jsonString, BeanContextSchema.class); ret = sessionApexModel.updateContextSchema(jsonbean.getName(), jsonbean.getVersion(), - jsonbean.getSchemaFlavour(), jsonbean.getSchemaDefinition(), jsonbean.getUuid(), - jsonbean.getDescription()); + jsonbean.getSchemaFlavour(), jsonbean.getSchemaDefinition(), jsonbean.getUuid(), + jsonbean.getDescription()); if (ret.isOk()) { commitChanges(); } @@ -621,25 +618,24 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextSchema/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextSchema/Update" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * List context schemas with the given key names/versions. If successful the result(s) will be - * available in the result messages. The returned value(s) will be similar to - * {@link AxContextSchema}, with merged {@linkplain AxKeyInfo} for the root object. + * List context schemas with the given key names/versions. If successful the result(s) will be available in the + * result messages. The returned value(s) will be similar to {@link AxContextSchema}, with merged + * {@linkplain AxKeyInfo} for the root object. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("ContextSchema/Get") public ApexApiResult listContextSchemas(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -668,8 +664,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextSchema/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextSchema/Get" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -678,13 +673,13 @@ public class ApexEditorRestResource { * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @DELETE @Path("ContextSchema/Delete") public ApexApiResult deleteContextSchema(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -711,24 +706,23 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextSchema/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextSchema/Delete" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * Validate context schemas with the given key names/versions. The result(s) will be available - * in the result messages. + * Validate context schemas with the given key names/versions. The result(s) will be available in the result + * messages. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Validate/ContextSchema") public ApexApiResult validateContextSchemas(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -757,8 +751,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Validate/ContextSchema" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Validate/ContextSchema" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -766,8 +759,8 @@ public class ApexEditorRestResource { * Creates a context album with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextAlbum} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @POST @Path("ContextAlbum/Create") @@ -780,11 +773,11 @@ public class ApexEditorRestResource { return ret; } - final BeanContextAlbum jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextAlbum.class); + final BeanContextAlbum jsonbean = RestUtils.getJsonParameters(jsonString, BeanContextAlbum.class); ret = sessionApexModel.createContextAlbum(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getScope(), - Boolean.toString(jsonbean.getWriteable()), jsonbean.getItemSchema().getName(), - jsonbean.getItemSchema().getVersion(), jsonbean.getUuid(), jsonbean.getDescription()); + Boolean.toString(jsonbean.getWriteable()), jsonbean.getItemSchema().getName(), + jsonbean.getItemSchema().getVersion(), jsonbean.getUuid(), jsonbean.getDescription()); if (ret.isOk()) { commitChanges(); } @@ -793,8 +786,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextAlbum/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextAlbum/Create" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -802,8 +794,8 @@ public class ApexEditorRestResource { * Update a context album with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextAlbum} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @PUT @Path("ContextAlbum/Update") @@ -816,11 +808,11 @@ public class ApexEditorRestResource { return ret; } - final BeanContextAlbum jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextAlbum.class); + final BeanContextAlbum jsonbean = RestUtils.getJsonParameters(jsonString, BeanContextAlbum.class); ret = sessionApexModel.updateContextAlbum(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getScope(), - Boolean.toString(jsonbean.getWriteable()), jsonbean.getItemSchema().getName(), - jsonbean.getItemSchema().getVersion(), jsonbean.getUuid(), jsonbean.getDescription()); + Boolean.toString(jsonbean.getWriteable()), jsonbean.getItemSchema().getName(), + jsonbean.getItemSchema().getVersion(), jsonbean.getUuid(), jsonbean.getDescription()); if (ret.isOk()) { commitChanges(); } @@ -829,25 +821,24 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextAlbum/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextAlbum/Update" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * List context albums with the given key names/versions. If successful the result(s) will be - * available in the result messages. The returned value(s) will be similar to - * {@link AxContextAlbum}, with merged {@linkplain AxKeyInfo} for the root object. + * List context albums with the given key names/versions. If successful the result(s) will be available in the + * result messages. The returned value(s) will be similar to {@link AxContextAlbum}, with merged + * {@linkplain AxKeyInfo} for the root object. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("ContextAlbum/Get") public ApexApiResult listContextAlbums(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -876,8 +867,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextAlbum/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextAlbum/Get" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -886,13 +876,13 @@ public class ApexEditorRestResource { * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @DELETE @Path("ContextAlbum/Delete") public ApexApiResult deleteContextAlbum(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -919,24 +909,23 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("ContextAlbum/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("ContextAlbum/Delete" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * Validate context albums with the given key names/versions. The result(s) will be available in - * the result messages. + * Validate context albums with the given key names/versions. The result(s) will be available in the result + * messages. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Validate/ContextAlbum") public ApexApiResult validateContextAlbums(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -965,8 +954,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Validate/ContextAlbum" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Validate/ContextAlbum" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -974,8 +962,8 @@ public class ApexEditorRestResource { * Creates an event with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanEvent} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @POST @Path("Event/Create") @@ -988,10 +976,10 @@ public class ApexEditorRestResource { return ret; } - final BeanEvent jsonbean = RestUtils.getJSONParameters(jsonString, BeanEvent.class); + final BeanEvent jsonbean = RestUtils.getJsonParameters(jsonString, BeanEvent.class); ret = sessionApexModel.createEvent(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getNameSpace(), - jsonbean.getSource(), jsonbean.getTarget(), jsonbean.getUuid(), jsonbean.getDescription()); + jsonbean.getSource(), jsonbean.getTarget(), jsonbean.getUuid(), jsonbean.getDescription()); if (ret.isNok()) { return ret; } @@ -999,19 +987,19 @@ public class ApexEditorRestResource { for (final Entry p : jsonbean.getParameters().entrySet()) { if (p.getValue() == null) { ret = new ApexApiResult(Result.FAILED, "Null event parameter information for parameter \"" - + p.getKey() + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The event was created, but there was an error adding the event parameters." - + " The event has only been partially defined."); + + p.getKey() + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The event was created, but there was an error adding the event parameters." + + " The event has only been partially defined."); return ret; } - final ApexApiResult rettmp = - sessionApexModel.createEventPar(jsonbean.getName(), jsonbean.getVersion(), p.getKey(), - p.getValue().getName(), p.getValue().getVersion(), p.getValue().getOptional()); + final ApexApiResult rettmp = sessionApexModel.createEventPar(jsonbean.getName(), + jsonbean.getVersion(), p.getKey(), p.getValue().getName(), + p.getValue().getVersion(), p.getValue().getOptional()); if (rettmp.isNok()) { rettmp.addMessage("Failed to add event parameter information for parameter \"" + p.getKey() - + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The event was created, but there was an error adding the event parameters." - + " The event has only been partially defined."); + + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The event was created, but there was an error adding the event parameters." + + " The event has only been partially defined."); ret = rettmp; return ret; } @@ -1025,8 +1013,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Event/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Event/Create" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -1034,8 +1021,8 @@ public class ApexEditorRestResource { * Update an event with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanEvent} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @PUT @Path("Event/Update") @@ -1048,12 +1035,12 @@ public class ApexEditorRestResource { return ret; } - final BeanEvent jsonbean = RestUtils.getJSONParameters(jsonString, BeanEvent.class); + final BeanEvent jsonbean = RestUtils.getJsonParameters(jsonString, BeanEvent.class); if (jsonbean.getName() == null || jsonbean.getName().equals("") || jsonbean.getVersion() == null - || jsonbean.getVersion().equals("")) { + || jsonbean.getVersion().equals("")) { ret = new ApexApiResult(Result.FAILED, "Null/Empty event name/version (\"" + jsonbean.getName() + ":" - + jsonbean.getVersion() + "\" passed to UpdateEvent"); + + jsonbean.getVersion() + "\" passed to UpdateEvent"); return ret; } @@ -1071,24 +1058,23 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Event/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Event/Update" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * List events with the given key names/versions. If successful the result(s) will be available - * in the result messages. The returned value(s) will be similar to {@link AxEvent}, with merged - * {@linkplain AxKeyInfo} for the root object. + * List events with the given key names/versions. If successful the result(s) will be available in the result + * messages. The returned value(s) will be similar to {@link AxEvent}, with merged {@linkplain AxKeyInfo} for the + * root object. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Event/Get") - public ApexApiResult listEvent(@QueryParam("name") final String name, @QueryParam("version") final String version) { + public ApexApiResult listEvent(@QueryParam("name") final String name, @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1117,8 +1103,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Event/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Event/Get" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -1127,13 +1112,13 @@ public class ApexEditorRestResource { * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @DELETE @Path("Event/Delete") public ApexApiResult deleteEvent(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1160,24 +1145,22 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Event/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Event/Delete" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * Validate events with the given key names/versions. The result(s) will be available in the - * result messages. + * Validate events with the given key names/versions. The result(s) will be available in the result messages. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Validate/Event") public ApexApiResult validateEvent(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1206,8 +1189,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Validate/Event" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Validate/Event" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -1215,8 +1197,8 @@ public class ApexEditorRestResource { * Creates a task with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @POST @Path("Task/Create") @@ -1230,10 +1212,10 @@ public class ApexEditorRestResource { return ret; } - final BeanTask jsonbean = RestUtils.getJSONParameters(jsonString, BeanTask.class); + final BeanTask jsonbean = RestUtils.getJsonParameters(jsonString, BeanTask.class); ret = sessionApexModel.createTask(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getUuid(), - jsonbean.getDescription()); + jsonbean.getDescription()); if (ret.isNok()) { return ret; } @@ -1241,28 +1223,28 @@ public class ApexEditorRestResource { for (final Entry fin : jsonbean.getInputFields().entrySet()) { if (fin.getValue() == null) { ret = new ApexApiResult(Result.FAILED, "Null task input field information for field \"" - + fin.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The task was created, but there was an error adding the input fields." - + " The task has only been partially defined."); + + fin.getKey() + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, but there was an error adding the input fields." + + TASK_PARTIALLY_DEFINED); return ret; } if (fin.getKey() == null || !fin.getKey().equals(fin.getValue().getLocalName())) { ret = new ApexApiResult(Result.FAILED, "Invalid task input field information for field \"" - + fin.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The localName of the field (\"" + fin.getValue().getLocalName() - + "\") is not the same as the field name. " - + "The task was created, but there was an error adding the input fields." - + " The task has only been partially defined."); + + fin.getKey() + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The localName of the field (\"" + fin.getValue().getLocalName() + + "\") is not the same as the field name. " + + "The task was created, but there was an error adding the input fields." + + TASK_PARTIALLY_DEFINED); return ret; } tempres = sessionApexModel.createTaskInputField(jsonbean.getName(), jsonbean.getVersion(), - fin.getKey(), fin.getValue().getName(), fin.getValue().getVersion(), - fin.getValue().getOptional()); + fin.getKey(), fin.getValue().getName(), fin.getValue().getVersion(), + fin.getValue().getOptional()); if (tempres.isNok()) { tempres.addMessage("Failed to add task input field information for field \"" + fin.getKey() - + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The task was created, but there was an error adding the input fields." - + " The task has only been partially defined."); + + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, but there was an error adding the input fields." + + TASK_PARTIALLY_DEFINED); ret = tempres; return ret; } @@ -1272,28 +1254,28 @@ public class ApexEditorRestResource { for (final Entry fout : jsonbean.getOutputFields().entrySet()) { if (fout.getValue() == null) { ret = new ApexApiResult(Result.FAILED, "Null task output field information for field \"" - + fout.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The task was created, but there was an error adding the output fields." - + " The task has only been partially defined."); + + fout.getKey() + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, but there was an error adding the output fields." + + TASK_PARTIALLY_DEFINED); return ret; } if (fout.getKey() == null || !fout.getKey().equals(fout.getValue().getLocalName())) { ret = new ApexApiResult(Result.FAILED, "Invalid task output field information for field \"" - + fout.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The localName of the field (\"" + fout.getValue().getLocalName() - + "\") is not the same as the field name. " - + "The task was created, but there was an error adding the output fields." - + " The task has only been partially defined."); + + fout.getKey() + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The localName of the field (\"" + fout.getValue().getLocalName() + + "\") is not the same as the field name. " + + "The task was created, but there was an error adding the output fields." + + TASK_PARTIALLY_DEFINED); return ret; } tempres = sessionApexModel.createTaskOutputField(jsonbean.getName(), jsonbean.getVersion(), - fout.getKey(), fout.getValue().getName(), fout.getValue().getVersion(), - fout.getValue().getOptional()); + fout.getKey(), fout.getValue().getName(), fout.getValue().getVersion(), + fout.getValue().getOptional()); if (tempres.isNok()) { tempres.addMessage("Failed to add task output field information for field \"" + fout.getKey() - + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The task was created, but there was an error adding the output fields." - + " The task has only been partially defined."); + + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, but there was an error adding the output fields." + + TASK_PARTIALLY_DEFINED); ret = tempres; return ret; } @@ -1302,12 +1284,12 @@ public class ApexEditorRestResource { if (jsonbean.getTaskLogic() != null) { final BeanLogic logic = jsonbean.getTaskLogic(); tempres = sessionApexModel.createTaskLogic(jsonbean.getName(), jsonbean.getVersion(), - logic.getLogicFlavour(), logic.getLogic()); + logic.getLogicFlavour(), logic.getLogic()); if (tempres.isNok()) { tempres.addMessage("Failed to add task logic in task " + jsonbean.getName() + ":" - + jsonbean.getVersion() - + ". The task was created, but there was an error adding the logic." - + " The task has only been partially defined."); + + jsonbean.getVersion() + + ". The task was created, but there was an error adding the logic." + + TASK_PARTIALLY_DEFINED); ret = tempres; return ret; } @@ -1315,21 +1297,22 @@ public class ApexEditorRestResource { if (jsonbean.getParameters() != null) { for (final Entry param : jsonbean.getParameters().entrySet()) { if (param.getKey() == null || param.getValue() == null - || !param.getKey().equals(param.getValue().getParameterName())) { + || !param.getKey().equals(param.getValue().getParameterName())) { ret = new ApexApiResult(Result.FAILED, - "Null or invalid task parameter information for parameter \"" + param.getKey() - + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The task was created, but there was an error adding the parameters." - + " The task has only been partially defined."); + "Null or invalid task parameter information for parameter \"" + param.getKey() + + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, " + + "but there was an error adding the parameters." + + TASK_PARTIALLY_DEFINED); return ret; } tempres = sessionApexModel.createTaskParameter(jsonbean.getName(), jsonbean.getVersion(), - param.getValue().getParameterName(), param.getValue().getDefaultValue()); + param.getValue().getParameterName(), param.getValue().getDefaultValue()); if (tempres.isNok()) { - tempres.addMessage("Failed to add task parameter \"" + param.getKey() + "\" in task " - + jsonbean.getName() + ":" + jsonbean.getVersion() - + ". The task was created, but there was an error adding the parameters." - + " The task has only been partially defined."); + tempres.addMessage("Failed to add task parameter \"" + param.getKey() + IN_TASK + + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, but there was an error adding the parameters." + + TASK_PARTIALLY_DEFINED); ret = tempres; return ret; } @@ -1339,20 +1322,22 @@ public class ApexEditorRestResource { for (final BeanKeyRef contextalbum : jsonbean.getContexts()) { if (contextalbum.getName() == null || contextalbum.getVersion() == null) { ret = new ApexApiResult(Result.FAILED, - "Null or invalid context album reference information in task " + jsonbean.getName() - + ":" + jsonbean.getVersion() - + ". The task was created, but there was an error adding the" - + " context album reference. The task has only been partially defined."); + "Null or invalid context album reference information in task " + + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, but there was an error adding the" + + " context album reference. " + + "The task has only been partially defined."); return ret; } tempres = sessionApexModel.createTaskContextRef(jsonbean.getName(), jsonbean.getVersion(), - contextalbum.getName(), contextalbum.getVersion()); + contextalbum.getName(), contextalbum.getVersion()); if (tempres.isNok()) { ret = new ApexApiResult(Result.FAILED, - "Failed to add context album reference information in task " + jsonbean.getName() + ":" - + jsonbean.getVersion() - + ". The task was created, but there was an error adding the" - + " context album reference. The task has only been partially defined."); + "Failed to add context album reference information in task " + + jsonbean.getName() + ":" + jsonbean.getVersion() + + ". The task was created, but there was an error adding the" + + " context album reference. " + + "The task has only been partially defined."); return ret; } } @@ -1365,8 +1350,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Task/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Task/Create" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -1374,8 +1358,8 @@ public class ApexEditorRestResource { * Update a task with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @PUT @Path("Task/Update") @@ -1388,12 +1372,12 @@ public class ApexEditorRestResource { return ret; } - final BeanTask jsonbean = RestUtils.getJSONParameters(jsonString, BeanTask.class); + final BeanTask jsonbean = RestUtils.getJsonParameters(jsonString, BeanTask.class); if (jsonbean.getName() == null || jsonbean.getName().equals("") || jsonbean.getVersion() == null - || jsonbean.getVersion().equals("")) { + || jsonbean.getVersion().equals("")) { ret = new ApexApiResult(Result.FAILED, "Null/Empty task name/version (\"" + jsonbean.getName() + ":" - + jsonbean.getVersion() + "\" passed to UpdateTask"); + + jsonbean.getVersion() + "\" passed to UpdateTask"); return ret; } @@ -1411,24 +1395,23 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Task/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Task/Update" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * List tasks with the given key names/versions. If successful the result(s) will be available - * in the result messages. The returned value(s) will be similar to {@link AxTask}, with merged - * {@linkplain AxKeyInfo} for the root object. + * List tasks with the given key names/versions. If successful the result(s) will be available in the result + * messages. The returned value(s) will be similar to {@link AxTask}, with merged {@linkplain AxKeyInfo} for the + * root object. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Task/Get") - public ApexApiResult listTask(@QueryParam("name") final String name, @QueryParam("version") final String version) { + public ApexApiResult listTask(@QueryParam("name") final String name, @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1457,8 +1440,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Task/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Task/Get" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -1467,13 +1449,13 @@ public class ApexEditorRestResource { * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @DELETE @Path("Task/Delete") public ApexApiResult deleteTask(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1503,24 +1485,22 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Task/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Task/Delete" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * Validate tasks with the given key names/versions. The result(s) will be available in the - * result messages. + * Validate tasks with the given key names/versions. The result(s) will be available in the result messages. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Validate/Task") public ApexApiResult validateTask(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1549,8 +1529,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Validate/Task" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Validate/Task" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -1559,8 +1538,8 @@ public class ApexEditorRestResource { * Creates a policy with the information in the JSON string passed. * * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @POST @Path("Policy/Create") @@ -1575,21 +1554,22 @@ public class ApexEditorRestResource { return ret; } - final BeanPolicy jsonbean = RestUtils.getJSONParameters(jsonString, BeanPolicy.class); + final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class); final String policyname = jsonbean.getName(); final String policyversion = jsonbean.getVersion(); ret = sessionApexModel.createPolicy(policyname, policyversion, jsonbean.getTemplate(), - jsonbean.getFirstState(), jsonbean.getUuid(), jsonbean.getDescription()); + jsonbean.getFirstState(), jsonbean.getUuid(), jsonbean.getDescription()); if (ret.isNok()) { return ret; } if (jsonbean.getStates() == null || jsonbean.getStates().isEmpty()) { - ret = new ApexApiResult(Result.FAILED, "Null or empty state map; no states defined for policy \"" - + policyname + ":" + policyversion - + "\". The policy was created, but there was an error adding states." - + " The policy has only been partially defined."); + ret = new ApexApiResult(Result.FAILED, + "Null or empty state map; no states defined for policy \"" + policyname + ":" + + policyversion + + "\". The policy was created, but there was an error adding states." + + POLICY_PARTIALLY_DEFINED); return ret; } @@ -1599,29 +1579,29 @@ public class ApexEditorRestResource { final String statename = e.getKey(); final BeanState state = e.getValue(); if (state == null) { - ret = new ApexApiResult(Result.FAILED, "Null or invalid state information for state \"" + statename - + "\" for policy \"" + policyname + ":" + policyversion - + "\". The policy was created, but there was an error adding the state." - + " The policy has only been partially defined."); + ret = new ApexApiResult(Result.FAILED, + "Null or invalid state information for state \"" + statename + FOR_POLICY + + policyname + ":" + policyversion + POLICY_CREATED_STATE_ERROR + + POLICY_PARTIALLY_DEFINED); return ret; } if (state.getTrigger() == null) { - ret = new ApexApiResult(Result.FAILED, "Null or invalid state trigger for state \"" + statename - + "\" for policy \"" + policyname + ":" + policyversion - + "\". The policy was created, but there was an error adding the state." - + " The policy has only been partially defined."); + ret = new ApexApiResult(Result.FAILED, + "Null or invalid state trigger for state \"" + statename + FOR_POLICY + policyname + + ":" + policyversion + POLICY_CREATED_STATE_ERROR + + POLICY_PARTIALLY_DEFINED); return ret; } if (state.getDefaultTask() == null) { - ret = new ApexApiResult(Result.FAILED, "Null or invalid default task for state \"" + statename - + "\" for policy \"" + policyname + ":" + policyversion - + "\". The policy was created, but there was an error adding the state." - + " The policy has only been partially defined."); + ret = new ApexApiResult(Result.FAILED, + "Null or invalid default task for state \"" + statename + FOR_POLICY + policyname + + ":" + policyversion + POLICY_CREATED_STATE_ERROR + + POLICY_PARTIALLY_DEFINED); return ret; } tempres = sessionApexModel.createPolicyState(policyname, policyversion, statename, - state.getTrigger().getName(), state.getTrigger().getVersion(), state.getDefaultTask().getName(), - state.getDefaultTask().getVersion()); + state.getTrigger().getName(), state.getTrigger().getVersion(), + state.getDefaultTask().getName(), state.getDefaultTask().getVersion()); if (tempres.isNok()) { ret = tempres; return ret; @@ -1635,12 +1615,13 @@ public class ApexEditorRestResource { final BeanLogic tsl = state.getTaskSelectionLogic(); if (tsl != null) { tempres = sessionApexModel.createPolicyStateTaskSelectionLogic(policyname, policyversion, statename, - tsl.getLogicFlavour(), tsl.getLogic()); + tsl.getLogicFlavour(), tsl.getLogic()); if (tempres.isNok()) { tempres.addMessage("Failed to add task selection logic for state \"" + statename + "\" for" - + " policy \"" + policyname + ":" + policyversion - + "\". The policy was created, but there was an error adding the task selection logic " - + "for the state. The policy has only been partially defined."); + + " policy \"" + policyname + ":" + policyversion + + POLICY_WAS_CREATED + + "but there was an error adding the task selection logic " + + "for the state. The policy has only been partially defined."); ret = tempres; return ret; } @@ -1650,20 +1631,20 @@ public class ApexEditorRestResource { if (contexts != null) { for (final BeanKeyRef c : contexts) { if (c == null) { - ret = new ApexApiResult(Result.FAILED, - "Null or invalid context reference \"" + c + "\" for" + " state \"" + statename - + "\" for policy \"" + policyname + ":" + policyversion + ret = new ApexApiResult(Result.FAILED, "Null or invalid context reference \"" + c + "\" for" + + " state \"" + statename + FOR_POLICY + policyname + ":" + policyversion + "\". The policy was created, but there was an error adding the context " + "reference for the state. The policy has only been partially defined."); return ret; } tempres = sessionApexModel.createPolicyStateContextRef(policyname, policyversion, statename, - c.getName(), c.getVersion()); + c.getName(), c.getVersion()); if (tempres.isNok()) { tempres.addMessage("Failed to add context reference \"" + c + "\" for state \"" + statename - + "\" for policy \"" + policyname + ":" + policyversion - + "\". The policy was created, but there was an error adding the context reference " - + "for the state. The policy has only been partially defined."); + + FOR_POLICY + policyname + ":" + policyversion + + POLICY_WAS_CREATED + + "but there was an error adding the context reference " + + "for the state. The policy has only been partially defined."); ret = tempres; return ret; } @@ -1677,21 +1658,21 @@ public class ApexEditorRestResource { final BeanLogic finalizer = f.getValue(); if (finalizername == null || finalizer == null) { ret = new ApexApiResult(Result.FAILED, - "Null or invalid finalizer information for finalizer " + "named \"" + finalizername - + "\" in state \"" + statename + "\" for policy \"" + policyname + ":" - + policyversion - + "\". The policy and state were created, but there was an error adding the" - + " finalizer. The policy has only been partially defined."); + "Null or invalid finalizer information for finalizer " + "named \"" + + finalizername + IN_STATE + statename + FOR_POLICY + + policyname + ":" + policyversion + + POLICY_STATE_CREATED_OTHER_ERROR + + " finalizer. The policy has only " + + "been partially defined."); return ret; } tempres = sessionApexModel.createPolicyStateFinalizerLogic(policyname, policyversion, statename, - finalizername, finalizer.getLogicFlavour(), finalizer.getLogic()); + finalizername, finalizer.getLogicFlavour(), finalizer.getLogic()); if (tempres.isNok()) { tempres.addMessage("Failed to add finalizer information for finalizer named \"" - + finalizername + "\" in" + " state \"" + statename + "\" for policy \"" - + policyname + ":" + policyversion - + "\". The policy and state were created, but there was an error adding the" - + " finalizer. The policy has only been partially defined."); + + finalizername + "\" in" + " state \"" + statename + FOR_POLICY + + policyname + ":" + policyversion + POLICY_STATE_CREATED_OTHER_ERROR + + " finalizer. The policy has only been partially defined."); ret = tempres; return ret; } @@ -1699,9 +1680,8 @@ public class ApexEditorRestResource { } final Map outputs = state.getStateOutputs(); if (outputs == null || outputs.isEmpty()) { - ret = new ApexApiResult(Result.FAILED, - "No state outputs have been defined in state \"" + statename + "\" for policy \"" - + policyname + ":" + policyversion + ret = new ApexApiResult(Result.FAILED, "No state outputs have been defined in state \"" + statename + + FOR_POLICY + policyname + ":" + policyversion + "\". The policy and state were created, but there was an error adding state" + " outputs. The policy has only been partially defined."); return ret; @@ -1711,19 +1691,19 @@ public class ApexEditorRestResource { final BeanStateOutput output = o.getValue(); if (outputname == null || output == null || output.getEvent() == null) { ret = new ApexApiResult(Result.FAILED, - "Null or invalid output information for output named \"" + outputname + "\" in state \"" - + statename + "\" for policy \"" + policyname + ":" + policyversion - + "\". The policy and state were created, but there was an error adding the" - + " output. The policy has only been partially defined."); + "Null or invalid output information for output named \"" + outputname + IN_STATE + + statename + FOR_POLICY + policyname + ":" + policyversion + + POLICY_STATE_CREATED_OTHER_ERROR + + " output. The policy has only been partially defined."); return ret; } tempres = sessionApexModel.createPolicyStateOutput(policyname, policyversion, statename, outputname, - output.getEvent().getName(), output.getEvent().getVersion(), output.getNextState()); + output.getEvent().getName(), output.getEvent().getVersion(), output.getNextState()); if (tempres.isNok()) { tempres.addMessage("Failed to add output information for output named \"" + outputname - + "\" in state \"" + statename + "\" for policy \"" + policyname + ":" + policyversion - + "\". The policy and state were created, but there was an error adding the output." - + " The policy has only been partially defined."); + + IN_STATE + statename + FOR_POLICY + policyname + ":" + policyversion + + "\". The policy and state were created, " + + "but there was an error adding the output." + POLICY_PARTIALLY_DEFINED); ret = tempres; return ret; } @@ -1731,32 +1711,31 @@ public class ApexEditorRestResource { final Map taskmap = state.getTasks(); if (taskmap == null || taskmap.isEmpty()) { - ret = new ApexApiResult(Result.FAILED, - "No tasks have been defined in state \"" + statename + "\" for policy \"" + policyname + ":" - + policyversion + ret = new ApexApiResult(Result.FAILED, "No tasks have been defined in state \"" + statename + + FOR_POLICY + policyname + ":" + policyversion + "\". The policy and state were created, but there was an error adding tasks." - + " The policy has only been partially defined."); + + POLICY_PARTIALLY_DEFINED); return ret; } for (final Map.Entry t : taskmap.entrySet()) { final String tasklocalname = t.getKey(); final BeanStateTaskRef taskref = t.getValue(); if (tasklocalname == null || taskref == null || taskref.getTask() == null) { - ret = new ApexApiResult(Result.FAILED, - "Null or invalid task information for task named \"" + tasklocalname + "\" in state \"" - + statename + "\" for for policy \"" + policyname + ":" + policyversion + ret = new ApexApiResult(Result.FAILED, "Null or invalid task information for task named \"" + + tasklocalname + IN_STATE + statename + "\" for for policy \"" + policyname + + ":" + policyversion + "\". The policy and state were created, but there was an error adding the " + "task. The policy has only been partially defined."); return ret; } tempres = sessionApexModel.createPolicyStateTaskRef(policyname, policyversion, statename, - tasklocalname, taskref.getTask().getName(), taskref.getTask().getVersion(), - taskref.getOutputType(), taskref.getOutputName()); + tasklocalname, taskref.getTask().getName(), taskref.getTask().getVersion(), + taskref.getOutputType(), taskref.getOutputName()); if (tempres.isNok()) { tempres.addMessage("Failed to add task reference \"" + t + "\" for state \"" + statename - + "\" for policy \"" + policyname + ":" + policyversion - + "\". The policy was created, but there was an error adding the task reference for" - + " the state. The policy has only been partially defined."); + + FOR_POLICY + policyname + ":" + policyversion + POLICY_WAS_CREATED + + "but there was an error adding the task reference for" + + " the state. The policy has only been partially defined."); ret = tempres; return ret; } @@ -1771,8 +1750,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Policy/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Policy/Create" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } // CHECKSTYLE:ON: MethodLength @@ -1782,13 +1760,13 @@ public class ApexEditorRestResource { * * @param firstStatePeriodic indicates if periodic event should be created and added to model * @param jsonString the JSON string to be parsed. See {@linkplain BeanPolicy} - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @PUT @Path("Policy/Update") public ApexApiResult updatePolicy(@QueryParam("firstStatePeriodic") final boolean firstStatePeriodic, - final String jsonString) { + final String jsonString) { ApexApiResult ret = null; LOGGER.entry(jsonString); try { @@ -1797,12 +1775,12 @@ public class ApexEditorRestResource { return ret; } - final BeanPolicy jsonbean = RestUtils.getJSONParameters(jsonString, BeanPolicy.class); + final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class); if (jsonbean.getName() == null || jsonbean.getName().equals("") || jsonbean.getVersion() == null - || jsonbean.getVersion().equals("")) { + || jsonbean.getVersion().equals("")) { ret = new ApexApiResult(Result.FAILED, "Null/Empty Policy name/version (\"" + jsonbean.getName() + ":" - + jsonbean.getVersion() + "\" passed to UpdatePolicy"); + + jsonbean.getVersion() + "\" passed to UpdatePolicy"); return ret; } @@ -1813,12 +1791,11 @@ public class ApexEditorRestResource { if (firstStatePeriodic) { final ApexApiResult existingPeriodicEvent = sessionApexModel.listEvent("PeriodicEvent", null); if (existingPeriodicEvent.isNok()) { - final String periodicEventString = - "{\"name\":\"PeriodicEvent\",\"version\":\"0.0.1\"," - + "\"uuid\":\"44236da1-3d47-4988-8033-b6fee9d6a0f4\"," - + "\"description\":\"Generated description for concept referred to by key " - + "'PeriodicEvent:0.0.1'\",\"source\":\"System\",\"target\":\"Apex\"," - + "\"nameSpace\":\"org.onap.policy.apex.domains.aadm.events\",\"parameters\":{}}"; + final String periodicEventString = "{\"name\":\"PeriodicEvent\",\"version\":\"0.0.1\"," + + "\"uuid\":\"44236da1-3d47-4988-8033-b6fee9d6a0f4\"," + + "\"description\":\"Generated description for concept referred to by key " + + "'PeriodicEvent:0.0.1'\",\"source\":\"System\",\"target\":\"Apex\"," + + "\"nameSpace\":\"org.onap.policy.apex.domains.aadm.events\",\"parameters\":{}}"; ret = createEvent(periodicEventString); if (ret.isNok()) { return ret; @@ -1834,25 +1811,24 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Policy/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Policy/Update" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } /** - * List policies with the given key names/versions. If successful the result(s) will be - * available in the result messages. The returned value(s) will be similar to {@link AxPolicy}, - * with merged {@linkplain AxKey Info} for the root object. + * List policies with the given key names/versions. If successful the result(s) will be available in the result + * messages. The returned value(s) will be similar to {@link AxPolicy}, with merged {@linkplain AxKey Info} for the + * root object. * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @GET @Path("Policy/Get") public ApexApiResult listPolicy(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1882,8 +1858,7 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Policy/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + LOGGER.exit("Policy/Get" + (ret != null && ret.isOk() ? ": OK" : NOT_OK)); } } @@ -1892,13 +1867,13 @@ public class ApexEditorRestResource { * * @param name the name to search for. If null or empty, then all names will be queried * @param version the version to search for. If null then all versions will be searched for. - * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return - * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ @DELETE @Path("Policy/Delete") public ApexApiResult deletePolicy(@QueryParam("name") final String name, - @QueryParam("version") final String version) { + @QueryParam(VERSION) final String version) { ApexApiResult ret = null; String name1 = name; String version1 = version; @@ -1928,20 +1903,18 @@ public class ApexEditorRestResource { LOGGER.catching(e); throw e; } finally { - LOGGER.exit((ret == null ? false : ret.isOk())); - LOGGER.info("Policy/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK")); + String result = "Policy/Delete" + (ret != null && ret.isOk() ? ": OK" : NOT_OK); + LOGGER.exit(result); } } /** - * The json strings representing the objects listed, stored in result.messages[], does not - * contain the AxKeyInformation for that object. This utility method retrieves the AxKeyInfo for - * each object and adds it to the json for the object. + * The json strings representing the objects listed, stored in result.messages[], does not contain the + * AxKeyInformation for that object. This utility method retrieves the AxKeyInfo for each object and adds it to the + * json for the object. * - * @param result The list result, containing json representations of objects stored in its - * "messages" array - * @return The list result, containing json augmented representations of objects stored in its - * "messages" array + * @param result The list result, containing json representations of objects stored in its "messages" array + * @return The list result, containing json augmented representations of objects stored in its "messages" array */ private ApexApiResult addKeyInfo2Messages(final ApexApiResult result) { if (result.isNok()) { @@ -1962,43 +1935,43 @@ public class ApexEditorRestResource { JsonObject objecttochange = jsonObject; String name = null; if (jsonObject != null && jsonObject.get("key") != null && jsonObject.get("key").isJsonObject() - && jsonObject.getAsJsonObject("key").get("name") != null) { + && jsonObject.getAsJsonObject("key").get("name") != null) { name = jsonObject.getAsJsonObject("key").get("name").getAsString(); - } else if (jsonObject != null && jsonObject.get("policyKey") != null - && jsonObject.get("policyKey").isJsonObject() - && jsonObject.getAsJsonObject("policyKey").get("name") != null) { - name = jsonObject.getAsJsonObject("policyKey").get("name").getAsString(); + } else if (jsonObject != null && jsonObject.get(POLICY_KEY) != null + && jsonObject.get(POLICY_KEY).isJsonObject() + && jsonObject.getAsJsonObject(POLICY_KEY).get("name") != null) { + name = jsonObject.getAsJsonObject(POLICY_KEY).get("name").getAsString(); } String version = null; if (jsonObject != null && jsonObject.get("key") != null && jsonObject.get("key").isJsonObject() - && jsonObject.getAsJsonObject("key").get("version") != null) { - version = jsonObject.getAsJsonObject("key").get("version").getAsString(); - } else if (jsonObject != null && jsonObject.get("policyKey") != null - && jsonObject.get("policyKey").isJsonObject() - && jsonObject.getAsJsonObject("policyKey").get("version") != null) { - version = jsonObject.getAsJsonObject("policyKey").get("version").getAsString(); + && jsonObject.getAsJsonObject("key").get(VERSION) != null) { + version = jsonObject.getAsJsonObject("key").get(VERSION).getAsString(); + } else if (jsonObject != null && jsonObject.get(POLICY_KEY) != null + && jsonObject.get(POLICY_KEY).isJsonObject() + && jsonObject.getAsJsonObject(POLICY_KEY).get(VERSION) != null) { + version = jsonObject.getAsJsonObject(POLICY_KEY).get(VERSION).getAsString(); } if (name == null && version == null && jsonObject.entrySet() != null - && jsonObject.entrySet().size() > 0) { + && !jsonObject.entrySet().isEmpty()) { objecttochange = (JsonObject) jsonObject.entrySet().iterator().next().getValue(); if (objecttochange != null && objecttochange.get("key") != null - && objecttochange.get("key").isJsonObject() - && objecttochange.getAsJsonObject("key").get("name") != null) { + && objecttochange.get("key").isJsonObject() + && objecttochange.getAsJsonObject("key").get("name") != null) { name = objecttochange.getAsJsonObject("key").get("name").getAsString(); - } else if (objecttochange != null && objecttochange.get("policyKey") != null - && objecttochange.get("policyKey").isJsonObject() - && objecttochange.getAsJsonObject("policyKey").get("name") != null) { - name = objecttochange.getAsJsonObject("policyKey").get("name").getAsString(); + } else if (objecttochange != null && objecttochange.get(POLICY_KEY) != null + && objecttochange.get(POLICY_KEY).isJsonObject() + && objecttochange.getAsJsonObject(POLICY_KEY).get("name") != null) { + name = objecttochange.getAsJsonObject(POLICY_KEY).get("name").getAsString(); } if (objecttochange != null && objecttochange.get("key") != null - && objecttochange.get("key").isJsonObject() - && objecttochange.getAsJsonObject("key").get("version") != null) { - version = objecttochange.getAsJsonObject("key").get("version").getAsString(); - } else if (objecttochange != null && objecttochange.get("policyKey") != null - && objecttochange.get("policyKey").isJsonObject() - && objecttochange.getAsJsonObject("policyKey").get("version") != null) { - version = objecttochange.getAsJsonObject("policyKey").get("version").getAsString(); + && objecttochange.get("key").isJsonObject() + && objecttochange.getAsJsonObject("key").get(VERSION) != null) { + version = objecttochange.getAsJsonObject("key").get(VERSION).getAsString(); + } else if (objecttochange != null && objecttochange.get(POLICY_KEY) != null + && objecttochange.get(POLICY_KEY).isJsonObject() + && objecttochange.getAsJsonObject(POLICY_KEY).get(VERSION) != null) { + version = objecttochange.getAsJsonObject(POLICY_KEY).get(VERSION).getAsString(); } } @@ -2008,22 +1981,23 @@ public class ApexEditorRestResource { if (name != null && version != null) { final ApexApiResult keyInfoResult = sessionApexModel.listKeyInformation(name, version); final List keyInfoMessages = keyInfoResult.getMessages(); - if (keyInfoResult.isOk() && keyInfoMessages != null && keyInfoMessages.size() > 0) { + if (keyInfoResult.isOk() && keyInfoMessages != null && !keyInfoMessages.isEmpty()) { final String keyInfoJson = keyInfoMessages.get(0); final JsonObject keyInfoJsonObject = gson.fromJson(keyInfoJson, JsonObject.class); - if (keyInfoJsonObject != null && keyInfoJsonObject.get("apexKeyInfo") != null - && keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("UUID") != null) { - uuid = keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("UUID").getAsString(); + if (keyInfoJsonObject != null && keyInfoJsonObject.get(APEX_KEY_INFO) != null + && keyInfoJsonObject.get(APEX_KEY_INFO).getAsJsonObject().get("UUID") != null) { + uuid = keyInfoJsonObject.get(APEX_KEY_INFO).getAsJsonObject().get("UUID").getAsString(); } - if (keyInfoJsonObject != null && keyInfoJsonObject.get("apexKeyInfo") != null - && keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("description") != null) { - desc = keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("description") - .getAsString(); + if (keyInfoJsonObject != null && keyInfoJsonObject.get(APEX_KEY_INFO) != null + && keyInfoJsonObject.get(APEX_KEY_INFO).getAsJsonObject() + .get(DESCRIPTION) != null) { + desc = keyInfoJsonObject.get(APEX_KEY_INFO).getAsJsonObject().get(DESCRIPTION) + .getAsString(); } } } objecttochange.addProperty("uuid", uuid); - objecttochange.addProperty("description", desc); + objecttochange.addProperty(DESCRIPTION, desc); augmessages.add(gson.toJson(jsonObject)); } catch (final Exception e) { augmessages.add(message); @@ -2040,16 +2014,24 @@ public class ApexEditorRestResource { } /* - * This method is used only for testing and is used to cause an exception on calls from unit - * test to test exception handling. + * This method is used only for testing and is used to cause an exception on calls from unit test to test exception + * handling. */ protected static int createCorruptSession() { final ApexEditorRestResource apexEditorRestResource = new ApexEditorRestResource(); final ApexApiResult result = apexEditorRestResource.createSession(); - final int corruptSessionId = new Integer(result.getMessages().get(0)); + final int corruptSessionId = Integer.parseInt(result.getMessages().get(0)); SESSIONMODELMAP.put(corruptSessionId, null); return corruptSessionId; } + + /** + * Increment the session number. + */ + private static void incrementNextSession() { + nextSession++; + } + } diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/RestUtils.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/RestUtils.java index 02779a4d7..2bd47238a 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/RestUtils.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/RestUtils.java @@ -103,7 +103,7 @@ public abstract class RestUtils { * @param jsonString the incoming JSON string * @return a map of the JSON strings */ - public static Map getJSONParameters(final String jsonString) { + public static Map getJsonParameters(final String jsonString) { final GsonBuilder gb = new GsonBuilder(); gb.serializeNulls().enableComplexMapKeySerialization(); final JsonObject jsonObject = gb.create().fromJson(jsonString, JsonObject.class); @@ -120,12 +120,12 @@ public abstract class RestUtils { * Apex HTTP PUT requests send simple single level JSON strings, this method reads those strings * into a map. * - * @param the generic type + * @param the generic type * @param jsonString the incoming JSON string * @param clz the clz * @return a map of the JSON strings */ - public static CLZ getJSONParameters(final String jsonString, final Class clz) { + public static C getJsonParameters(final String jsonString, final Class clz) { final GsonBuilder gb = new GsonBuilder(); gb.serializeNulls().enableComplexMapKeySerialization(); final JsonObject jsonObject = gb.create().fromJson(jsonString, JsonObject.class); @@ -134,8 +134,7 @@ public abstract class RestUtils { final JsonElement val = jsonEntry.getValue(); jsonEntry.setValue(blank2null(val)); } - final CLZ ret = gb.create().fromJson(jsonObject, clz); - return ret; + return gb.create().fromJson(jsonObject, clz); } // Regular expressions for checking input types @@ -148,13 +147,13 @@ public abstract class RestUtils { /** * Gets the concept from JSON. * - * @param the generic type + * @param the generic type * @param jsonString the json string * @param clz the clz * @return the concept from JSON * @throws JAXBException the JAXB exception */ - public static CLZ getConceptFromJSON(final String jsonString, final Class clz) + public static C getConceptFromJson(final String jsonString, final Class clz) throws JAXBException { Unmarshaller unmarshaller = null; final JAXBContext jaxbContext = JAXBContext.newInstance(clz); @@ -168,10 +167,8 @@ public abstract class RestUtils { return null; } final StreamSource source = new StreamSource(new StringReader(jsonString)); - final JAXBElement rootElement = unmarshaller.unmarshal(source, clz); - final CLZ apexConcept = rootElement.getValue(); - return apexConcept; - + final JAXBElement rootElement = unmarshaller.unmarshal(source, clz); + return rootElement.getValue(); } /** @@ -180,11 +177,9 @@ public abstract class RestUtils { * @param object the object * @return the JSO nfrom concept */ - public static String getJSONfromConcept(final Object object) { + public static String getJsonfromConcept(final Object object) { final GsonBuilder gb = new GsonBuilder(); gb.serializeNulls().enableComplexMapKeySerialization(); - final String jsonObject = gb.create().toJson(object); - return jsonObject; + return gb.create().toJson(object); } - } diff --git a/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/RestInterfaceTest.java b/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/RestInterfaceTest.java index dc1e1137b..7af4b37c3 100644 --- a/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/RestInterfaceTest.java +++ b/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/RestInterfaceTest.java @@ -102,7 +102,7 @@ public class RestInterfaceTest { // create the client final Client c = ClientBuilder.newClient(); // Create the web target - target = c.target(new ApexEditorParameters().getBaseURI()); + target = c.target(new ApexEditorParameters().getBaseUri()); // load a test model locally localmodel = new ApexModelReader<>(AxPolicyModel.class, false) @@ -149,7 +149,7 @@ public class RestInterfaceTest { */ private static int createNewSession() { final ApexApiResult responseMsg = target.path("editor/-1/Session/Create").request().get(ApexApiResult.class); - assertEquals(responseMsg.getResult(), ApexApiResult.Result.SUCCESS); + assertEquals(ApexApiResult.Result.SUCCESS, responseMsg.getResult()); assertTrue(responseMsg.getMessages().size() == 1); return Integer.parseInt(responseMsg.getMessages().get(0)); } @@ -157,11 +157,11 @@ public class RestInterfaceTest { /** * Upload policy. * - * @param sessionID the session ID + * @param sessionId the session ID * @param modelAsJsonString the model as json string */ - private void uploadPolicy(final int sessionID, final String modelAsJsonString) { - final Builder requestbuilder = target.path("editor/" + sessionID + "/Model/Load").request(); + private void uploadPolicy(final int sessionId, final String modelAsJsonString) { + final Builder requestbuilder = target.path("editor/" + sessionId + "/Model/Load").request(); final ApexApiResult responseMsg = requestbuilder.put(Entity.json(modelAsJsonString), ApexApiResult.class); assertTrue(responseMsg.isOk()); } @@ -176,11 +176,11 @@ public class RestInterfaceTest { @Test public void testUploadThenGet() throws ApexException, JAXBException { - final int sessionID = createNewSession(); + final int sessionId = createNewSession(); - uploadPolicy(sessionID, localmodelString); + uploadPolicy(sessionId, localmodelString); - final ApexApiResult responseMsg = target.path("editor/" + sessionID + "/Policy/Get") + final ApexApiResult responseMsg = target.path("editor/" + sessionId + "/Policy/Get") .queryParam("name", "Policy0").queryParam("version", "0.0.1").request().get(ApexApiResult.class); assertTrue(responseMsg.isOk()); diff --git a/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/TestApexEditorStartup.java b/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/TestApexEditorStartup.java index 699505aa8..0fad411a5 100644 --- a/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/TestApexEditorStartup.java +++ b/client/client-editor/src/test/java/org/onap/policy/apex/client/editor/rest/TestApexEditorStartup.java @@ -336,7 +336,7 @@ public class TestApexEditorStartup { * @throws InterruptedException if the test is interrupted */ @Test - public void testTTLArg0() throws IOException, InterruptedException { + public void testTtlArg0() throws IOException, InterruptedException { final String[] args = new String[] { "-t10" }; final String outString = runEditor(args); @@ -359,7 +359,7 @@ public class TestApexEditorStartup { * @throws InterruptedException if the test is interrupted */ @Test - public void testTTLArg1() throws IOException, InterruptedException { + public void testTtlArg1() throws IOException, InterruptedException { final String[] args = new String[] { "-t", "10", "-l", "localhost" }; final String outString = runEditor(args); @@ -382,7 +382,7 @@ public class TestApexEditorStartup { * @throws InterruptedException if the test is interrupted */ @Test - public void testPortTTLArg0() throws IOException, InterruptedException { + public void testPortTtlArg0() throws IOException, InterruptedException { final String[] args = new String[] { "-t", "10", "-p", "12321" }; final String outString = runEditor(args); @@ -406,7 +406,7 @@ public class TestApexEditorStartup { * @throws InterruptedException if the test is interrupted */ @Test - public void testPortTTLArg1() throws IOException, InterruptedException { + public void testPortTtlArg1() throws IOException, InterruptedException { final String[] args = new String[] { "--time-to-live", "10", "--port", "12321", "--listen", "127.0.0.1" }; final String outString = runEditor(args); @@ -430,8 +430,8 @@ public class TestApexEditorStartup { * @throws InterruptedException if the test is interrupted */ private String runEditor(final String[] args) throws InterruptedException { - final ByteArrayOutputStream outBAStream = new ByteArrayOutputStream(); - final PrintStream outStream = new PrintStream(outBAStream); + final ByteArrayOutputStream outBaStream = new ByteArrayOutputStream(); + final PrintStream outStream = new PrintStream(outBaStream); final ApexEditorMain editorMain = new ApexEditorMain(args, outStream); @@ -450,7 +450,7 @@ public class TestApexEditorStartup { } editorMain.shutdown(); - final String outString = outBAStream.toString(); + final String outString = outBaStream.toString(); System.out.println(outString); return outString; } diff --git a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRest.java b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRest.java index c6460d2c9..774cfc632 100644 --- a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRest.java +++ b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRest.java @@ -59,14 +59,14 @@ public class ApexServicesRest { // Create a resource configuration that scans for JAX-RS resources and providers // in org.onap.policy.apex.client.full.rest package - final ResourceConfig rc = new ResourceConfig().packages(parameters.getRESTPackages()); + final ResourceConfig rc = new ResourceConfig().packages(parameters.getRestPackages()); // Add MultiPartFeature class for jersey-media-multipart rc.register(MultiPartFeature.class); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI - server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseURI(), rc); + server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseUri(), rc); // Add static content server.getServerConfiguration().addHttpHandler(new org.glassfish.grizzly.http.server.CLStaticHttpHandler( diff --git a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java index a2fb0ac73..c89fcf473 100644 --- a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java +++ b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java @@ -22,11 +22,20 @@ package org.onap.policy.apex.client.full.rest; import java.io.PrintStream; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + /** * This class is the main class that is used to launch the Apex editor from the command line. * */ public class ApexServicesRestMain { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServicesRestMain.class); + + // Recurring string constants + private static final String REST_ENDPOINT_PREFIX = "Apex Editor REST endpoint ("; + /** * The Enum EditorState holds the current state of the editor. */ @@ -65,7 +74,7 @@ public class ApexServicesRestMain { final ApexServicesRestMain editorMain = new ApexServicesRestMain(args, System.out); editorMain.init(); } catch (final Exception e) { - System.err.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } @@ -87,7 +96,7 @@ public class ApexServicesRestMain { parameters = parser.parse(args); } catch (final ApexServicesRestParameterException e) { throw new ApexServicesRestParameterException( - "Apex Editor REST endpoint (" + this.toString() + ") parameter error, " + e.getMessage() + '\n' + REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n' + parser.getHelp(ApexServicesRestMain.class.getCanonicalName())); } @@ -99,7 +108,7 @@ public class ApexServicesRestMain { final String validationMessage = parameters.validate(); if (validationMessage.length() > 0) { throw new ApexServicesRestParameterException( - "Apex Editor REST endpoint (" + this.toString() + ") parameters invalid, " + validationMessage + REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage + '\n' + parser.getHelp(ApexServicesRestMain.class.getCanonicalName())); } @@ -110,8 +119,8 @@ public class ApexServicesRestMain { * Initialize the Apex editor. */ public void init() { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") starting at " - + parameters.getBaseURI().toString() + " . . ."); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + + parameters.getBaseUri().toString() + " . . ."); try { state = EditorState.INITIALIZING; @@ -125,10 +134,10 @@ public class ApexServicesRestMain { state = EditorState.RUNNING; if (parameters.getTimeToLive() == ApexServicesRestParameters.INFINITY_TIME_TO_LIVE) { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") started at " - + parameters.getBaseURI().toString()); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at " + + parameters.getBaseUri().toString()); } else { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") started"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started"); } // Find out how long is left to wait @@ -144,7 +153,7 @@ public class ApexServicesRestMain { } } catch (final Exception e) { outStream.println( - "Apex Editor REST endpoint (" + this.toString() + ") failed at with error: " + e.getMessage()); + REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage()); } finally { if (apexServices != null) { apexServices.shutdown(); @@ -181,11 +190,11 @@ public class ApexServicesRestMain { */ public void shutdown() { if (apexServices != null) { - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") shutting down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down"); apexServices.shutdown(); } state = EditorState.STOPPED; - outStream.println("Apex Editor REST endpoint (" + this.toString() + ") shut down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down"); } /** diff --git a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameterParser.java b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameterParser.java index 8a90aa633..bb27943d6 100644 --- a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameterParser.java +++ b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameterParser.java @@ -81,7 +81,7 @@ public class ApexServicesRestParameterParser { } try { if (commandLine.hasOption('p')) { - parameters.setRESTPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); + parameters.setRestPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); } } catch (final ParseException e) { throw new ApexServicesRestParameterException("error parsing argument \"port\" :" + e.getMessage(), e); diff --git a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameters.java b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameters.java index 52ad885fd..f5f9d4c35 100644 --- a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameters.java +++ b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestParameters.java @@ -37,14 +37,21 @@ public class ApexServicesRestParameters { private static final String DEFAULT_STATIC_PATH = "/"; // Package that will field REST requests - private static final String[] DEFAULT_PACKAGES = new String[] { "org.onap.policy.apex.client.deployment.rest", - "org.onap.policy.apex.client.editor.rest", "org.onap.policy.apex.client.monitoring.rest" }; + private static final String[] DEFAULT_PACKAGES = new String[] { + "org.onap.policy.apex.client.deployment.rest", + "org.onap.policy.apex.client.editor.rest", + "org.onap.policy.apex.client.monitoring.rest" + }; // The services parameters private boolean helpSet = false; private int restPort = DEFAULT_REST_PORT; private long timeToLive = INFINITY_TIME_TO_LIVE; + /** + * Validate the parameters. + * @return the result of the validation + */ public String validate() { String validationMessage = ""; validationMessage += validatePort(); @@ -53,11 +60,11 @@ public class ApexServicesRestParameters { return validationMessage; } - public URI getBaseURI() { + public URI getBaseUri() { return URI.create(DEFAULT_SERVER_URI_ROOT + restPort + DEFAULT_REST_PATH); } - public String[] getRESTPackages() { + public String[] getRestPackages() { return DEFAULT_PACKAGES; } @@ -89,11 +96,11 @@ public class ApexServicesRestParameters { this.helpSet = helpSet; } - public int getRESTPort() { + public int getRestPort() { return restPort; } - public void setRESTPort(final int restPort) { + public void setRestPort(final int restPort) { this.restPort = restPort; } @@ -108,7 +115,7 @@ public class ApexServicesRestParameters { @Override public String toString() { final StringBuilder ret = new StringBuilder(); - ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseURI()).append(", TTL=") + ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseUri()).append(", TTL=") .append(this.getTimeToLive()).append("sec"); return ret.toString(); } diff --git a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRest.java b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRest.java index e7802ae3f..d600fb25c 100644 --- a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRest.java +++ b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRest.java @@ -56,11 +56,11 @@ public class ApexMonitoringRest { // Create a resource configuration that scans for JAX-RS resources and providers // in org.onap.policy.apex.services.client.monitoring.rest package - final ResourceConfig rc = new ResourceConfig().packages(parameters.getRESTPackages()); + final ResourceConfig rc = new ResourceConfig().packages(parameters.getRestPackages()); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI - server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseURI(), rc); + server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseUri(), rc); // Add static content server.getServerConfiguration().addHttpHandler(new org.glassfish.grizzly.http.server.CLStaticHttpHandler( diff --git a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java index bf2365f46..297ee97e9 100644 --- a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java +++ b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java @@ -22,12 +22,21 @@ package org.onap.policy.apex.client.monitoring.rest; import java.io.PrintStream; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + /** * The main class for Apex Restful Monitoring. * * @author Michael Watkins (michael.watkins@ericsson.com) */ public class ApexMonitoringRestMain { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexMonitoringRestMain.class); + + // Recurring string constants + private static final String REST_ENDPOINT_PREFIX = "Apex Services REST endpoint ("; + // Services state public enum ServicesState { STOPPED, READY, INITIALIZING, RUNNING @@ -54,7 +63,7 @@ public class ApexMonitoringRestMain { final ApexMonitoringRestMain restMain = new ApexMonitoringRestMain(args, System.out); restMain.init(); } catch (final Exception e) { - System.err.println(e.getMessage()); + LOGGER.error("start failed", e); } } @@ -76,7 +85,7 @@ public class ApexMonitoringRestMain { parameters = parser.parse(args); } catch (final ApexMonitoringRestParameterException e) { throw new ApexMonitoringRestParameterException( - "Apex Services REST endpoint (" + this.toString() + ") parameter error, " + e.getMessage() + '\n' + REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n' + parser.getHelp(ApexMonitoringRestMain.class.getCanonicalName())); } @@ -89,7 +98,7 @@ public class ApexMonitoringRestMain { final String validationMessage = parameters.validate(); if (validationMessage.length() > 0) { throw new ApexMonitoringRestParameterException( - "Apex Services REST endpoint (" + this.toString() + ") parameters invalid, " + validationMessage + REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage + '\n' + parser.getHelp(ApexMonitoringRestMain.class.getCanonicalName())); } @@ -100,8 +109,8 @@ public class ApexMonitoringRestMain { * Initialize the rest service. */ public void init() { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") starting at " - + parameters.getBaseURI().toString() + " . . ."); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + + parameters.getBaseUri().toString() + " . . ."); try { state = ServicesState.INITIALIZING; @@ -115,10 +124,10 @@ public class ApexMonitoringRestMain { state = ServicesState.RUNNING; if (parameters.getTimeToLive() == ApexMonitoringRestParameters.INFINITY_TIME_TO_LIVE) { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") started at " - + parameters.getBaseURI().toString()); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at " + + parameters.getBaseUri().toString()); } else { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") started"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started"); } // Find out how long is left to wait @@ -134,7 +143,7 @@ public class ApexMonitoringRestMain { } } catch (final Exception e) { outStream.println( - "Apex Services REST endpoint (" + this.toString() + ") failed at with error: " + e.getMessage()); + REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage()); } finally { if (apexMonitoringRest != null) { apexMonitoringRest.shutdown(); @@ -167,11 +176,11 @@ public class ApexMonitoringRestMain { */ public void shutdown() { if (apexMonitoringRest != null) { - outStream.println("Apex Services REST endpoint (" + this.toString() + ") shutting down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down"); apexMonitoringRest.shutdown(); } state = ServicesState.STOPPED; - outStream.println("Apex Services REST endpoint (" + this.toString() + ") shut down"); + outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down"); } /** diff --git a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameterParser.java b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameterParser.java index af2ff6821..f5c8ad8c0 100644 --- a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameterParser.java +++ b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameterParser.java @@ -81,7 +81,7 @@ public class ApexMonitoringRestParameterParser { } try { if (commandLine.hasOption('p')) { - parameters.setRESTPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); + parameters.setRestPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); } } catch (final ParseException e) { throw new ApexMonitoringRestParameterException("error parsing argument \"port\" :" + e.getMessage(), e); diff --git a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameters.java b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameters.java index fea7ae4a8..e4148a470 100644 --- a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameters.java +++ b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestParameters.java @@ -44,6 +44,10 @@ public class ApexMonitoringRestParameters { private int restPort = DEFAULT_REST_PORT; private long timeToLive = INFINITY_TIME_TO_LIVE; + /** + * Validate the parameters. + * @return the result of the validation + */ public String validate() { String validationMessage = ""; validationMessage += validatePort(); @@ -52,11 +56,11 @@ public class ApexMonitoringRestParameters { return validationMessage; } - public URI getBaseURI() { + public URI getBaseUri() { return URI.create(DEFAULT_SERVER_URI_ROOT + restPort + DEFAULT_REST_PATH); } - public String[] getRESTPackages() { + public String[] getRestPackages() { return DEFAULT_PACKAGES; } @@ -88,11 +92,11 @@ public class ApexMonitoringRestParameters { this.helpSet = helpSet; } - public int getRESTPort() { + public int getRestPort() { return restPort; } - public void setRESTPort(final int restPort) { + public void setRestPort(final int restPort) { this.restPort = restPort; } @@ -107,7 +111,7 @@ public class ApexMonitoringRestParameters { @Override public String toString() { final StringBuilder ret = new StringBuilder(); - ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseURI()).append(", TTL=") + ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseUri()).append(", TTL=") .append(this.getTimeToLive()).append("sec"); return ret.toString(); } diff --git a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestResource.java b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestResource.java index 85465a14b..f8cee7741 100644 --- a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestResource.java +++ b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestResource.java @@ -48,9 +48,8 @@ import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** - * The class represents the root resource exposed at the base URL
- * The url to access this resource would be in the form {@code /rest/....}
- * For example: a GET request to the following URL + * The class represents the root resource exposed at the base URL
The url to access this resource would be in the + * form {@code /rest/....}
For example: a GET request to the following URL * {@code http://localhost:18989/apexservices/rest/?hostName=localhost&port=12345} * * Note: An allocated {@code hostName} and {@code port} query parameter must be included in all requests. @@ -58,27 +57,26 @@ import org.slf4j.ext.XLoggerFactory; * */ @Path("monitoring/") -@Produces({ MediaType.APPLICATION_JSON }) -@Consumes({ MediaType.APPLICATION_JSON }) +@Produces( + { MediaType.APPLICATION_JSON }) +@Consumes( + { MediaType.APPLICATION_JSON }) public class ApexMonitoringRestResource { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexMonitoringRestResource.class); + // Recurring string constants + private static final String ERROR_CONNECTING_PREFIX = "Error connecting to Apex Engine Service at "; + // Set the maximum number of stored data entries to be stored for each engine - private static final int maxCachedEntries = 50; + private static final int MAX_CACHED_ENTITIES = 50; // Set up a map separated by host and engine for the data - private static final HashMap>> cache = - new HashMap>>(); + private static final HashMap>> cache = new HashMap<>(); // Set up a map separated by host for storing the state of periodic events - private static final HashMap periodicEventsStateCache = new HashMap(); - - /** - * Constructor, a new resource director is created for each request. - */ - public ApexMonitoringRestResource() {} + private static final HashMap periodicEventsStateCache = new HashMap<>(); /** * Query the engine service for data. @@ -96,10 +94,10 @@ public class ApexMonitoringRestResource { try { engineServiceFacade.init(); } catch (final ApexDeploymentException e) { - final String errorMessage = "Error connecting to Apex Engine Service at " + host; + final String errorMessage = ERROR_CONNECTING_PREFIX + host; LOGGER.warn(errorMessage + "
", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + e.getMessage()) - .build(); + .build(); } final JsonObject responseObject = new JsonObject(); @@ -107,8 +105,8 @@ public class ApexMonitoringRestResource { // Engine Service data responseObject.addProperty("engine_id", engineServiceFacade.getKey().getId()); responseObject.addProperty("model_id", - engineServiceFacade.getApexModelKey() != null ? engineServiceFacade.getApexModelKey().getId() - : "Not Set"); + engineServiceFacade.getApexModelKey() != null ? engineServiceFacade.getApexModelKey().getId() + : "Not Set"); responseObject.addProperty("server", hostName); responseObject.addProperty("port", Integer.toString(port)); responseObject.addProperty("periodic_events", getPeriodicEventsState(host)); @@ -127,14 +125,16 @@ public class ApexMonitoringRestResource { engineStatusObject.addProperty("up_time", axEngineModel.getStats().getUpTime() / 1000L); engineStatusObject.addProperty("policy_executions", axEngineModel.getStats().getEventCount()); engineStatusObject.addProperty("last_policy_duration", - gson.toJson( - getValuesFromCache(host, engineKey.getId() + "_last_policy_duration", - axEngineModel.getTimestamp(), axEngineModel.getStats().getLastExecutionTime()), - List.class)); - engineStatusObject.addProperty("average_policy_duration", - gson.toJson(getValuesFromCache(host, engineKey.getId() + "_average_policy_duration", - axEngineModel.getTimestamp(), - (long) axEngineModel.getStats().getAverageExecutionTime()), List.class)); + gson.toJson(getValuesFromCache(host, engineKey.getId() + "_last_policy_duration", + axEngineModel.getTimestamp(), + axEngineModel.getStats().getLastExecutionTime()), List.class)); + engineStatusObject + .addProperty("average_policy_duration", gson.toJson( + getValuesFromCache(host, engineKey.getId() + "_average_policy_duration", + axEngineModel.getTimestamp(), + (long) axEngineModel.getStats() + .getAverageExecutionTime()), + List.class)); engineStatusList.add(engineStatusObject); } catch (final ApexException e) { LOGGER.warn("Error getting status of engine with ID " + engineKey.getId() + "
", e); @@ -174,23 +174,26 @@ public class ApexMonitoringRestResource { @GET @Path("startstop/") public Response startStop(@QueryParam("hostName") final String hostName, @QueryParam("port") final int port, - @QueryParam("engineId") final String engineId, @QueryParam("startstop") final String startStop) { + @QueryParam("engineId") final String engineId, @QueryParam("startstop") final String startStop) { final EngineServiceFacade engineServiceFacade = new EngineServiceFacade(hostName, port); try { engineServiceFacade.init(); } catch (final ApexDeploymentException e) { - final String errorMessage = "Error connecting to Apex Engine Service at " + hostName + ":" + port; + final String errorMessage = ERROR_CONNECTING_PREFIX + hostName + ":" + port; LOGGER.warn(errorMessage + "
", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + e.getMessage()) - .build(); + .build(); } try { - final Map parameterMap = new HashMap(); - parameterMap.put("hostname", new String[] { hostName }); - parameterMap.put("port", new String[] { Integer.toString(port) }); - parameterMap.put("AxArtifactKey#" + engineId, new String[] { startStop }); + final Map parameterMap = new HashMap<>(); + parameterMap.put("hostname", new String[] + { hostName }); + parameterMap.put("port", new String[] + { Integer.toString(port) }); + parameterMap.put("AxArtifactKey#" + engineId, new String[] + { startStop }); final AxArtifactKey engineKey = ParameterCheck.getEngineKey(parameterMap); if (startStop.equals("Start")) { engineServiceFacade.startEngine(engineKey); @@ -203,7 +206,7 @@ public class ApexMonitoringRestResource { final StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + sw.toString()) - .build(); + .build(); } return Response.ok("{}").build(); @@ -222,17 +225,21 @@ public class ApexMonitoringRestResource { @GET @Path("periodiceventstartstop/") public Response periodiceventStartStop(@QueryParam("hostName") final String hostName, - @QueryParam("port") final int port, @QueryParam("engineId") final String engineId, - @QueryParam("startstop") final String startStop, @QueryParam("period") final long period) { + @QueryParam("port") final int port, @QueryParam("engineId") final String engineId, + @QueryParam("startstop") final String startStop, @QueryParam("period") final long period) { final EngineServiceFacade engineServiceFacade = new EngineServiceFacade(hostName, port); final String host = hostName + ":" + port; try { engineServiceFacade.init(); - final Map parameterMap = new HashMap(); - parameterMap.put("hostname", new String[] { hostName }); - parameterMap.put("port", new String[] { Integer.toString(port) }); - parameterMap.put("AxArtifactKey#" + engineId, new String[] { startStop }); - parameterMap.put("period", new String[] { Long.toString(period) }); + final Map parameterMap = new HashMap<>(); + parameterMap.put("hostname", new String[] + { hostName }); + parameterMap.put("port", new String[] + { Integer.toString(port) }); + parameterMap.put("AxArtifactKey#" + engineId, new String[] + { startStop }); + parameterMap.put("period", new String[] + { Long.toString(period) }); final AxArtifactKey engineKey = ParameterCheck.getEngineKey(parameterMap); if (startStop.equals("Start")) { engineServiceFacade.startPerioidicEvents(engineKey, period); @@ -242,10 +249,10 @@ public class ApexMonitoringRestResource { setPeriodicEventsState(host, false); } } catch (final ApexDeploymentException e) { - final String errorMessage = "Error connecting to Apex Engine Service at " + host; + final String errorMessage = ERROR_CONNECTING_PREFIX + host; LOGGER.warn(errorMessage + "
", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + e.getMessage()) - .build(); + .build(); } return Response.ok("{}").build(); @@ -258,7 +265,11 @@ public class ApexMonitoringRestResource { * @return a boolean stating if periodic events are running for a given host */ private Boolean getPeriodicEventsState(final String host) { - return periodicEventsStateCache.containsKey(host) ? periodicEventsStateCache.get(host) : false; + if (periodicEventsStateCache.containsKey(host)) { + return periodicEventsStateCache.get(host); + } else { + return false; + } } /** @@ -282,7 +293,7 @@ public class ApexMonitoringRestResource { * @return a list of {@code Counter} objects for that engine */ private List getValuesFromCache(final String host, final String id, final long timestamp, - final long latestValue) { + final long latestValue) { SlidingWindowList valueList; if (!cache.containsKey(host)) { @@ -292,7 +303,7 @@ public class ApexMonitoringRestResource { if (cache.get(host).containsKey(id)) { valueList = (SlidingWindowList) cache.get(host).get(id); } else { - valueList = new SlidingWindowList(maxCachedEntries); + valueList = new SlidingWindowList<>(MAX_CACHED_ENTITIES); } valueList.add(new Counter(timestamp, latestValue)); diff --git a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelFactory.java b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelFactory.java index 376643211..c0003ac68 100644 --- a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelFactory.java +++ b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelFactory.java @@ -50,6 +50,33 @@ import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; * The Class AADMDomainModelFactory. */ public class AadmDomainModelFactory { + // Recurring string constants + private static final String MATCH = "Match"; + private static final String ESTABLISH = "Establish"; + private static final String DECIDE = "Decide"; + private static final String TASK_SELECTION_LOGIC = "TaskSelectionLogic"; + private static final String DEFAULT_TASK_LOGIC = "DefaultTaskLogic"; + private static final String TASK_LOGIC = "TaskLogic"; + private static final String VERSION = "VERSION"; + private static final String THRESHOLD = "THRESHOLD"; + private static final String PROFILE2 = "PROFILE"; + private static final String BLACKLIST_ON = "BLACKLIST_ON"; + private static final String ACTTASK = "ACTTASK"; + private static final String TCP_ON = "TCP_ON"; + private static final String PROBE_ON = "PROBE_ON"; + private static final String APPLICATION = "APPLICATION"; + private static final String NW_IP = "NW_IP"; + private static final String IMSI_IP = "IMSI_IP"; + private static final String ENODEB_ID = "ENODEB_ID"; + private static final String DEFAULT_SOURCE = "External"; + private static final String DEFAULT_NAMESPACE = "org.onap.policy.apex.examples.aadm.events"; + private static final String JAVA_LANG_INTEGER = "java.lang.Integer"; + private static final String JAVA_LANG_DOUBLE = "java.lang.Double"; + private static final String JAVA_LANG_BOOLEAN = "java.lang.Boolean"; + private static final String JAVA_LANG_STRING = "java.lang.String"; + private static final String JAVA_LANG_LONG = "java.lang.Long"; + private static final String DEFAULT_VERSION = "0.0.1"; + /** * Gets the AADM policy model. * @@ -59,59 +86,61 @@ public class AadmDomainModelFactory { public AxPolicyModel getAadmPolicyModel() { // CHECKSTYLE:ON: checkstyle // Data types for event parameters - final AxContextSchema imsi = new AxContextSchema(new AxArtifactKey("IMSI", "0.0.1"), "Java", "java.lang.Long"); - final AxContextSchema ueIpAddress = - new AxContextSchema(new AxArtifactKey("UEIPAddress", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema nwIpAddress = - new AxContextSchema(new AxArtifactKey("NWIPAddress", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema dosFlag = - new AxContextSchema(new AxArtifactKey("DOSFlag", "0.0.1"), "Java", "java.lang.Boolean"); - final AxContextSchema roundTripTime = - new AxContextSchema(new AxArtifactKey("RoundTripTime", "0.0.1"), "Java", "java.lang.Long"); - final AxContextSchema applicationName = - new AxContextSchema(new AxArtifactKey("ApplicationName", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema protocolGroup = - new AxContextSchema(new AxArtifactKey("ProtocolGroup", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema eNodeBId = - new AxContextSchema(new AxArtifactKey("ENodeBID", "0.0.1"), "Java", "java.lang.Long"); - final AxContextSchema httpHostClass = - new AxContextSchema(new AxArtifactKey("HttpHostClass", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema tcpOnFlag = - new AxContextSchema(new AxArtifactKey("TCPOnFlag", "0.0.1"), "Java", "java.lang.Boolean"); - final AxContextSchema probeOnFlag = - new AxContextSchema(new AxArtifactKey("ProbeOnFlag", "0.0.1"), "Java", "java.lang.Boolean"); - final AxContextSchema blacklistOnFlag = - new AxContextSchema(new AxArtifactKey("BlacklistOnFlag", "0.0.1"), "Java", "java.lang.Boolean"); - final AxContextSchema averageThroughput = - new AxContextSchema(new AxArtifactKey("AverageThroughput", "0.0.1"), "Java", "java.lang.Double"); - final AxContextSchema serviceRequestCount = - new AxContextSchema(new AxArtifactKey("ServiceRequestCount", "0.0.1"), "Java", "java.lang.Integer"); - final AxContextSchema attchCount = - new AxContextSchema(new AxArtifactKey("AttachCount", "0.0.1"), "Java", "java.lang.Integer"); - final AxContextSchema subscriberCount = - new AxContextSchema(new AxArtifactKey("SubscriberCount", "0.0.1"), "Java", "java.lang.Integer"); - final AxContextSchema averageServiceRequest = - new AxContextSchema(new AxArtifactKey("AverageServiceRequest", "0.0.1"), "Java", "java.lang.Double"); - final AxContextSchema averageAttach = - new AxContextSchema(new AxArtifactKey("AverageAttach", "0.0.1"), "Java", "java.lang.Double"); - final AxContextSchema actionTask = - new AxContextSchema(new AxArtifactKey("ActionTask", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema version = - new AxContextSchema(new AxArtifactKey("Version", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema profile = - new AxContextSchema(new AxArtifactKey("Profile", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema threshold = - new AxContextSchema(new AxArtifactKey("Threshold", "0.0.1"), "Java", "java.lang.Long"); - final AxContextSchema triggerSpec = - new AxContextSchema(new AxArtifactKey("TriggerSpec", "0.0.1"), "Java", "java.lang.String"); - final AxContextSchema periodicEventCount = - new AxContextSchema(new AxArtifactKey("PeriodicEventCount", "0.0.1"), "Java", "java.lang.Long"); - final AxContextSchema periodicDelay = - new AxContextSchema(new AxArtifactKey("PeriodicDelay", "0.0.1"), "Java", "java.lang.Long"); - final AxContextSchema periodicTime = - new AxContextSchema(new AxArtifactKey("PeriodicTime", "0.0.1"), "Java", "java.lang.Long"); - - final AxContextSchemas aadmContextSchemas = new AxContextSchemas(new AxArtifactKey("AADMDatatypes", "0.0.1")); + final AxContextSchema imsi = new AxContextSchema(new AxArtifactKey("IMSI", DEFAULT_VERSION), "Java", + JAVA_LANG_LONG); + final AxContextSchema ueIpAddress = new AxContextSchema(new AxArtifactKey("UEIPAddress", DEFAULT_VERSION), + "Java", JAVA_LANG_STRING); + final AxContextSchema nwIpAddress = new AxContextSchema(new AxArtifactKey("NWIPAddress", DEFAULT_VERSION), + "Java", JAVA_LANG_STRING); + final AxContextSchema dosFlag = new AxContextSchema(new AxArtifactKey("DOSFlag", DEFAULT_VERSION), "Java", + JAVA_LANG_BOOLEAN); + final AxContextSchema roundTripTime = new AxContextSchema(new AxArtifactKey("RoundTripTime", DEFAULT_VERSION), + "Java", JAVA_LANG_LONG); + final AxContextSchema applicationName = new AxContextSchema( + new AxArtifactKey("ApplicationName", DEFAULT_VERSION), "Java", JAVA_LANG_STRING); + final AxContextSchema protocolGroup = new AxContextSchema(new AxArtifactKey("ProtocolGroup", DEFAULT_VERSION), + "Java", JAVA_LANG_STRING); + final AxContextSchema eNodeBId = new AxContextSchema(new AxArtifactKey("ENodeBID", DEFAULT_VERSION), "Java", + JAVA_LANG_LONG); + final AxContextSchema httpHostClass = new AxContextSchema(new AxArtifactKey("HttpHostClass", DEFAULT_VERSION), + "Java", JAVA_LANG_STRING); + final AxContextSchema tcpOnFlag = new AxContextSchema(new AxArtifactKey("TCPOnFlag", DEFAULT_VERSION), "Java", + JAVA_LANG_BOOLEAN); + final AxContextSchema probeOnFlag = new AxContextSchema(new AxArtifactKey("ProbeOnFlag", DEFAULT_VERSION), + "Java", JAVA_LANG_BOOLEAN); + final AxContextSchema blacklistOnFlag = new AxContextSchema( + new AxArtifactKey("BlacklistOnFlag", DEFAULT_VERSION), "Java", JAVA_LANG_BOOLEAN); + final AxContextSchema averageThroughput = new AxContextSchema( + new AxArtifactKey("AverageThroughput", DEFAULT_VERSION), "Java", JAVA_LANG_DOUBLE); + final AxContextSchema serviceRequestCount = new AxContextSchema( + new AxArtifactKey("ServiceRequestCount", DEFAULT_VERSION), "Java", JAVA_LANG_INTEGER); + final AxContextSchema attchCount = new AxContextSchema(new AxArtifactKey("AttachCount", DEFAULT_VERSION), + "Java", JAVA_LANG_INTEGER); + final AxContextSchema subscriberCount = new AxContextSchema( + new AxArtifactKey("SubscriberCount", DEFAULT_VERSION), "Java", JAVA_LANG_INTEGER); + final AxContextSchema averageServiceRequest = new AxContextSchema( + new AxArtifactKey("AverageServiceRequest", DEFAULT_VERSION), "Java", JAVA_LANG_DOUBLE); + final AxContextSchema averageAttach = new AxContextSchema(new AxArtifactKey("AverageAttach", DEFAULT_VERSION), + "Java", JAVA_LANG_DOUBLE); + final AxContextSchema actionTask = new AxContextSchema(new AxArtifactKey("ActionTask", DEFAULT_VERSION), "Java", + JAVA_LANG_STRING); + final AxContextSchema version = new AxContextSchema(new AxArtifactKey("Version", DEFAULT_VERSION), "Java", + JAVA_LANG_STRING); + final AxContextSchema profile = new AxContextSchema(new AxArtifactKey("Profile", DEFAULT_VERSION), "Java", + JAVA_LANG_STRING); + final AxContextSchema threshold = new AxContextSchema(new AxArtifactKey("Threshold", DEFAULT_VERSION), "Java", + JAVA_LANG_LONG); + final AxContextSchema triggerSpec = new AxContextSchema(new AxArtifactKey("TriggerSpec", DEFAULT_VERSION), + "Java", JAVA_LANG_STRING); + final AxContextSchema periodicEventCount = new AxContextSchema( + new AxArtifactKey("PeriodicEventCount", DEFAULT_VERSION), "Java", JAVA_LANG_LONG); + final AxContextSchema periodicDelay = new AxContextSchema(new AxArtifactKey("PeriodicDelay", DEFAULT_VERSION), + "Java", JAVA_LANG_LONG); + final AxContextSchema periodicTime = new AxContextSchema(new AxArtifactKey("PeriodicTime", DEFAULT_VERSION), + "Java", JAVA_LANG_LONG); + + final AxContextSchemas aadmContextSchemas = new AxContextSchemas( + new AxArtifactKey("AADMDatatypes", DEFAULT_VERSION)); aadmContextSchemas.getSchemasMap().put(imsi.getKey(), imsi); aadmContextSchemas.getSchemasMap().put(ueIpAddress.getKey(), ueIpAddress); aadmContextSchemas.getSchemasMap().put(nwIpAddress.getKey(), nwIpAddress); @@ -139,161 +168,165 @@ public class AadmDomainModelFactory { aadmContextSchemas.getSchemasMap().put(periodicDelay.getKey(), periodicDelay); aadmContextSchemas.getSchemasMap().put(periodicTime.getKey(), periodicTime); - final AxEvent aadmEvent = - new AxEvent(new AxArtifactKey("AADMEvent", "0.0.1"), "org.onap.policy.apex.examples.aadm.events"); - aadmEvent.setSource("External"); + final AxEvent aadmEvent = new AxEvent(new AxArtifactKey("AADMEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + aadmEvent.setSource(DEFAULT_SOURCE); aadmEvent.setTarget("Apex"); aadmEvent.getParameterMap().put("IMSI", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "IMSI"), imsi.getKey())); - aadmEvent.getParameterMap().put("ENODEB_ID", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "ENODEB_ID"), eNodeBId.getKey())); - aadmEvent.getParameterMap().put("IMSI_IP", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "IMSI_IP"), ueIpAddress.getKey())); - aadmEvent.getParameterMap().put("NW_IP", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "NW_IP"), nwIpAddress.getKey())); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "IMSI"), imsi.getKey())); + aadmEvent.getParameterMap().put(ENODEB_ID, + new AxField(new AxReferenceKey(aadmEvent.getKey(), ENODEB_ID), eNodeBId.getKey())); + aadmEvent.getParameterMap().put(IMSI_IP, + new AxField(new AxReferenceKey(aadmEvent.getKey(), IMSI_IP), ueIpAddress.getKey())); + aadmEvent.getParameterMap().put(NW_IP, + new AxField(new AxReferenceKey(aadmEvent.getKey(), NW_IP), nwIpAddress.getKey())); aadmEvent.getParameterMap().put("DoS", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "DoS"), dosFlag.getKey())); - aadmEvent.getParameterMap().put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", new AxField( - new AxReferenceKey(aadmEvent.getKey(), "TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX"), roundTripTime.getKey())); - aadmEvent.getParameterMap().put("TCP_UE_SIDE_AVG_THROUGHPUT", new AxField( - new AxReferenceKey(aadmEvent.getKey(), "TCP_UE_SIDE_AVG_THROUGHPUT"), averageThroughput.getKey())); - aadmEvent.getParameterMap().put("APPLICATION", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "APPLICATION"), applicationName.getKey())); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "DoS"), dosFlag.getKey())); + aadmEvent.getParameterMap().put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", + new AxField(new AxReferenceKey(aadmEvent.getKey(), "TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX"), + roundTripTime.getKey())); + aadmEvent.getParameterMap().put("TCP_UE_SIDE_AVG_THROUGHPUT", + new AxField(new AxReferenceKey(aadmEvent.getKey(), "TCP_UE_SIDE_AVG_THROUGHPUT"), + averageThroughput.getKey())); + aadmEvent.getParameterMap().put(APPLICATION, + new AxField(new AxReferenceKey(aadmEvent.getKey(), APPLICATION), applicationName.getKey())); aadmEvent.getParameterMap().put("protocol_group", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "protocol_group"), protocolGroup.getKey())); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "protocol_group"), protocolGroup.getKey())); aadmEvent.getParameterMap().put("http_host_class", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "http_host_class"), httpHostClass.getKey())); - aadmEvent.getParameterMap().put("PROBE_ON", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "PROBE_ON"), probeOnFlag.getKey())); - aadmEvent.getParameterMap().put("TCP_ON", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "TCP_ON"), tcpOnFlag.getKey())); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "http_host_class"), httpHostClass.getKey())); + aadmEvent.getParameterMap().put(PROBE_ON, + new AxField(new AxReferenceKey(aadmEvent.getKey(), PROBE_ON), probeOnFlag.getKey())); + aadmEvent.getParameterMap().put(TCP_ON, + new AxField(new AxReferenceKey(aadmEvent.getKey(), TCP_ON), tcpOnFlag.getKey())); aadmEvent.getParameterMap().put("SGW_IP_ADDRESS", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "SGW_IP_ADDRESS"), nwIpAddress.getKey())); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "SGW_IP_ADDRESS"), nwIpAddress.getKey())); aadmEvent.getParameterMap().put("UE_IP_ADDRESS", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "UE_IP_ADDRESS"), ueIpAddress.getKey())); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "UE_IP_ADDRESS"), ueIpAddress.getKey())); aadmEvent.getParameterMap().put("SERVICE_REQUEST_COUNT", new AxField( - new AxReferenceKey(aadmEvent.getKey(), "SERVICE_REQUEST_COUNT"), serviceRequestCount.getKey())); + new AxReferenceKey(aadmEvent.getKey(), "SERVICE_REQUEST_COUNT"), serviceRequestCount.getKey())); aadmEvent.getParameterMap().put("ATTACH_COUNT", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "ATTACH_COUNT"), attchCount.getKey())); - aadmEvent.getParameterMap().put("NUM_SUBSCRIBERS", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "NUM_SUBSCRIBERS"), subscriberCount.getKey())); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "ATTACH_COUNT"), attchCount.getKey())); + aadmEvent.getParameterMap().put("NUM_SUBSCRIBERS", new AxField( + new AxReferenceKey(aadmEvent.getKey(), "NUM_SUBSCRIBERS"), subscriberCount.getKey())); aadmEvent.getParameterMap().put("AVG_SUBSCRIBER_SERVICE_REQUEST", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "AVG_SUBSCRIBER_SERVICE_REQUEST"), - averageServiceRequest.getKey())); - aadmEvent.getParameterMap().put("AVG_SUBSCRIBER_ATTACH", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "AVG_SUBSCRIBER_ATTACH"), averageAttach.getKey())); - aadmEvent.getParameterMap().put("ACTTASK", - new AxField(new AxReferenceKey(aadmEvent.getKey(), "ACTTASK"), actionTask.getKey())); - - final AxEvent aadmXStreamActEvent = new AxEvent(new AxArtifactKey("XSTREAM_AADM_ACT_EVENT", "0.0.1"), - "org.onap.policy.apex.examples.aadm.events"); + new AxField(new AxReferenceKey(aadmEvent.getKey(), "AVG_SUBSCRIBER_SERVICE_REQUEST"), + averageServiceRequest.getKey())); + aadmEvent.getParameterMap().put("AVG_SUBSCRIBER_ATTACH", new AxField( + new AxReferenceKey(aadmEvent.getKey(), "AVG_SUBSCRIBER_ATTACH"), averageAttach.getKey())); + aadmEvent.getParameterMap().put(ACTTASK, + new AxField(new AxReferenceKey(aadmEvent.getKey(), ACTTASK), actionTask.getKey())); + + final AxEvent aadmXStreamActEvent = new AxEvent(new AxArtifactKey("XSTREAM_AADM_ACT_EVENT", DEFAULT_VERSION), + DEFAULT_NAMESPACE); aadmXStreamActEvent.setSource("Apex"); - aadmXStreamActEvent.setTarget("External"); + aadmXStreamActEvent.setTarget(DEFAULT_SOURCE); aadmXStreamActEvent.getParameterMap().put("IMSI", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "IMSI"), imsi.getKey())); - aadmXStreamActEvent.getParameterMap().put("IMSI_IP", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "IMSI_IP"), ueIpAddress.getKey())); - aadmXStreamActEvent.getParameterMap().put("ENODEB_ID", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "ENODEB_ID"), eNodeBId.getKey())); - aadmXStreamActEvent.getParameterMap().put("NW_IP", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "NW_IP"), nwIpAddress.getKey())); - aadmXStreamActEvent.getParameterMap().put("ACTTASK", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "ACTTASK"), actionTask.getKey())); - aadmXStreamActEvent.getParameterMap().put("PROBE_ON", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "PROBE_ON"), probeOnFlag.getKey())); - aadmXStreamActEvent.getParameterMap().put("TCP_ON", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "TCP_ON"), tcpOnFlag.getKey())); - aadmXStreamActEvent.getParameterMap().put("VERSION", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "VERSION"), version.getKey())); - aadmXStreamActEvent.getParameterMap().put("TRIGGER_SPEC", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "TRIGGER_SPEC"), triggerSpec.getKey())); + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "IMSI"), imsi.getKey())); + aadmXStreamActEvent.getParameterMap().put(IMSI_IP, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), IMSI_IP), ueIpAddress.getKey())); + aadmXStreamActEvent.getParameterMap().put(ENODEB_ID, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), ENODEB_ID), eNodeBId.getKey())); + aadmXStreamActEvent.getParameterMap().put(NW_IP, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), NW_IP), nwIpAddress.getKey())); + aadmXStreamActEvent.getParameterMap().put(ACTTASK, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), ACTTASK), actionTask.getKey())); + aadmXStreamActEvent.getParameterMap().put(PROBE_ON, new AxField( + new AxReferenceKey(aadmXStreamActEvent.getKey(), PROBE_ON), probeOnFlag.getKey())); + aadmXStreamActEvent.getParameterMap().put(TCP_ON, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), TCP_ON), tcpOnFlag.getKey())); + aadmXStreamActEvent.getParameterMap().put(VERSION, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), VERSION), version.getKey())); + aadmXStreamActEvent.getParameterMap().put("TRIGGER_SPEC", new AxField( + new AxReferenceKey(aadmXStreamActEvent.getKey(), "TRIGGER_SPEC"), triggerSpec.getKey())); aadmXStreamActEvent.getParameterMap().put("MAJ_MIN_MAINT_VERSION", new AxField( - new AxReferenceKey(aadmXStreamActEvent.getKey(), "MAJ_MIN_MAINT_VERSION"), version.getKey())); - aadmXStreamActEvent.getParameterMap().put("BLACKLIST_ON", new AxField( - new AxReferenceKey(aadmXStreamActEvent.getKey(), "BLACKLIST_ON"), blacklistOnFlag.getKey())); - aadmXStreamActEvent.getParameterMap().put("PROFILE", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "PROFILE"), profile.getKey())); - aadmXStreamActEvent.getParameterMap().put("THRESHOLD", - new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), "THRESHOLD"), threshold.getKey())); - - final AxEvent vMmeEvent = - new AxEvent(new AxArtifactKey("VMMEEvent", "0.0.1"), "org.onap.policy.apex.examples.aadm.events"); - vMmeEvent.setSource("External"); + new AxReferenceKey(aadmXStreamActEvent.getKey(), "MAJ_MIN_MAINT_VERSION"), version.getKey())); + aadmXStreamActEvent.getParameterMap().put(BLACKLIST_ON, new AxField( + new AxReferenceKey(aadmXStreamActEvent.getKey(), BLACKLIST_ON), blacklistOnFlag.getKey())); + aadmXStreamActEvent.getParameterMap().put(PROFILE2, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), PROFILE2), profile.getKey())); + aadmXStreamActEvent.getParameterMap().put(THRESHOLD, + new AxField(new AxReferenceKey(aadmXStreamActEvent.getKey(), THRESHOLD), threshold.getKey())); + + final AxEvent vMmeEvent = new AxEvent(new AxArtifactKey("VMMEEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + vMmeEvent.setSource(DEFAULT_SOURCE); vMmeEvent.setTarget("Apex"); vMmeEvent.getParameterMap().put("IMSI", - new AxField(new AxReferenceKey(vMmeEvent.getKey(), "IMSI"), imsi.getKey())); - vMmeEvent.getParameterMap().put("ENODEB_ID", - new AxField(new AxReferenceKey(vMmeEvent.getKey(), "ENODEB_ID"), eNodeBId.getKey())); - vMmeEvent.getParameterMap().put("IMSI_IP", - new AxField(new AxReferenceKey(vMmeEvent.getKey(), "IMSI_IP"), ueIpAddress.getKey())); - vMmeEvent.getParameterMap().put("NW_IP", - new AxField(new AxReferenceKey(vMmeEvent.getKey(), "NW_IP"), nwIpAddress.getKey())); - vMmeEvent.getParameterMap().put("PROFILE", - new AxField(new AxReferenceKey(vMmeEvent.getKey(), "PROFILE"), profile.getKey())); - vMmeEvent.getParameterMap().put("THRESHOLD", - new AxField(new AxReferenceKey(vMmeEvent.getKey(), "THRESHOLD"), threshold.getKey())); - - final AxEvent sapcEvent = - new AxEvent(new AxArtifactKey("SAPCEvent", "0.0.1"), "org.onap.policy.apex.examples.aadm.events"); - sapcEvent.setSource("External"); + new AxField(new AxReferenceKey(vMmeEvent.getKey(), "IMSI"), imsi.getKey())); + vMmeEvent.getParameterMap().put(ENODEB_ID, + new AxField(new AxReferenceKey(vMmeEvent.getKey(), ENODEB_ID), eNodeBId.getKey())); + vMmeEvent.getParameterMap().put(IMSI_IP, + new AxField(new AxReferenceKey(vMmeEvent.getKey(), IMSI_IP), ueIpAddress.getKey())); + vMmeEvent.getParameterMap().put(NW_IP, + new AxField(new AxReferenceKey(vMmeEvent.getKey(), NW_IP), nwIpAddress.getKey())); + vMmeEvent.getParameterMap().put(PROFILE2, + new AxField(new AxReferenceKey(vMmeEvent.getKey(), PROFILE2), profile.getKey())); + vMmeEvent.getParameterMap().put(THRESHOLD, + new AxField(new AxReferenceKey(vMmeEvent.getKey(), THRESHOLD), threshold.getKey())); + + final AxEvent sapcEvent = new AxEvent(new AxArtifactKey("SAPCEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + sapcEvent.setSource(DEFAULT_SOURCE); sapcEvent.setTarget("Apex"); sapcEvent.getParameterMap().put("IMSI", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "IMSI"), imsi.getKey())); - sapcEvent.getParameterMap().put("ENODEB_ID", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "ENODEB_ID"), eNodeBId.getKey())); - sapcEvent.getParameterMap().put("IMSI_IP", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "IMSI_IP"), ueIpAddress.getKey())); - sapcEvent.getParameterMap().put("NW_IP", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "NW_IP"), nwIpAddress.getKey())); - sapcEvent.getParameterMap().put("PROFILE", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "PROFILE"), profile.getKey())); - sapcEvent.getParameterMap().put("THRESHOLD", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "THRESHOLD"), threshold.getKey())); - sapcEvent.getParameterMap().put("TCP_ON", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "TCP_ON"), tcpOnFlag.getKey())); - sapcEvent.getParameterMap().put("PROBE_ON", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "PROBE_ON"), probeOnFlag.getKey())); - sapcEvent.getParameterMap().put("VERSION", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "VERSION"), version.getKey())); - sapcEvent.getParameterMap().put("BLACKLIST_ON", - new AxField(new AxReferenceKey(sapcEvent.getKey(), "BLACKLIST_ON"), blacklistOnFlag.getKey())); - - final AxEvent sapcBlacklistSubscriberEvent = - new AxEvent(new AxArtifactKey("SAPCBlacklistSubscriberEvent", "0.0.1"), - "org.onap.policy.apex.examples.aadm.events"); + new AxField(new AxReferenceKey(sapcEvent.getKey(), "IMSI"), imsi.getKey())); + sapcEvent.getParameterMap().put(ENODEB_ID, + new AxField(new AxReferenceKey(sapcEvent.getKey(), ENODEB_ID), eNodeBId.getKey())); + sapcEvent.getParameterMap().put(IMSI_IP, + new AxField(new AxReferenceKey(sapcEvent.getKey(), IMSI_IP), ueIpAddress.getKey())); + sapcEvent.getParameterMap().put(NW_IP, + new AxField(new AxReferenceKey(sapcEvent.getKey(), NW_IP), nwIpAddress.getKey())); + sapcEvent.getParameterMap().put(PROFILE2, + new AxField(new AxReferenceKey(sapcEvent.getKey(), PROFILE2), profile.getKey())); + sapcEvent.getParameterMap().put(THRESHOLD, + new AxField(new AxReferenceKey(sapcEvent.getKey(), THRESHOLD), threshold.getKey())); + sapcEvent.getParameterMap().put(TCP_ON, + new AxField(new AxReferenceKey(sapcEvent.getKey(), TCP_ON), tcpOnFlag.getKey())); + sapcEvent.getParameterMap().put(PROBE_ON, + new AxField(new AxReferenceKey(sapcEvent.getKey(), PROBE_ON), probeOnFlag.getKey())); + sapcEvent.getParameterMap().put(VERSION, + new AxField(new AxReferenceKey(sapcEvent.getKey(), VERSION), version.getKey())); + sapcEvent.getParameterMap().put(BLACKLIST_ON, + new AxField(new AxReferenceKey(sapcEvent.getKey(), BLACKLIST_ON), blacklistOnFlag.getKey())); + + final AxEvent sapcBlacklistSubscriberEvent = new AxEvent( + new AxArtifactKey("SAPCBlacklistSubscriberEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); sapcBlacklistSubscriberEvent.setSource("Apex"); - sapcBlacklistSubscriberEvent.setTarget("External"); + sapcBlacklistSubscriberEvent.setTarget(DEFAULT_SOURCE); sapcBlacklistSubscriberEvent.getParameterMap().put("IMSI", - new AxField(new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "IMSI"), imsi.getKey())); - sapcBlacklistSubscriberEvent.getParameterMap().put("PROFILE", - new AxField(new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "PROFILE"), profile.getKey())); - sapcBlacklistSubscriberEvent.getParameterMap().put("BLACKLIST_ON", new AxField( - new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "BLACKLIST_ON"), blacklistOnFlag.getKey())); - sapcBlacklistSubscriberEvent.getParameterMap().put("IMSI_IP", new AxField( - new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "IMSI_IP"), ueIpAddress.getKey())); - sapcBlacklistSubscriberEvent.getParameterMap().put("NW_IP", - new AxField(new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "NW_IP"), nwIpAddress.getKey())); - sapcBlacklistSubscriberEvent.getParameterMap().put("PROBE_ON", new AxField( - new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "PROBE_ON"), probeOnFlag.getKey())); - sapcBlacklistSubscriberEvent.getParameterMap().put("TCP_ON", - new AxField(new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "TCP_ON"), tcpOnFlag.getKey())); - - final AxEvent periodicEvent = - new AxEvent(new AxArtifactKey("PeriodicEvent", "0.0.1"), "org.onap.policy.apex.examples.aadm.events"); + new AxField(new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), "IMSI"), imsi.getKey())); + sapcBlacklistSubscriberEvent.getParameterMap().put(PROFILE2, new AxField( + new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), PROFILE2), profile.getKey())); + sapcBlacklistSubscriberEvent.getParameterMap().put(BLACKLIST_ON, + new AxField(new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), BLACKLIST_ON), + blacklistOnFlag.getKey())); + sapcBlacklistSubscriberEvent.getParameterMap().put(IMSI_IP, new AxField( + new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), IMSI_IP), ueIpAddress.getKey())); + sapcBlacklistSubscriberEvent.getParameterMap().put(NW_IP, new AxField( + new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), NW_IP), nwIpAddress.getKey())); + sapcBlacklistSubscriberEvent.getParameterMap().put(PROBE_ON, new AxField( + new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), PROBE_ON), probeOnFlag.getKey())); + sapcBlacklistSubscriberEvent.getParameterMap().put(TCP_ON, new AxField( + new AxReferenceKey(sapcBlacklistSubscriberEvent.getKey(), TCP_ON), tcpOnFlag.getKey())); + + final AxEvent periodicEvent = new AxEvent(new AxArtifactKey("PeriodicEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); periodicEvent.setSource("System"); periodicEvent.setTarget("Apex"); - periodicEvent.getParameterMap().put("PERIODIC_EVENT_COUNT", new AxField( - new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_EVENT_COUNT"), periodicEventCount.getKey())); - periodicEvent.getParameterMap().put("PERIODIC_DELAY", - new AxField(new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_DELAY"), periodicDelay.getKey())); - periodicEvent.getParameterMap().put("PERIODIC_FIRST_TIME", - new AxField(new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_FIRST_TIME"), periodicTime.getKey())); + periodicEvent.getParameterMap().put("PERIODIC_EVENT_COUNT", + new AxField(new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_EVENT_COUNT"), + periodicEventCount.getKey())); + periodicEvent.getParameterMap().put("PERIODIC_DELAY", new AxField( + new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_DELAY"), periodicDelay.getKey())); + periodicEvent.getParameterMap().put("PERIODIC_FIRST_TIME", new AxField( + new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_FIRST_TIME"), periodicTime.getKey())); periodicEvent.getParameterMap().put("PERIODIC_CURRENT_TIME", new AxField( - new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_CURRENT_TIME"), periodicTime.getKey())); - periodicEvent.getParameterMap().put("PERIODIC_LAST_TIME", - new AxField(new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_LAST_TIME"), periodicTime.getKey())); + new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_CURRENT_TIME"), periodicTime.getKey())); + periodicEvent.getParameterMap().put("PERIODIC_LAST_TIME", new AxField( + new AxReferenceKey(periodicEvent.getKey(), "PERIODIC_LAST_TIME"), periodicTime.getKey())); - final AxEvents aadmEvents = new AxEvents(new AxArtifactKey("AADMEvents", "0.0.1")); + final AxEvents aadmEvents = new AxEvents(new AxArtifactKey("AADMEvents", DEFAULT_VERSION)); aadmEvents.getEventMap().put(aadmEvent.getKey(), aadmEvent); aadmEvents.getEventMap().put(aadmXStreamActEvent.getKey(), aadmXStreamActEvent); aadmEvents.getEventMap().put(vMmeEvent.getKey(), vMmeEvent); @@ -302,151 +335,155 @@ public class AadmDomainModelFactory { aadmEvents.getEventMap().put(periodicEvent.getKey(), periodicEvent); // Data types for context - final AxContextSchema eNodeBStatus = new AxContextSchema(new AxArtifactKey("ENodeBStatus", "0.0.1"), "Java", - "org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus"); - final AxContextSchema imsiStatus = new AxContextSchema(new AxArtifactKey("IMSIStatus", "0.0.1"), "Java", - "org.onap.policy.apex.examples.aadm.concepts.ImsiStatus"); - final AxContextSchema ipAddressStatus = new AxContextSchema(new AxArtifactKey("IPAddressStatus", "0.0.1"), - "Java", "org.onap.policy.apex.examples.aadm.concepts.IpAddressStatus"); + final AxContextSchema eNodeBStatus = new AxContextSchema(new AxArtifactKey("ENodeBStatus", DEFAULT_VERSION), + "Java", "org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus"); + final AxContextSchema imsiStatus = new AxContextSchema(new AxArtifactKey("IMSIStatus", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.examples.aadm.concepts.ImsiStatus"); + final AxContextSchema ipAddressStatus = new AxContextSchema( + new AxArtifactKey("IPAddressStatus", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.examples.aadm.concepts.IpAddressStatus"); aadmContextSchemas.getSchemasMap().put(eNodeBStatus.getKey(), eNodeBStatus); aadmContextSchemas.getSchemasMap().put(imsiStatus.getKey(), imsiStatus); aadmContextSchemas.getSchemasMap().put(ipAddressStatus.getKey(), ipAddressStatus); // Three context albums for AADM - final AxContextAlbum eNodeBStatusAlbum = new AxContextAlbum(new AxArtifactKey("ENodeBStatusAlbum", "0.0.1"), - "APPLICATION", true, eNodeBStatus.getKey()); - final AxContextAlbum imsiStatusAlbum = new AxContextAlbum(new AxArtifactKey("IMSIStatusAlbum", "0.0.1"), - "APPLICATION", true, imsiStatus.getKey()); + final AxContextAlbum eNodeBStatusAlbum = new AxContextAlbum( + new AxArtifactKey("ENodeBStatusAlbum", DEFAULT_VERSION), APPLICATION, true, + eNodeBStatus.getKey()); + final AxContextAlbum imsiStatusAlbum = new AxContextAlbum(new AxArtifactKey("IMSIStatusAlbum", DEFAULT_VERSION), + APPLICATION, true, imsiStatus.getKey()); final AxContextAlbum ipAddressStatusAlbum = new AxContextAlbum( - new AxArtifactKey("IPAddressStatusAlbum", "0.0.1"), "APPLICATION", true, ipAddressStatus.getKey()); + new AxArtifactKey("IPAddressStatusAlbum", DEFAULT_VERSION), APPLICATION, true, + ipAddressStatus.getKey()); - final AxContextAlbums aadmAlbums = new AxContextAlbums(new AxArtifactKey("AADMContext", "0.0.1")); + final AxContextAlbums aadmAlbums = new AxContextAlbums(new AxArtifactKey("AADMContext", DEFAULT_VERSION)); aadmAlbums.getAlbumsMap().put(eNodeBStatusAlbum.getKey(), eNodeBStatusAlbum); aadmAlbums.getAlbumsMap().put(imsiStatusAlbum.getKey(), imsiStatusAlbum); aadmAlbums.getAlbumsMap().put(ipAddressStatusAlbum.getKey(), ipAddressStatusAlbum); // Tasks - final AxLogicReader logicReader = - new PolicyLogicReader().setLogicPackage(this.getClass().getPackage().getName()).setDefaultLogic(null); + final AxLogicReader logicReader = new PolicyLogicReader() + .setLogicPackage(this.getClass().getPackage().getName()).setDefaultLogic(null); - final AxTask aadmMatchTask = new AxTask(new AxArtifactKey("AADMMatchTask", "0.0.1")); + final AxTask aadmMatchTask = new AxTask(new AxArtifactKey("AADMMatchTask", DEFAULT_VERSION)); aadmMatchTask.duplicateInputFields(aadmEvent.getParameterMap()); aadmMatchTask.duplicateOutputFields(aadmEvent.getParameterMap()); aadmMatchTask.getContextAlbumReferences().add(eNodeBStatusAlbum.getKey()); aadmMatchTask.getContextAlbumReferences().add(imsiStatusAlbum.getKey()); aadmMatchTask.getContextAlbumReferences().add(ipAddressStatusAlbum.getKey()); - aadmMatchTask.setTaskLogic(new AxTaskLogic(aadmMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + aadmMatchTask.setTaskLogic(new AxTaskLogic(aadmMatchTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask aadmEstablishTask = new AxTask(new AxArtifactKey("AADMEstablishTask", "0.0.1")); + final AxTask aadmEstablishTask = new AxTask(new AxArtifactKey("AADMEstablishTask", DEFAULT_VERSION)); aadmEstablishTask.duplicateInputFields(aadmEvent.getParameterMap()); aadmEstablishTask.duplicateOutputFields(aadmEvent.getParameterMap()); - logicReader.setDefaultLogic("Default_TaskLogic"); - aadmEstablishTask.setTaskLogic(new AxTaskLogic(aadmEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + logicReader.setDefaultLogic(DEFAULT_TASK_LOGIC); + aadmEstablishTask.setTaskLogic(new AxTaskLogic(aadmEstablishTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask aadmDecideTask = new AxTask(new AxArtifactKey("AADMDecideTask", "0.0.1")); + final AxTask aadmDecideTask = new AxTask(new AxArtifactKey("AADMDecideTask", DEFAULT_VERSION)); aadmDecideTask.duplicateInputFields(aadmEvent.getParameterMap()); aadmDecideTask.duplicateOutputFields(aadmEvent.getParameterMap()); - aadmDecideTask.setTaskLogic(new AxTaskLogic(aadmDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + aadmDecideTask.setTaskLogic(new AxTaskLogic(aadmDecideTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); logicReader.setDefaultLogic(null); - final AxTask aadmDoSSuggestionActTask = new AxTask(new AxArtifactKey("AADMDoSSuggestionActTask", "0.0.1")); + final AxTask aadmDoSSuggestionActTask = new AxTask( + new AxArtifactKey("AADMDoSSuggestionActTask", DEFAULT_VERSION)); aadmDoSSuggestionActTask.duplicateInputFields(aadmEvent.getParameterMap()); aadmDoSSuggestionActTask.duplicateOutputFields(aadmXStreamActEvent.getParameterMap()); aadmDoSSuggestionActTask.getContextAlbumReferences().add(eNodeBStatusAlbum.getKey()); aadmDoSSuggestionActTask.getContextAlbumReferences().add(imsiStatusAlbum.getKey()); - aadmDoSSuggestionActTask - .setTaskLogic(new AxTaskLogic(aadmDoSSuggestionActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + aadmDoSSuggestionActTask.setTaskLogic( + new AxTaskLogic(aadmDoSSuggestionActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask aadmNoActTask = new AxTask(new AxArtifactKey("AADMNoActTask", "0.0.1")); + final AxTask aadmNoActTask = new AxTask(new AxArtifactKey("AADMNoActTask", DEFAULT_VERSION)); aadmNoActTask.duplicateInputFields(aadmEvent.getParameterMap()); aadmNoActTask.duplicateOutputFields(aadmXStreamActEvent.getParameterMap()); - aadmNoActTask.setTaskLogic(new AxTaskLogic(aadmNoActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + aadmNoActTask.setTaskLogic(new AxTaskLogic(aadmNoActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask aadmDoSProvenActTask = new AxTask(new AxArtifactKey("AADMDoSProvenActTask", "0.0.1")); + final AxTask aadmDoSProvenActTask = new AxTask(new AxArtifactKey("AADMDoSProvenActTask", DEFAULT_VERSION)); aadmDoSProvenActTask.duplicateInputFields(aadmEvent.getParameterMap()); aadmDoSProvenActTask.duplicateOutputFields(aadmXStreamActEvent.getParameterMap()); aadmDoSProvenActTask.getContextAlbumReferences().add(eNodeBStatusAlbum.getKey()); aadmDoSProvenActTask.getContextAlbumReferences().add(imsiStatusAlbum.getKey()); aadmDoSProvenActTask - .setTaskLogic(new AxTaskLogic(aadmDoSProvenActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(aadmDoSProvenActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask vMmeMatchTask = new AxTask(new AxArtifactKey("VMMEMatchTask", "0.0.1")); + final AxTask vMmeMatchTask = new AxTask(new AxArtifactKey("VMMEMatchTask", DEFAULT_VERSION)); vMmeMatchTask.duplicateInputFields(vMmeEvent.getParameterMap()); vMmeMatchTask.duplicateOutputFields(vMmeEvent.getParameterMap()); - vMmeMatchTask.setTaskLogic(new AxTaskLogic(vMmeMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + vMmeMatchTask.setTaskLogic(new AxTaskLogic(vMmeMatchTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask vMmeEstablishTask = new AxTask(new AxArtifactKey("VMMEEstablishTask", "0.0.1")); + final AxTask vMmeEstablishTask = new AxTask(new AxArtifactKey("VMMEEstablishTask", DEFAULT_VERSION)); vMmeEstablishTask.duplicateInputFields(vMmeEvent.getParameterMap()); vMmeEstablishTask.duplicateOutputFields(vMmeEvent.getParameterMap()); - logicReader.setDefaultLogic("Default_TaskLogic"); - vMmeEstablishTask.setTaskLogic(new AxTaskLogic(vMmeEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + logicReader.setDefaultLogic(DEFAULT_TASK_LOGIC); + vMmeEstablishTask.setTaskLogic(new AxTaskLogic(vMmeEstablishTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask vMmeDecideTask = new AxTask(new AxArtifactKey("VMMEDecideTask", "0.0.1")); + final AxTask vMmeDecideTask = new AxTask(new AxArtifactKey("VMMEDecideTask", DEFAULT_VERSION)); vMmeDecideTask.duplicateInputFields(vMmeEvent.getParameterMap()); vMmeDecideTask.duplicateOutputFields(vMmeEvent.getParameterMap()); - vMmeDecideTask.setTaskLogic(new AxTaskLogic(vMmeDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + vMmeDecideTask.setTaskLogic(new AxTaskLogic(vMmeDecideTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask vMmeNoActTask = new AxTask(new AxArtifactKey("VMMENoActTask", "0.0.1")); + final AxTask vMmeNoActTask = new AxTask(new AxArtifactKey("VMMENoActTask", DEFAULT_VERSION)); vMmeNoActTask.duplicateInputFields(vMmeEvent.getParameterMap()); vMmeNoActTask.duplicateOutputFields(vMmeEvent.getParameterMap()); - vMmeNoActTask.setTaskLogic(new AxTaskLogic(vMmeNoActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + vMmeNoActTask.setTaskLogic(new AxTaskLogic(vMmeNoActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask vMmeActTask = new AxTask(new AxArtifactKey("VMMEActTask", "0.0.1")); + final AxTask vMmeActTask = new AxTask(new AxArtifactKey("VMMEActTask", DEFAULT_VERSION)); vMmeActTask.duplicateInputFields(vMmeEvent.getParameterMap()); vMmeActTask.duplicateOutputFields(vMmeEvent.getParameterMap()); logicReader.setDefaultLogic(null); - vMmeActTask.setTaskLogic(new AxTaskLogic(vMmeActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + vMmeActTask.setTaskLogic(new AxTaskLogic(vMmeActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask sapcMatchTask = new AxTask(new AxArtifactKey("SAPCMatchTask", "0.0.1")); + final AxTask sapcMatchTask = new AxTask(new AxArtifactKey("SAPCMatchTask", DEFAULT_VERSION)); sapcMatchTask.duplicateInputFields(sapcEvent.getParameterMap()); sapcMatchTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); - sapcMatchTask.setTaskLogic(new AxTaskLogic(sapcMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + sapcMatchTask.setTaskLogic(new AxTaskLogic(sapcMatchTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask sapcEstablishTask = new AxTask(new AxArtifactKey("SAPCEstablishTask", "0.0.1")); + final AxTask sapcEstablishTask = new AxTask(new AxArtifactKey("SAPCEstablishTask", DEFAULT_VERSION)); sapcEstablishTask.duplicateInputFields(sapcEvent.getParameterMap()); sapcEstablishTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); - logicReader.setDefaultLogic("Default_TaskLogic"); - sapcEstablishTask.setTaskLogic(new AxTaskLogic(sapcEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + logicReader.setDefaultLogic(DEFAULT_TASK_LOGIC); + sapcEstablishTask.setTaskLogic(new AxTaskLogic(sapcEstablishTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask sapcDecideTask = new AxTask(new AxArtifactKey("SAPCDecideTask", "0.0.1")); + final AxTask sapcDecideTask = new AxTask(new AxArtifactKey("SAPCDecideTask", DEFAULT_VERSION)); sapcDecideTask.duplicateInputFields(sapcEvent.getParameterMap()); sapcDecideTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); - sapcDecideTask.setTaskLogic(new AxTaskLogic(sapcDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + sapcDecideTask.setTaskLogic(new AxTaskLogic(sapcDecideTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask sapcActTask = new AxTask(new AxArtifactKey("SAPCActTask", "0.0.1")); + final AxTask sapcActTask = new AxTask(new AxArtifactKey("SAPCActTask", DEFAULT_VERSION)); sapcActTask.duplicateInputFields(sapcEvent.getParameterMap()); sapcActTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); sapcActTask.getContextAlbumReferences().add(imsiStatusAlbum.getKey()); logicReader.setDefaultLogic(null); - sapcActTask.setTaskLogic(new AxTaskLogic(sapcActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + sapcActTask.setTaskLogic(new AxTaskLogic(sapcActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - logicReader.setDefaultLogic("Default_TaskLogic"); + logicReader.setDefaultLogic(DEFAULT_TASK_LOGIC); - final AxTask periodicMatchTask = new AxTask(new AxArtifactKey("PeriodicMatchTask", "0.0.1")); + final AxTask periodicMatchTask = new AxTask(new AxArtifactKey("PeriodicMatchTask", DEFAULT_VERSION)); periodicMatchTask.duplicateInputFields(periodicEvent.getParameterMap()); periodicMatchTask.duplicateOutputFields(periodicEvent.getParameterMap()); - periodicMatchTask.setTaskLogic(new AxTaskLogic(periodicMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + periodicMatchTask.setTaskLogic(new AxTaskLogic(periodicMatchTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask periodicEstablishTask = new AxTask(new AxArtifactKey("PeriodicEstablishTask", "0.0.1")); + final AxTask periodicEstablishTask = new AxTask(new AxArtifactKey("PeriodicEstablishTask", DEFAULT_VERSION)); periodicEstablishTask.duplicateInputFields(periodicEvent.getParameterMap()); periodicEstablishTask.duplicateOutputFields(periodicEvent.getParameterMap()); - periodicEstablishTask - .setTaskLogic(new AxTaskLogic(periodicEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + periodicEstablishTask.setTaskLogic( + new AxTaskLogic(periodicEstablishTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask periodicDecideTask = new AxTask(new AxArtifactKey("PeriodicDecideTask", "0.0.1")); + final AxTask periodicDecideTask = new AxTask(new AxArtifactKey("PeriodicDecideTask", DEFAULT_VERSION)); periodicDecideTask.duplicateInputFields(periodicEvent.getParameterMap()); periodicDecideTask.duplicateOutputFields(periodicEvent.getParameterMap()); - periodicDecideTask.setTaskLogic(new AxTaskLogic(periodicDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + periodicDecideTask.setTaskLogic(new AxTaskLogic(periodicDecideTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask periodicActTask = new AxTask(new AxArtifactKey("PeriodicActTask", "0.0.1")); + final AxTask periodicActTask = new AxTask(new AxArtifactKey("PeriodicActTask", DEFAULT_VERSION)); periodicActTask.duplicateInputFields(periodicEvent.getParameterMap()); periodicActTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); periodicActTask.getContextAlbumReferences().add(imsiStatusAlbum.getKey()); logicReader.setDefaultLogic(null); - periodicActTask.setTaskLogic(new AxTaskLogic(periodicActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + periodicActTask.setTaskLogic(new AxTaskLogic(periodicActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTasks aadmTasks = new AxTasks(new AxArtifactKey("AADMTasks", "0.0.1")); + final AxTasks aadmTasks = new AxTasks(new AxArtifactKey("AADMTasks", DEFAULT_VERSION)); aadmTasks.getTaskMap().put(aadmMatchTask.getKey(), aadmMatchTask); aadmTasks.getTaskMap().put(aadmEstablishTask.getKey(), aadmEstablishTask); aadmTasks.getTaskMap().put(aadmDecideTask.getKey(), aadmDecideTask); @@ -470,64 +507,65 @@ public class AadmDomainModelFactory { // Policies logicReader.setDefaultLogic(null); - final AxPolicy aadmPolicy = new AxPolicy(new AxArtifactKey("AADMPolicy", "0.0.1")); + final AxPolicy aadmPolicy = new AxPolicy(new AxArtifactKey("AADMPolicy", DEFAULT_VERSION)); aadmPolicy.setTemplate("MEDA"); final AxState aadmActState = new AxState(new AxReferenceKey(aadmPolicy.getKey(), "Act")); aadmActState.setTrigger(aadmEvent.getKey()); - final AxStateOutput aadmAct2Out = - new AxStateOutput(aadmActState.getKey(), AxReferenceKey.getNullKey(), aadmXStreamActEvent.getKey()); + final AxStateOutput aadmAct2Out = new AxStateOutput(aadmActState.getKey(), AxReferenceKey.getNullKey(), + aadmXStreamActEvent.getKey()); aadmActState.getStateOutputs().put(aadmAct2Out.getKey().getLocalName(), aadmAct2Out); aadmActState.getContextAlbumReferences().add(ipAddressStatusAlbum.getKey()); aadmActState.getContextAlbumReferences().add(imsiStatusAlbum.getKey()); aadmActState.getContextAlbumReferences().add(eNodeBStatusAlbum.getKey()); aadmActState.setTaskSelectionLogic( - new AxTaskSelectionLogic(aadmActState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + new AxTaskSelectionLogic(aadmActState.getKey(), TASK_SELECTION_LOGIC, "MVEL", logicReader)); aadmActState.setDefaultTask(aadmNoActTask.getKey()); aadmActState.getTaskReferences().put(aadmNoActTask.getKey(), new AxStateTaskReference(aadmActState.getKey(), - aadmNoActTask.getKey(), AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); + aadmNoActTask.getKey(), AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); aadmActState.getTaskReferences().put(aadmDoSSuggestionActTask.getKey(), - new AxStateTaskReference(aadmActState.getKey(), aadmDoSSuggestionActTask.getKey(), - AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); + new AxStateTaskReference(aadmActState.getKey(), aadmDoSSuggestionActTask.getKey(), + AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); aadmActState.getTaskReferences().put(aadmDoSProvenActTask.getKey(), - new AxStateTaskReference(aadmActState.getKey(), aadmDoSProvenActTask.getKey(), - AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); + new AxStateTaskReference(aadmActState.getKey(), aadmDoSProvenActTask.getKey(), + AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); - logicReader.setDefaultLogic("Default_TaskSelectionLogic"); + logicReader.setDefaultLogic("DefaultTaskSelectionLogic"); - final AxState aadmDecideState = new AxState(new AxReferenceKey(aadmPolicy.getKey(), "Decide")); + final AxState aadmDecideState = new AxState(new AxReferenceKey(aadmPolicy.getKey(), DECIDE)); aadmDecideState.setTrigger(aadmEvent.getKey()); - final AxStateOutput aadmDec2Act = - new AxStateOutput(aadmDecideState.getKey(), aadmActState.getKey(), aadmEvent.getKey()); + final AxStateOutput aadmDec2Act = new AxStateOutput(aadmDecideState.getKey(), aadmActState.getKey(), + aadmEvent.getKey()); aadmDecideState.getStateOutputs().put(aadmDec2Act.getKey().getLocalName(), aadmDec2Act); aadmDecideState.setTaskSelectionLogic( - new AxTaskSelectionLogic(aadmDecideState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + new AxTaskSelectionLogic(aadmDecideState.getKey(), TASK_SELECTION_LOGIC, "MVEL", logicReader)); aadmDecideState.setDefaultTask(aadmDecideTask.getKey()); - aadmDecideState.getTaskReferences().put(aadmDecideTask.getKey(), new AxStateTaskReference( - aadmDecideState.getKey(), aadmDecideTask.getKey(), AxStateTaskOutputType.DIRECT, aadmDec2Act.getKey())); + aadmDecideState.getTaskReferences().put(aadmDecideTask.getKey(), + new AxStateTaskReference(aadmDecideState.getKey(), aadmDecideTask.getKey(), + AxStateTaskOutputType.DIRECT, aadmDec2Act.getKey())); - final AxState aadmEstablishState = new AxState(new AxReferenceKey(aadmPolicy.getKey(), "Establish")); + final AxState aadmEstablishState = new AxState(new AxReferenceKey(aadmPolicy.getKey(), ESTABLISH)); aadmEstablishState.setTrigger(aadmEvent.getKey()); - final AxStateOutput aadmEst2Dec = - new AxStateOutput(aadmEstablishState.getKey(), aadmDecideState.getKey(), aadmEvent.getKey()); + final AxStateOutput aadmEst2Dec = new AxStateOutput(aadmEstablishState.getKey(), aadmDecideState.getKey(), + aadmEvent.getKey()); aadmEstablishState.getStateOutputs().put(aadmEst2Dec.getKey().getLocalName(), aadmEst2Dec); - aadmEstablishState.setTaskSelectionLogic( - new AxTaskSelectionLogic(aadmEstablishState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + aadmEstablishState.setTaskSelectionLogic(new AxTaskSelectionLogic(aadmEstablishState.getKey(), + TASK_SELECTION_LOGIC, "MVEL", logicReader)); aadmEstablishState.setDefaultTask(aadmEstablishTask.getKey()); aadmEstablishState.getTaskReferences().put(aadmEstablishTask.getKey(), - new AxStateTaskReference(aadmEstablishState.getKey(), aadmEstablishTask.getKey(), - AxStateTaskOutputType.DIRECT, aadmEst2Dec.getKey())); + new AxStateTaskReference(aadmEstablishState.getKey(), aadmEstablishTask.getKey(), + AxStateTaskOutputType.DIRECT, aadmEst2Dec.getKey())); - final AxState aadmMatchState = new AxState(new AxReferenceKey(aadmPolicy.getKey(), "Match")); + final AxState aadmMatchState = new AxState(new AxReferenceKey(aadmPolicy.getKey(), MATCH)); aadmMatchState.setTrigger(aadmEvent.getKey()); - final AxStateOutput aadmMat2Est = - new AxStateOutput(aadmMatchState.getKey(), aadmEstablishState.getKey(), aadmEvent.getKey()); + final AxStateOutput aadmMat2Est = new AxStateOutput(aadmMatchState.getKey(), aadmEstablishState.getKey(), + aadmEvent.getKey()); aadmMatchState.getStateOutputs().put(aadmMat2Est.getKey().getLocalName(), aadmMat2Est); aadmMatchState.setTaskSelectionLogic( - new AxTaskSelectionLogic(aadmMatchState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + new AxTaskSelectionLogic(aadmMatchState.getKey(), TASK_SELECTION_LOGIC, "MVEL", logicReader)); aadmMatchState.setDefaultTask(aadmMatchTask.getKey()); aadmMatchState.getTaskReferences().put(aadmMatchTask.getKey(), new AxStateTaskReference(aadmMatchState.getKey(), - aadmMatchTask.getKey(), AxStateTaskOutputType.DIRECT, aadmMat2Est.getKey())); + aadmMatchTask.getKey(), AxStateTaskOutputType.DIRECT, aadmMat2Est.getKey())); aadmPolicy.setFirstState(aadmMatchState.getKey().getLocalName()); aadmPolicy.getStateMap().put(aadmMatchState.getKey().getLocalName(), aadmMatchState); @@ -535,47 +573,48 @@ public class AadmDomainModelFactory { aadmPolicy.getStateMap().put(aadmDecideState.getKey().getLocalName(), aadmDecideState); aadmPolicy.getStateMap().put(aadmActState.getKey().getLocalName(), aadmActState); - final AxPolicy vMmePolicy = new AxPolicy(new AxArtifactKey("VMMEPolicy", "0.0.1")); + final AxPolicy vMmePolicy = new AxPolicy(new AxArtifactKey("VMMEPolicy", DEFAULT_VERSION)); vMmePolicy.setTemplate("MEDA"); final AxState vMmeActState = new AxState(new AxReferenceKey(vMmePolicy.getKey(), "Act")); vMmeActState.setTrigger(vMmeEvent.getKey()); - final AxStateOutput vMmeAct2Out = - new AxStateOutput(vMmeActState.getKey(), AxReferenceKey.getNullKey(), vMmeEvent.getKey()); + final AxStateOutput vMmeAct2Out = new AxStateOutput(vMmeActState.getKey(), AxReferenceKey.getNullKey(), + vMmeEvent.getKey()); vMmeActState.getStateOutputs().put(vMmeAct2Out.getKey().getLocalName(), vMmeAct2Out); vMmeActState.setDefaultTask(vMmeActTask.getKey()); vMmeActState.getTaskReferences().put(vMmeActTask.getKey(), new AxStateTaskReference(vMmeActState.getKey(), - vMmeActTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeAct2Out.getKey())); + vMmeActTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeAct2Out.getKey())); vMmeActState.getTaskReferences().put(vMmeNoActTask.getKey(), new AxStateTaskReference(vMmeActState.getKey(), - vMmeNoActTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeAct2Out.getKey())); + vMmeNoActTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeAct2Out.getKey())); - final AxState vMmeDecideState = new AxState(new AxReferenceKey(vMmePolicy.getKey(), "Decide")); + final AxState vMmeDecideState = new AxState(new AxReferenceKey(vMmePolicy.getKey(), DECIDE)); vMmeDecideState.setTrigger(vMmeEvent.getKey()); - final AxStateOutput vMmeDec2Act = - new AxStateOutput(vMmeDecideState.getKey(), vMmeActState.getKey(), vMmeEvent.getKey()); + final AxStateOutput vMmeDec2Act = new AxStateOutput(vMmeDecideState.getKey(), vMmeActState.getKey(), + vMmeEvent.getKey()); vMmeDecideState.getStateOutputs().put(vMmeDec2Act.getKey().getLocalName(), vMmeDec2Act); vMmeDecideState.setDefaultTask(vMmeDecideTask.getKey()); - vMmeDecideState.getTaskReferences().put(vMmeDecideTask.getKey(), new AxStateTaskReference( - vMmeDecideState.getKey(), vMmeDecideTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeDec2Act.getKey())); + vMmeDecideState.getTaskReferences().put(vMmeDecideTask.getKey(), + new AxStateTaskReference(vMmeDecideState.getKey(), vMmeDecideTask.getKey(), + AxStateTaskOutputType.DIRECT, vMmeDec2Act.getKey())); - final AxState vMmeEstablishState = new AxState(new AxReferenceKey(vMmePolicy.getKey(), "Establish")); + final AxState vMmeEstablishState = new AxState(new AxReferenceKey(vMmePolicy.getKey(), ESTABLISH)); vMmeEstablishState.setTrigger(vMmeEvent.getKey()); - final AxStateOutput vMmeEst2Dec = - new AxStateOutput(vMmeEstablishState.getKey(), vMmeDecideState.getKey(), vMmeEvent.getKey()); + final AxStateOutput vMmeEst2Dec = new AxStateOutput(vMmeEstablishState.getKey(), vMmeDecideState.getKey(), + vMmeEvent.getKey()); vMmeEstablishState.getStateOutputs().put(vMmeEst2Dec.getKey().getLocalName(), vMmeEst2Dec); vMmeEstablishState.setDefaultTask(vMmeEstablishTask.getKey()); vMmeEstablishState.getTaskReferences().put(vMmeEstablishTask.getKey(), - new AxStateTaskReference(vMmeEstablishState.getKey(), vMmeEstablishTask.getKey(), - AxStateTaskOutputType.DIRECT, vMmeEst2Dec.getKey())); + new AxStateTaskReference(vMmeEstablishState.getKey(), vMmeEstablishTask.getKey(), + AxStateTaskOutputType.DIRECT, vMmeEst2Dec.getKey())); - final AxState vMmeMatchState = new AxState(new AxReferenceKey(vMmePolicy.getKey(), "Match")); + final AxState vMmeMatchState = new AxState(new AxReferenceKey(vMmePolicy.getKey(), MATCH)); vMmeMatchState.setTrigger(vMmeEvent.getKey()); - final AxStateOutput vMmeMat2Est = - new AxStateOutput(vMmeMatchState.getKey(), vMmeEstablishState.getKey(), vMmeEvent.getKey()); + final AxStateOutput vMmeMat2Est = new AxStateOutput(vMmeMatchState.getKey(), vMmeEstablishState.getKey(), + vMmeEvent.getKey()); vMmeMatchState.getStateOutputs().put(vMmeMat2Est.getKey().getLocalName(), vMmeMat2Est); vMmeMatchState.setDefaultTask(vMmeMatchTask.getKey()); vMmeMatchState.getTaskReferences().put(vMmeMatchTask.getKey(), new AxStateTaskReference(vMmeMatchState.getKey(), - vMmeMatchTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeMat2Est.getKey())); + vMmeMatchTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeMat2Est.getKey())); vMmePolicy.setFirstState(vMmeMatchState.getKey().getLocalName()); vMmePolicy.getStateMap().put(vMmeMatchState.getKey().getLocalName(), vMmeMatchState); @@ -583,45 +622,46 @@ public class AadmDomainModelFactory { vMmePolicy.getStateMap().put(vMmeDecideState.getKey().getLocalName(), vMmeDecideState); vMmePolicy.getStateMap().put(vMmeActState.getKey().getLocalName(), vMmeActState); - final AxPolicy sapcPolicy = new AxPolicy(new AxArtifactKey("SAPCPolicy", "0.0.1")); + final AxPolicy sapcPolicy = new AxPolicy(new AxArtifactKey("SAPCPolicy", DEFAULT_VERSION)); sapcPolicy.setTemplate("MEDA"); final AxState sapcActState = new AxState(new AxReferenceKey(sapcPolicy.getKey(), "Act")); sapcActState.setTrigger(sapcEvent.getKey()); final AxStateOutput sapcAct2Out = new AxStateOutput(sapcActState.getKey(), AxReferenceKey.getNullKey(), - sapcBlacklistSubscriberEvent.getKey()); + sapcBlacklistSubscriberEvent.getKey()); sapcActState.getStateOutputs().put(sapcAct2Out.getKey().getLocalName(), sapcAct2Out); sapcActState.setDefaultTask(sapcActTask.getKey()); sapcActState.getTaskReferences().put(sapcActTask.getKey(), new AxStateTaskReference(sapcActState.getKey(), - sapcActTask.getKey(), AxStateTaskOutputType.DIRECT, sapcAct2Out.getKey())); + sapcActTask.getKey(), AxStateTaskOutputType.DIRECT, sapcAct2Out.getKey())); - final AxState sapcDecideState = new AxState(new AxReferenceKey(sapcPolicy.getKey(), "Decide")); + final AxState sapcDecideState = new AxState(new AxReferenceKey(sapcPolicy.getKey(), DECIDE)); sapcDecideState.setTrigger(sapcEvent.getKey()); - final AxStateOutput sapcDec2Act = - new AxStateOutput(sapcDecideState.getKey(), sapcActState.getKey(), sapcEvent.getKey()); + final AxStateOutput sapcDec2Act = new AxStateOutput(sapcDecideState.getKey(), sapcActState.getKey(), + sapcEvent.getKey()); sapcDecideState.getStateOutputs().put(sapcDec2Act.getKey().getLocalName(), sapcDec2Act); sapcDecideState.setDefaultTask(sapcDecideTask.getKey()); - sapcDecideState.getTaskReferences().put(sapcDecideTask.getKey(), new AxStateTaskReference( - sapcDecideState.getKey(), sapcDecideTask.getKey(), AxStateTaskOutputType.DIRECT, sapcDec2Act.getKey())); + sapcDecideState.getTaskReferences().put(sapcDecideTask.getKey(), + new AxStateTaskReference(sapcDecideState.getKey(), sapcDecideTask.getKey(), + AxStateTaskOutputType.DIRECT, sapcDec2Act.getKey())); - final AxState sapcEstablishState = new AxState(new AxReferenceKey(sapcPolicy.getKey(), "Establish")); + final AxState sapcEstablishState = new AxState(new AxReferenceKey(sapcPolicy.getKey(), ESTABLISH)); sapcEstablishState.setTrigger(sapcEvent.getKey()); - final AxStateOutput sapcEst2Dec = - new AxStateOutput(sapcEstablishState.getKey(), sapcDecideState.getKey(), sapcEvent.getKey()); + final AxStateOutput sapcEst2Dec = new AxStateOutput(sapcEstablishState.getKey(), sapcDecideState.getKey(), + sapcEvent.getKey()); sapcEstablishState.getStateOutputs().put(sapcEst2Dec.getKey().getLocalName(), sapcEst2Dec); sapcEstablishState.setDefaultTask(sapcEstablishTask.getKey()); sapcEstablishState.getTaskReferences().put(sapcEstablishTask.getKey(), - new AxStateTaskReference(sapcEstablishState.getKey(), sapcEstablishTask.getKey(), - AxStateTaskOutputType.DIRECT, sapcEst2Dec.getKey())); + new AxStateTaskReference(sapcEstablishState.getKey(), sapcEstablishTask.getKey(), + AxStateTaskOutputType.DIRECT, sapcEst2Dec.getKey())); - final AxState sapcMatchState = new AxState(new AxReferenceKey(sapcPolicy.getKey(), "Match")); + final AxState sapcMatchState = new AxState(new AxReferenceKey(sapcPolicy.getKey(), MATCH)); sapcMatchState.setTrigger(aadmXStreamActEvent.getKey()); - final AxStateOutput sapcMat2Est = - new AxStateOutput(sapcMatchState.getKey(), sapcEstablishState.getKey(), sapcEvent.getKey()); + final AxStateOutput sapcMat2Est = new AxStateOutput(sapcMatchState.getKey(), sapcEstablishState.getKey(), + sapcEvent.getKey()); sapcMatchState.getStateOutputs().put(sapcMat2Est.getKey().getLocalName(), sapcMat2Est); sapcMatchState.setDefaultTask(sapcMatchTask.getKey()); sapcMatchState.getTaskReferences().put(sapcMatchTask.getKey(), new AxStateTaskReference(sapcMatchState.getKey(), - sapcMatchTask.getKey(), AxStateTaskOutputType.DIRECT, sapcMat2Est.getKey())); + sapcMatchTask.getKey(), AxStateTaskOutputType.DIRECT, sapcMat2Est.getKey())); sapcPolicy.setFirstState(sapcMatchState.getKey().getLocalName()); sapcPolicy.getStateMap().put(sapcMatchState.getKey().getLocalName(), sapcMatchState); @@ -629,48 +669,48 @@ public class AadmDomainModelFactory { sapcPolicy.getStateMap().put(sapcDecideState.getKey().getLocalName(), sapcDecideState); sapcPolicy.getStateMap().put(sapcActState.getKey().getLocalName(), sapcActState); - final AxPolicy periodicPolicy = new AxPolicy(new AxArtifactKey("PeriodicPolicy", "0.0.1")); + final AxPolicy periodicPolicy = new AxPolicy(new AxArtifactKey("PeriodicPolicy", DEFAULT_VERSION)); periodicPolicy.setTemplate("MEDA"); final AxState periodicActState = new AxState(new AxReferenceKey(periodicPolicy.getKey(), "Act")); periodicActState.setTrigger(periodicEvent.getKey()); final AxStateOutput perAct2Out = new AxStateOutput(periodicActState.getKey(), AxReferenceKey.getNullKey(), - sapcBlacklistSubscriberEvent.getKey()); + sapcBlacklistSubscriberEvent.getKey()); periodicActState.getStateOutputs().put(perAct2Out.getKey().getLocalName(), perAct2Out); periodicActState.setDefaultTask(periodicActTask.getKey()); periodicActState.getTaskReferences().put(periodicActTask.getKey(), - new AxStateTaskReference(periodicActState.getKey(), periodicActTask.getKey(), - AxStateTaskOutputType.DIRECT, perAct2Out.getKey())); + new AxStateTaskReference(periodicActState.getKey(), periodicActTask.getKey(), + AxStateTaskOutputType.DIRECT, perAct2Out.getKey())); - final AxState periodicDecideState = new AxState(new AxReferenceKey(periodicPolicy.getKey(), "Decide")); + final AxState periodicDecideState = new AxState(new AxReferenceKey(periodicPolicy.getKey(), DECIDE)); periodicDecideState.setTrigger(periodicEvent.getKey()); - final AxStateOutput perDec2Act = - new AxStateOutput(periodicDecideState.getKey(), periodicActState.getKey(), periodicEvent.getKey()); + final AxStateOutput perDec2Act = new AxStateOutput(periodicDecideState.getKey(), periodicActState.getKey(), + periodicEvent.getKey()); periodicDecideState.getStateOutputs().put(perDec2Act.getKey().getLocalName(), perDec2Act); periodicDecideState.setDefaultTask(periodicDecideTask.getKey()); periodicDecideState.getTaskReferences().put(periodicDecideTask.getKey(), - new AxStateTaskReference(periodicDecideState.getKey(), periodicDecideTask.getKey(), - AxStateTaskOutputType.DIRECT, perDec2Act.getKey())); + new AxStateTaskReference(periodicDecideState.getKey(), periodicDecideTask.getKey(), + AxStateTaskOutputType.DIRECT, perDec2Act.getKey())); - final AxState periodicEstablishState = new AxState(new AxReferenceKey(periodicPolicy.getKey(), "Establish")); + final AxState periodicEstablishState = new AxState(new AxReferenceKey(periodicPolicy.getKey(), ESTABLISH)); periodicEstablishState.setTrigger(periodicEvent.getKey()); final AxStateOutput perEst2Dec = new AxStateOutput(periodicEstablishState.getKey(), - periodicDecideState.getKey(), periodicEvent.getKey()); + periodicDecideState.getKey(), periodicEvent.getKey()); periodicEstablishState.getStateOutputs().put(perEst2Dec.getKey().getLocalName(), perEst2Dec); periodicEstablishState.setDefaultTask(periodicEstablishTask.getKey()); periodicEstablishState.getTaskReferences().put(periodicEstablishTask.getKey(), - new AxStateTaskReference(periodicEstablishState.getKey(), periodicEstablishTask.getKey(), - AxStateTaskOutputType.DIRECT, perEst2Dec.getKey())); + new AxStateTaskReference(periodicEstablishState.getKey(), periodicEstablishTask.getKey(), + AxStateTaskOutputType.DIRECT, perEst2Dec.getKey())); - final AxState periodicMatchState = new AxState(new AxReferenceKey(periodicPolicy.getKey(), "Match")); + final AxState periodicMatchState = new AxState(new AxReferenceKey(periodicPolicy.getKey(), MATCH)); periodicMatchState.setTrigger(periodicEvent.getKey()); - final AxStateOutput perMat2Est = - new AxStateOutput(periodicMatchState.getKey(), periodicEstablishState.getKey(), periodicEvent.getKey()); + final AxStateOutput perMat2Est = new AxStateOutput(periodicMatchState.getKey(), periodicEstablishState.getKey(), + periodicEvent.getKey()); periodicMatchState.getStateOutputs().put(perMat2Est.getKey().getLocalName(), perMat2Est); periodicMatchState.setDefaultTask(periodicMatchTask.getKey()); periodicMatchState.getTaskReferences().put(periodicMatchTask.getKey(), - new AxStateTaskReference(periodicMatchState.getKey(), periodicMatchTask.getKey(), - AxStateTaskOutputType.DIRECT, perMat2Est.getKey())); + new AxStateTaskReference(periodicMatchState.getKey(), periodicMatchTask.getKey(), + AxStateTaskOutputType.DIRECT, perMat2Est.getKey())); periodicPolicy.setFirstState(periodicMatchState.getKey().getLocalName()); periodicPolicy.getStateMap().put(periodicMatchState.getKey().getLocalName(), periodicMatchState); @@ -678,14 +718,15 @@ public class AadmDomainModelFactory { periodicPolicy.getStateMap().put(periodicDecideState.getKey().getLocalName(), periodicDecideState); periodicPolicy.getStateMap().put(periodicActState.getKey().getLocalName(), periodicActState); - final AxPolicies aadmPolicies = new AxPolicies(new AxArtifactKey("AADMPolicies", "0.0.1")); + final AxPolicies aadmPolicies = new AxPolicies(new AxArtifactKey("AADMPolicies", DEFAULT_VERSION)); aadmPolicies.getPolicyMap().put(aadmPolicy.getKey(), aadmPolicy); aadmPolicies.getPolicyMap().put(vMmePolicy.getKey(), vMmePolicy); aadmPolicies.getPolicyMap().put(sapcPolicy.getKey(), sapcPolicy); aadmPolicies.getPolicyMap().put(periodicPolicy.getKey(), periodicPolicy); - final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("AADMKeyInformation", "0.0.1")); - final AxPolicyModel aadmPolicyModel = new AxPolicyModel(new AxArtifactKey("AADMPolicyModel", "0.0.1")); + final AxKeyInformation keyInformation = new AxKeyInformation( + new AxArtifactKey("AADMKeyInformation", DEFAULT_VERSION)); + final AxPolicyModel aadmPolicyModel = new AxPolicyModel(new AxArtifactKey("AADMPolicyModel", DEFAULT_VERSION)); aadmPolicyModel.setPolicies(aadmPolicies); aadmPolicyModel.setEvents(aadmEvents); aadmPolicyModel.setTasks(aadmTasks); diff --git a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelSaver.java b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelSaver.java index 5a3afd901..60eee455c 100644 --- a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelSaver.java +++ b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelSaver.java @@ -23,6 +23,8 @@ package org.onap.policy.apex.examples.aadm.model; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.onap.policy.apex.model.basicmodel.handling.ApexModelSaver; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; /** * This class saves sample domain models to disk in XML and JSON format. @@ -30,6 +32,9 @@ import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; * @author Liam Fallon (liam.fallon@ericsson.com) */ public final class AadmDomainModelSaver { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(AadmDomainModelSaver.class); + /** * Private default constructor to prevent subclassing. */ @@ -43,7 +48,7 @@ public final class AadmDomainModelSaver { */ public static void main(final String[] args) throws ApexException { if (args.length != 1) { - System.err.println("usage: " + AadmDomainModelSaver.class.getCanonicalName() + " modelDirectory"); + LOGGER.error("usage: " + AadmDomainModelSaver.class.getCanonicalName() + " modelDirectory"); return; } diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTaskTaskLogic.mvel new file mode 100644 index 000000000..225a0da4d --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTaskTaskLogic.mvel @@ -0,0 +1,80 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; + +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +outFields["ACTTASK"] = "act"; +outFields["TRIGGER_SPEC"] = "XSTREAM_AADM_ACT_EVENT"; +outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; +outFields["PROBE_ON"] = true; +outFields["TCP_ON"] = false; +outFields["IMSI"] = inFields["IMSI"]; + +if (inFields["IMSI_IP"] != null) { + outFields["IMSI_IP"] = inFields["IMSI_IP"]; +} +else{ + outFields["IMSI_IP"] = inFields["UE_IP_ADDRESS"]; +} + +if (inFields["NW_IP"] != null) { + outFields["NW_IP"] = inFields["NW_IP"]; +} +else{ + outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; +} + +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); +logger.debug(imsiStatus); + +ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); +eNodeBStatus.setBeingProbed(false); + +leaveProbingOn = false; +for (ENodeBStatus enbStatus : getContextAlbum("ENodeBStatusAlbum").values) { + if (enbStatus.getBeingProbed()) { + leaveProbingOn = true; + } +} + +if (!leaveProbingOn) { + outFields["PROBE_ON"] = false; + outFields["TCP_ON"] = false; +} + +eNodeBStatus.decrementDosCount(); +logger.debug(eNodeBStatus.getENodeB() + ": dosCount is " + eNodeBStatus.getDosCount()); + +imsiStatus.setAnomalous(false); + +logger.debug("imsi: " + imsiStatus.getImsi() + " anamalous " + imsiStatus.getAnomalous()); + +getContextAlbum("IMSIStatusAlbum") .put(imsiStatus.getImsi(), imsiStatus); +getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); + +outFields["THRESHOLD"] = 0; +outFields["PROFILE"] = ""; +outFields["VERSION"] = "0.0.1"; +outFields["BLACKLIST_ON"] = false; + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTask_TaskLogic.mvel deleted file mode 100644 index 225a0da4d..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSProvenActTask_TaskLogic.mvel +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; -import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; - -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -outFields["ACTTASK"] = "act"; -outFields["TRIGGER_SPEC"] = "XSTREAM_AADM_ACT_EVENT"; -outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; -outFields["PROBE_ON"] = true; -outFields["TCP_ON"] = false; -outFields["IMSI"] = inFields["IMSI"]; - -if (inFields["IMSI_IP"] != null) { - outFields["IMSI_IP"] = inFields["IMSI_IP"]; -} -else{ - outFields["IMSI_IP"] = inFields["UE_IP_ADDRESS"]; -} - -if (inFields["NW_IP"] != null) { - outFields["NW_IP"] = inFields["NW_IP"]; -} -else{ - outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; -} - -ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); -logger.debug(imsiStatus); - -ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); -eNodeBStatus.setBeingProbed(false); - -leaveProbingOn = false; -for (ENodeBStatus enbStatus : getContextAlbum("ENodeBStatusAlbum").values) { - if (enbStatus.getBeingProbed()) { - leaveProbingOn = true; - } -} - -if (!leaveProbingOn) { - outFields["PROBE_ON"] = false; - outFields["TCP_ON"] = false; -} - -eNodeBStatus.decrementDosCount(); -logger.debug(eNodeBStatus.getENodeB() + ": dosCount is " + eNodeBStatus.getDosCount()); - -imsiStatus.setAnomalous(false); - -logger.debug("imsi: " + imsiStatus.getImsi() + " anamalous " + imsiStatus.getAnomalous()); - -getContextAlbum("IMSIStatusAlbum") .put(imsiStatus.getImsi(), imsiStatus); -getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); - -outFields["THRESHOLD"] = 0; -outFields["PROFILE"] = ""; -outFields["VERSION"] = "0.0.1"; -outFields["BLACKLIST_ON"] = false; - -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTaskTaskLogic.mvel new file mode 100644 index 000000000..63ac8d0ba --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTaskTaskLogic.mvel @@ -0,0 +1,106 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; + +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +outFields["ACTTASK"] = "probe"; +outFields["TRIGGER_SPEC"] = "XSTREAM_AADM_ACT_EVENT"; +outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; +outFields["IMSI"] = inFields["IMSI"]; + +if (inFields["IMSI_IP"] != null) { + outFields["IMSI_IP"] = inFields["IMSI_IP"]; +} +else { + outFields["IMSI_IP"] = inFields["UE_IP_ADDRESS"]; +} + +if (inFields["NW_IP"] != null) { + outFields["NW_IP"] = inFields["NW_IP"]; +} +else { + outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; +} + +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); +logger.debug(imsiStatus); + +ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); +logger.debug(eNodeBStatus); + +if (imsiStatus.getENodeBId() != null && !imsiStatus.getENodeBId().equals(inFields["ENODEB_ID"]) || inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] == null) { + // if user moved enodeB remove him from previous one + if (imsiStatus.getENodeBId() != null) { + eNodeBStatus.decrementDosCount(); + } + + // if user became non anomalous return action + if (inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] == null) { + imsiStatus.setAnomalous(false); + outFields["ACTTASK"] = "remove_from_probe"; + + for (ENodeBStatus enbStatus : getContextAlbum("ENodeBStatusAlbum").values) { + if (enbStatus.getBeingProbed()) { + outFields["PROBE_ON"] = true; + outFields["TCP_ON"] = true; + return true; + } + } + + outFields["PROBE_ON"] = false; + outFields["TCP_ON"] = false; + + getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getIMSI(), imsiStatus); + getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); + + return true; + } +} + +imsiStatus.setAnomalous(true); +imsiStatus.setAnomolousTime(System.currentTimeMillis()); +imsiStatus.setENodeBId(inFields["ENODEB_ID"]); +getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); +logger.debug(imsiStatus.getENodeBId() + ": enodeb added to imsi ip added " + outFields["IMSI_IP"]); + +ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); +if (eNodeBStatus == null) { + eNodeBStatus = new ENodeBStatus(imsiStatus.getENodeBId()); + getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); + logger.debug("new eNodeB added " + getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId())); +} + +eNodeBStatus.incrementDosCount(); +getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); +logger.debug(eNodeBStatus.getENodeB() + ": dosCount incremented to " + eNodeBStatus.getDosCount()); + +outFields["PROBE_ON"] = true; +outFields["TCP_ON"] = true; +outFields["THRESHOLD"] = 0; +outFields["PROFILE"] = ""; +outFields["VERSION"] = "0.0.1"; +outFields["BLACKLIST_ON"] = false; + +logger.debug("out here5"); + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTask_TaskLogic.mvel deleted file mode 100644 index 63ac8d0ba..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMDoSSuggestionActTask_TaskLogic.mvel +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; -import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; - -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -outFields["ACTTASK"] = "probe"; -outFields["TRIGGER_SPEC"] = "XSTREAM_AADM_ACT_EVENT"; -outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; -outFields["IMSI"] = inFields["IMSI"]; - -if (inFields["IMSI_IP"] != null) { - outFields["IMSI_IP"] = inFields["IMSI_IP"]; -} -else { - outFields["IMSI_IP"] = inFields["UE_IP_ADDRESS"]; -} - -if (inFields["NW_IP"] != null) { - outFields["NW_IP"] = inFields["NW_IP"]; -} -else { - outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; -} - -ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); -logger.debug(imsiStatus); - -ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); -logger.debug(eNodeBStatus); - -if (imsiStatus.getENodeBId() != null && !imsiStatus.getENodeBId().equals(inFields["ENODEB_ID"]) || inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] == null) { - // if user moved enodeB remove him from previous one - if (imsiStatus.getENodeBId() != null) { - eNodeBStatus.decrementDosCount(); - } - - // if user became non anomalous return action - if (inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] == null) { - imsiStatus.setAnomalous(false); - outFields["ACTTASK"] = "remove_from_probe"; - - for (ENodeBStatus enbStatus : getContextAlbum("ENodeBStatusAlbum").values) { - if (enbStatus.getBeingProbed()) { - outFields["PROBE_ON"] = true; - outFields["TCP_ON"] = true; - return true; - } - } - - outFields["PROBE_ON"] = false; - outFields["TCP_ON"] = false; - - getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getIMSI(), imsiStatus); - getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); - - return true; - } -} - -imsiStatus.setAnomalous(true); -imsiStatus.setAnomolousTime(System.currentTimeMillis()); -imsiStatus.setENodeBId(inFields["ENODEB_ID"]); -getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); -logger.debug(imsiStatus.getENodeBId() + ": enodeb added to imsi ip added " + outFields["IMSI_IP"]); - -ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); -if (eNodeBStatus == null) { - eNodeBStatus = new ENodeBStatus(imsiStatus.getENodeBId()); - getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); - logger.debug("new eNodeB added " + getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId())); -} - -eNodeBStatus.incrementDosCount(); -getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); -logger.debug(eNodeBStatus.getENodeB() + ": dosCount incremented to " + eNodeBStatus.getDosCount()); - -outFields["PROBE_ON"] = true; -outFields["TCP_ON"] = true; -outFields["THRESHOLD"] = 0; -outFields["PROFILE"] = ""; -outFields["VERSION"] = "0.0.1"; -outFields["BLACKLIST_ON"] = false; - -logger.debug("out here5"); - -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTaskTaskLogic.mvel new file mode 100644 index 000000000..24ad9bb0a --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTaskTaskLogic.mvel @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; +import org.onap.policy.apex.examples.aadm.concepts.IpAddressStatus; +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; + +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +ipAddress = inFields["UE_IP_ADDRESS"]; +if (ipAddress == null ) { + ipAddress = inFields["IMSI_IP"]; + + if (ipAddress == null ) { + logger.debug("Incoming event must specify parameter UE_IP_ADDRESS or parameter IMSI_IP"); + return false; + } +} + +imsi = inFields["IMSI"]; +if (imsi == null ) { + logger.debug("Incoming event must specify parameter IMSI"); + return false; +} + +eNodeBID = inFields["ENODEB_ID"]; +if (eNodeBID == null ) { + logger.debug("Incoming event must specify parameter ENODEB_ID"); + return false; +} + +IpAddressStatus ipAddressStatus = getContextAlbum("IPAddressStatusAlbum").get(ipAddress); +if (ipAddressStatus == null) { + ipAddressStatus = new IpAddressStatus(ipAddress); + ipAddressStatus.setImsi(imsi); + getContextAlbum("IPAddressStatusAlbum").put(ipAddressStatus.getIpAddress(), ipAddressStatus); + logger.debug("added new IP address " + getContextAlbum("IPAddressStatusAlbum").get(ipAddress)); +} +else { + logger.debug("found IP address " + ipAddressStatus); +} + +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)imsi); +if (imsiStatus == null) { + imsiStatus = new ImsiStatus(imsi); + imsiStatus.setENodeBId(eNodeBID); + getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); + logger.debug("added new IMSI " + imsi + " to IMSI status map") +} + +ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get((String)eNodeBID); +if (eNodeBStatus == null) { + eNodeBStatus = new ENodeBStatus(eNodeBID); + getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); + logger.debug("added new ENodeB " + eNodeBID + " to ENodeB status map") +} + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTask_TaskLogic.mvel deleted file mode 100644 index 24ad9bb0a..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMMatchTask_TaskLogic.mvel +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; -import org.onap.policy.apex.examples.aadm.concepts.IpAddressStatus; -import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; - -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -ipAddress = inFields["UE_IP_ADDRESS"]; -if (ipAddress == null ) { - ipAddress = inFields["IMSI_IP"]; - - if (ipAddress == null ) { - logger.debug("Incoming event must specify parameter UE_IP_ADDRESS or parameter IMSI_IP"); - return false; - } -} - -imsi = inFields["IMSI"]; -if (imsi == null ) { - logger.debug("Incoming event must specify parameter IMSI"); - return false; -} - -eNodeBID = inFields["ENODEB_ID"]; -if (eNodeBID == null ) { - logger.debug("Incoming event must specify parameter ENODEB_ID"); - return false; -} - -IpAddressStatus ipAddressStatus = getContextAlbum("IPAddressStatusAlbum").get(ipAddress); -if (ipAddressStatus == null) { - ipAddressStatus = new IpAddressStatus(ipAddress); - ipAddressStatus.setImsi(imsi); - getContextAlbum("IPAddressStatusAlbum").put(ipAddressStatus.getIpAddress(), ipAddressStatus); - logger.debug("added new IP address " + getContextAlbum("IPAddressStatusAlbum").get(ipAddress)); -} -else { - logger.debug("found IP address " + ipAddressStatus); -} - -ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)imsi); -if (imsiStatus == null) { - imsiStatus = new ImsiStatus(imsi); - imsiStatus.setENodeBId(eNodeBID); - getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); - logger.debug("added new IMSI " + imsi + " to IMSI status map") -} - -ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get((String)eNodeBID); -if (eNodeBStatus == null) { - eNodeBStatus = new ENodeBStatus(eNodeBID); - getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); - logger.debug("added new ENodeB " + eNodeBID + " to ENodeB status map") -} - -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTaskTaskLogic.mvel new file mode 100644 index 000000000..7107b940b --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTaskTaskLogic.mvel @@ -0,0 +1,55 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); + +outFields["ACTTASK"] = "no"; +outFields["TRIGGER_SPEC"] = "XSTREAM_AADM_ACT_EVENT"; +outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; + +if (inFields["PROBE_ON"] != null) { + outFields["PROBE_ON"] = inFields["PROBE_ON"]; +} +else{ + outFields["PROBE_ON"] = false; +} + +if (inFields["TCP_ON"] != null) { + outFields["TCP_ON"] = inFields["TCP_ON"]; +} +else { + outFields["TCP_ON"] = false; +} + +outFields["IMSI"] = inFields["IMSI"]; +if (inFields["IMSI_IP"] != null) { + outFields["IMSI_IP"] = inFields["IMSI_IP"]; +} +else { + outFields["IMSI_IP"] = inFields["UE_IP_ADDRESS"]; +} + +if (inFields["NW_IP"] != null) { + outFields["NW_IP"] = inFields["NW_IP"]; +} +else{ + outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; +} + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTask_TaskLogic.mvel deleted file mode 100644 index 7107b940b..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMNoActTask_TaskLogic.mvel +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); - -outFields["ACTTASK"] = "no"; -outFields["TRIGGER_SPEC"] = "XSTREAM_AADM_ACT_EVENT"; -outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; - -if (inFields["PROBE_ON"] != null) { - outFields["PROBE_ON"] = inFields["PROBE_ON"]; -} -else{ - outFields["PROBE_ON"] = false; -} - -if (inFields["TCP_ON"] != null) { - outFields["TCP_ON"] = inFields["TCP_ON"]; -} -else { - outFields["TCP_ON"] = false; -} - -outFields["IMSI"] = inFields["IMSI"]; -if (inFields["IMSI_IP"] != null) { - outFields["IMSI_IP"] = inFields["IMSI_IP"]; -} -else { - outFields["IMSI_IP"] = inFields["UE_IP_ADDRESS"]; -} - -if (inFields["NW_IP"] != null) { - outFields["NW_IP"] = inFields["NW_IP"]; -} -else{ - outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; -} - -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicyActTaskSelectionLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicyActTaskSelectionLogic.mvel new file mode 100644 index 000000000..9c71db50a --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicyActTaskSelectionLogic.mvel @@ -0,0 +1,67 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; +import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; + +logger.debug(subject.id + ":" + subject.stateName + " execution logic"); +logger.debug(inFields); + +logger.debug("inFields[SERVICE_REQUEST_COUNT]=" + inFields["SERVICE_REQUEST_COUNT"]); + +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); + +if (imsiStatus.getBlockingCount() > 1) { + subject.getTaskKey("AADMNoActTask").copyTo(selectedTask); + logger.debug("user blacklisted permanently"); + return false; +} + +logger.debug("imsi: " + imsiStatus.getImsi() + " anamalous " + imsiStatus.getAnomalous()); + +// check if this is second iteration +if (inFields["TCP_UE_SIDE_AVG_THROUGHPUT"] != null && inFields["TCP_UE_SIDE_AVG_THROUGHPUT"] > 100 && imsiStatus.getAnomalous()) { + subject.getTaskKey("AADMDoSProvenActTask").copyTo(selectedTask); + logger.debug("inside TCP_UE_SIDE_AVG_THROUGHPUT"); + return true; +} + +// Get the status of the ENodeB +ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get((String)inFields["ENODEB_ID"]); + +// check if this is first iteration and DoS +if (inFields["SERVICE_REQUEST_COUNT"] != null && + inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] != null && + inFields["SERVICE_REQUEST_COUNT"] > inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] && + eNodeBStatus != null && eNodeBStatus.getDosCount() > 100 && + inFields["NUM_SUBSCRIBERS"] != null && inFields["NUM_SUBSCRIBERS"] > 100) { + logger.debug("inside NUM_SUBSCRIBERS"); + subject.getTaskKey("AADMDoSProvenActTask").copyTo(selectedTask); + return true; +} + +// check if this is first iteration and request probe +if (inFields["UE_IP_ADDRESS"] != null) { + logger.debug("inside UE_IP_ADDRESS"); + subject.getTaskKey("AADMDoSSuggestionActTask").copyTo(selectedTask); + return true; +} + +subject.defaultTaskKey.copyTo(selectedTask); +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicy_Act_TaskSelectionLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicy_Act_TaskSelectionLogic.mvel deleted file mode 100644 index 9c71db50a..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/AADMPolicy_Act_TaskSelectionLogic.mvel +++ /dev/null @@ -1,67 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; -import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; - -logger.debug(subject.id + ":" + subject.stateName + " execution logic"); -logger.debug(inFields); - -logger.debug("inFields[SERVICE_REQUEST_COUNT]=" + inFields["SERVICE_REQUEST_COUNT"]); - -ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); - -if (imsiStatus.getBlockingCount() > 1) { - subject.getTaskKey("AADMNoActTask").copyTo(selectedTask); - logger.debug("user blacklisted permanently"); - return false; -} - -logger.debug("imsi: " + imsiStatus.getImsi() + " anamalous " + imsiStatus.getAnomalous()); - -// check if this is second iteration -if (inFields["TCP_UE_SIDE_AVG_THROUGHPUT"] != null && inFields["TCP_UE_SIDE_AVG_THROUGHPUT"] > 100 && imsiStatus.getAnomalous()) { - subject.getTaskKey("AADMDoSProvenActTask").copyTo(selectedTask); - logger.debug("inside TCP_UE_SIDE_AVG_THROUGHPUT"); - return true; -} - -// Get the status of the ENodeB -ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get((String)inFields["ENODEB_ID"]); - -// check if this is first iteration and DoS -if (inFields["SERVICE_REQUEST_COUNT"] != null && - inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] != null && - inFields["SERVICE_REQUEST_COUNT"] > inFields["AVG_SUBSCRIBER_SERVICE_REQUEST"] && - eNodeBStatus != null && eNodeBStatus.getDosCount() > 100 && - inFields["NUM_SUBSCRIBERS"] != null && inFields["NUM_SUBSCRIBERS"] > 100) { - logger.debug("inside NUM_SUBSCRIBERS"); - subject.getTaskKey("AADMDoSProvenActTask").copyTo(selectedTask); - return true; -} - -// check if this is first iteration and request probe -if (inFields["UE_IP_ADDRESS"] != null) { - logger.debug("inside UE_IP_ADDRESS"); - subject.getTaskKey("AADMDoSSuggestionActTask").copyTo(selectedTask); - return true; -} - -subject.defaultTaskKey.copyTo(selectedTask); -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskLogic.mvel new file mode 100644 index 000000000..69146d19c --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskLogic.mvel @@ -0,0 +1,23 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); +logger.debug(outFields); +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskSelectionLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskSelectionLogic.mvel new file mode 100644 index 000000000..20fe626cd --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/DefaultTaskSelectionLogic.mvel @@ -0,0 +1,23 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug(subject.id + ":" + subject.stateName); +subject.defaultTaskKey.copyTo(selectedTask) +logger.debug(subject.id + ":" + subject.stateName) + ", using default task"; +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskLogic.mvel deleted file mode 100644 index 69146d19c..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskLogic.mvel +++ /dev/null @@ -1,23 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); -logger.debug(outFields); -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskSelectionLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskSelectionLogic.mvel deleted file mode 100644 index 20fe626cd..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/Default_TaskSelectionLogic.mvel +++ /dev/null @@ -1,23 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -logger.debug(subject.id + ":" + subject.stateName); -subject.defaultTaskKey.copyTo(selectedTask) -logger.debug(subject.id + ":" + subject.stateName) + ", using default task"; -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTaskTaskLogic.mvel new file mode 100644 index 000000000..6a2c598b0 --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTaskTaskLogic.mvel @@ -0,0 +1,40 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; + +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +for (ImsiStatus imsiStatus : getContextAlbum("IMSIStatusAlbum").values()) { + if ((System.currentTimeMillis() - imsiStatus.getBlacklistedTime()) > 180000) { + imsiStatus.setBlacklistedTime(0); + getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); + } +} + +outFields["IMSI"] = 0; +outFields["PROFILE"] = "ServiceA"; +outFields["BLACKLIST_ON"] = false; +outFields["PROBE_ON"] = false; +outFields["TCP_ON"] = false; +outFields["NW_IP"] = "0.0.0.0"; +outFields["IMSI_IP"] = "0.0.0.0"; + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTask_TaskLogic.mvel deleted file mode 100644 index 6a2c598b0..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/PeriodicActTask_TaskLogic.mvel +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; - -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -for (ImsiStatus imsiStatus : getContextAlbum("IMSIStatusAlbum").values()) { - if ((System.currentTimeMillis() - imsiStatus.getBlacklistedTime()) > 180000) { - imsiStatus.setBlacklistedTime(0); - getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); - } -} - -outFields["IMSI"] = 0; -outFields["PROFILE"] = "ServiceA"; -outFields["BLACKLIST_ON"] = false; -outFields["PROBE_ON"] = false; -outFields["TCP_ON"] = false; -outFields["NW_IP"] = "0.0.0.0"; -outFields["IMSI_IP"] = "0.0.0.0"; - -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTaskTaskLogic.mvel new file mode 100644 index 000000000..b0c6c3158 --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTaskTaskLogic.mvel @@ -0,0 +1,79 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; + +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +if (inFields["IMSI"] == null) { + outFields["IMSI"] = 0; +} +else { + outFields["IMSI"] = inFields["IMSI"]; +} + +if (outFields["IMSI"] == 0 && inFields["IMSI_IP"] != null && inFields["IMSI_IP"].equals("0")) { + // no action arrived + outFields["IMSI"] = 0; + outFields["PROFILE"] = "none"; + outFields["BLACKLIST_ON"] = false; + outFields["PROBE_ON"] = false; + return true; +} + +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); +logger.debug(imsiStatus); + +if (imsiStatus.getBlockingCount() > 1) { + outFields["IMSI"] = 0; + outFields["PROFILE"] = "none"; + outFields["BLACKLIST_ON"] = false; + outFields["PROBE_ON"] = false; + + return true; +} + +if (imsiStatus.getBlockingCount() > 0 && imsiStatus.getBlacklistedTime() != 0) { + outFields["IMSI"] = 0; + outFields["PROFILE"] = "none"; + outFields["BLACKLIST_ON"] = false; + outFields["PROBE_ON"] = false; + + return true; +} + +imsiStatus.incrementBlockingCount(); +imsiStatus.setBlacklistedTime(System.currentTimeMillis()); + +logger.debug("Bocking count for IMSI: " + imsiStatus.getImsi() + " is: " + imsiStatus.getBlockingCount()); +getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); + +outFields["PROFILE"] = "ServiceA"; +outFields["BLACKLIST_ON"] = true; +outFields["PROBE_ON"] = false; + +if (imsiStatus.getBlockingCount() > 1) { + logger.debug("POLICY SAPCPolicy - blacklisting imsi: " + outFields["IMSI"] + " permanently"); +} +else { + logger.debug("POLICY SAPCPolicy - blacklisting imsi: " + outFields["IMSI"] + " temporary for 120000 ms"); +} + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTask_TaskLogic.mvel deleted file mode 100644 index b0c6c3158..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCActTask_TaskLogic.mvel +++ /dev/null @@ -1,79 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; - -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -if (inFields["IMSI"] == null) { - outFields["IMSI"] = 0; -} -else { - outFields["IMSI"] = inFields["IMSI"]; -} - -if (outFields["IMSI"] == 0 && inFields["IMSI_IP"] != null && inFields["IMSI_IP"].equals("0")) { - // no action arrived - outFields["IMSI"] = 0; - outFields["PROFILE"] = "none"; - outFields["BLACKLIST_ON"] = false; - outFields["PROBE_ON"] = false; - return true; -} - -ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); -logger.debug(imsiStatus); - -if (imsiStatus.getBlockingCount() > 1) { - outFields["IMSI"] = 0; - outFields["PROFILE"] = "none"; - outFields["BLACKLIST_ON"] = false; - outFields["PROBE_ON"] = false; - - return true; -} - -if (imsiStatus.getBlockingCount() > 0 && imsiStatus.getBlacklistedTime() != 0) { - outFields["IMSI"] = 0; - outFields["PROFILE"] = "none"; - outFields["BLACKLIST_ON"] = false; - outFields["PROBE_ON"] = false; - - return true; -} - -imsiStatus.incrementBlockingCount(); -imsiStatus.setBlacklistedTime(System.currentTimeMillis()); - -logger.debug("Bocking count for IMSI: " + imsiStatus.getImsi() + " is: " + imsiStatus.getBlockingCount()); -getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); - -outFields["PROFILE"] = "ServiceA"; -outFields["BLACKLIST_ON"] = true; -outFields["PROBE_ON"] = false; - -if (imsiStatus.getBlockingCount() > 1) { - logger.debug("POLICY SAPCPolicy - blacklisting imsi: " + outFields["IMSI"] + " permanently"); -} -else { - logger.debug("POLICY SAPCPolicy - blacklisting imsi: " + outFields["IMSI"] + " temporary for 120000 ms"); -} - -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTaskTaskLogic.mvel new file mode 100644 index 000000000..1de8b190c --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTaskTaskLogic.mvel @@ -0,0 +1,52 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +if (inFields["ACTTASK"] != null && inFields["ACTTASK"].equals("no")) { + outFields["IMSI"] = 0; + outFields["IMSI_IP"] = "0"; + return true; +} + +if (inFields["PROBE_ON"] != null) { + outFields["PROBE_ON"] = inFields["PROBE_ON"]; +} +else{ + outFields["PROBE_ON"] = false; +} + +if (inFields["TCP_ON"] != null) { + outFields["TCP_ON"] = inFields["TCP_ON"]; +} +else{ + outFields["TCP_ON"] = false; +} + +outFields["IMSI"] = inFields["IMSI"]; +if (inFields["IMSI_IP"] != null) { + outFields["IMSI_IP"] = inFields["IMSI_IP"]; +} + +if (inFields["NW_IP"] != null) { + outFields["NW_IP"] = inFields["NW_IP"]; +} + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTask_TaskLogic.mvel deleted file mode 100644 index 1de8b190c..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/SAPCMatchTask_TaskLogic.mvel +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -if (inFields["ACTTASK"] != null && inFields["ACTTASK"].equals("no")) { - outFields["IMSI"] = 0; - outFields["IMSI_IP"] = "0"; - return true; -} - -if (inFields["PROBE_ON"] != null) { - outFields["PROBE_ON"] = inFields["PROBE_ON"]; -} -else{ - outFields["PROBE_ON"] = false; -} - -if (inFields["TCP_ON"] != null) { - outFields["TCP_ON"] = inFields["TCP_ON"]; -} -else{ - outFields["TCP_ON"] = false; -} - -outFields["IMSI"] = inFields["IMSI"]; -if (inFields["IMSI_IP"] != null) { - outFields["IMSI_IP"] = inFields["IMSI_IP"]; -} - -if (inFields["NW_IP"] != null) { - outFields["NW_IP"] = inFields["NW_IP"]; -} - -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTaskTaskLogic.mvel new file mode 100644 index 000000000..db1abdfe9 --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTaskTaskLogic.mvel @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +outFields["TRIGGER_SPEC"] = "vMMEThresholdEvent"; +outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; + +if (outFields["IMSI"] == null) { + outFields["IMSI"] = 0; +} + +if (outFields["ENODEB_ID"] == null) { + outFields["ENODEB_ID"] = 0; +} + +if (outFields["IMSI_IP"] == null) { + outFields["IMSI_IP"] = ""; +} + +if (outFields["NW_IP"] == null) { + outFields["NW_IP"] = ""; +} + +outFields["PROFILE"] = "ServiceA"; +outFields["THRESHOLD"] = 20; +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTask_TaskLogic.mvel deleted file mode 100644 index db1abdfe9..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEActTask_TaskLogic.mvel +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -outFields["TRIGGER_SPEC"] = "vMMEThresholdEvent"; -outFields["MAJ_MIN_MAINT_VERSION"] = "0.0.1"; - -if (outFields["IMSI"] == null) { - outFields["IMSI"] = 0; -} - -if (outFields["ENODEB_ID"] == null) { - outFields["ENODEB_ID"] = 0; -} - -if (outFields["IMSI_IP"] == null) { - outFields["IMSI_IP"] = ""; -} - -if (outFields["NW_IP"] == null) { - outFields["NW_IP"] = ""; -} - -outFields["PROFILE"] = "ServiceA"; -outFields["THRESHOLD"] = 20; -return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTaskTaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTaskTaskLogic.mvel new file mode 100644 index 000000000..33dbd4cd0 --- /dev/null +++ b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTaskTaskLogic.mvel @@ -0,0 +1,47 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug(subject.id + ":" + subject.taskName + " execution logic"); +logger.debug(inFields); + +if (inFields["PROBE_ON"] != null) { + outFields["PROBE_ON"] = inFields["PROBE_ON"]; +} +else{ + outFields["PROBE_ON"] = false; +} + +if (inFields["TCP_ON"] != null) { + outFields["TCP_ON"] = inFields["TCP_ON"]; +} +else{ + outFields["TCP_ON"] = false; +} + +outFields["IMSI"] = inFields["IMSI"]; +if (inFields["IMSI_IP"] != null) { + outFields["IMSI_IP"] = inFields["IMSI_IP"]; +} + +if (inFields["NW_IP"] != null) { + outFields["NW_IP"] = inFields["NW_IP"]; +} +outFields["VERSION"] = inFields.getkey().getVersion(); + +return true; diff --git a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTask_TaskLogic.mvel b/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTask_TaskLogic.mvel deleted file mode 100644 index 33dbd4cd0..000000000 --- a/examples/examples-aadm/src/main/resources/org/onap/policy/apex/examples/aadm/model/mvel/VMMEMatchTask_TaskLogic.mvel +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -logger.debug(subject.id + ":" + subject.taskName + " execution logic"); -logger.debug(inFields); - -if (inFields["PROBE_ON"] != null) { - outFields["PROBE_ON"] = inFields["PROBE_ON"]; -} -else{ - outFields["PROBE_ON"] = false; -} - -if (inFields["TCP_ON"] != null) { - outFields["TCP_ON"] = inFields["TCP_ON"]; -} -else{ - outFields["TCP_ON"] = false; -} - -outFields["IMSI"] = inFields["IMSI"]; -if (inFields["IMSI_IP"] != null) { - outFields["IMSI_IP"] = inFields["IMSI_IP"]; -} - -if (inFields["NW_IP"] != null) { - outFields["NW_IP"] = inFields["NW_IP"]; -} -outFields["VERSION"] = inFields.getkey().getVersion(); - -return true; diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java index f574c74ec..c70c9feb6 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java @@ -120,7 +120,7 @@ public class AnomalyDetection implements Serializable { * * @param anomalyScores the anomaly score values of the algorithm */ - public void setAnomalyScores(final LinkedList anomalyScores) { + public void setAnomalyScores(final List anomalyScores) { this.anomalyScores = anomalyScores; } diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AutoLearn.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AutoLearn.java index f2e27725b..d935af5f0 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AutoLearn.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AutoLearn.java @@ -35,11 +35,6 @@ public class AutoLearn implements Serializable { private List counts = null; - /** - * The Constructor creates an AutoLearn concept. - */ - public AutoLearn() {} - /** * Checks if the Autolearn instance is initialized. * @@ -55,14 +50,14 @@ public class AutoLearn implements Serializable { * @param size the number of convergent variables to use */ public void init(final int size) { - if (avDiffs == null || avDiffs.size() == 0) { + if (avDiffs == null || avDiffs.isEmpty()) { avDiffs = new ArrayList<>(size); for (int i = 0; i < size; i++) { avDiffs.add(i, Double.NaN); } } - if (counts == null || counts.size() == 0) { + if (counts == null || counts.isEmpty()) { counts = new ArrayList<>(size); for (int i = 0; i < size; i++) { counts.add(i, 0L); diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelFactory.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelFactory.java index 6b71468d9..d13f93099 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelFactory.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelFactory.java @@ -50,6 +50,19 @@ import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; * The Class AdaptiveDomainModelFactory. */ public class AdaptiveDomainModelFactory { + // Recurring string constants + private static final String LAST_MONITORED_VALUE = "LastMonitoredValue"; + private static final String TASK_SELECTION_LOGIC = "TaskSelectionLogic"; + private static final String DEFAULT_STATE_LOGIC = "DefaultState_Logic"; + private static final String TASK_LOGIC = "TaskLogic"; + private static final String DECIDE = "Decide"; + private static final String ESTABLISH = "Establish"; + private static final String MATCH = "Match"; + private static final String EXTERNAL = "External"; + private static final String DEFAULT_NAMESPACE = "org.onap.policy.apex.examples.adaptive.events"; + private static final String ITERATION2 = "Iteration"; + private static final String DEFAULT_VERSION = "0.0.1"; + private static final String MONITORED_VALUE = "MonitoredValue"; /** * Gets the anomaly detection policy model. @@ -60,130 +73,142 @@ public class AdaptiveDomainModelFactory { public AxPolicyModel getAnomalyDetectionPolicyModel() { // CHECKSTYLE:ON: checkstyle:maximumMethodLength // Data types for event parameters - final AxContextSchema monitoredValue = - new AxContextSchema(new AxArtifactKey("MonitoredValue", "0.0.1"), "Java", "java.lang.Double"); - final AxContextSchema iteration = - new AxContextSchema(new AxArtifactKey("Iteration", "0.0.1"), "Java", "java.lang.Integer"); + final AxContextSchema monitoredValue = new AxContextSchema(new AxArtifactKey(MONITORED_VALUE, DEFAULT_VERSION), + "Java", "java.lang.Double"); + final AxContextSchema iteration = new AxContextSchema(new AxArtifactKey(ITERATION2, DEFAULT_VERSION), "Java", + "java.lang.Integer"); - final AxContextSchemas adContextSchemas = new AxContextSchemas(new AxArtifactKey("AADMDatatypes", "0.0.1")); + final AxContextSchemas adContextSchemas = new AxContextSchemas( + new AxArtifactKey("AADMDatatypes", DEFAULT_VERSION)); adContextSchemas.getSchemasMap().put(monitoredValue.getKey(), monitoredValue); adContextSchemas.getSchemasMap().put(iteration.getKey(), iteration); - final AxEvent anomalyDetectionTriggerEvent = - new AxEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - anomalyDetectionTriggerEvent.setSource("External"); - anomalyDetectionTriggerEvent.setTarget("Match"); - anomalyDetectionTriggerEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(anomalyDetectionTriggerEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - anomalyDetectionTriggerEvent.getParameterMap().put("Iteration", new AxField( - new AxReferenceKey(anomalyDetectionTriggerEvent.getKey(), "Iteration"), iteration.getKey())); - - final AxEvent anomalyDetectionMatchEvent = new AxEvent(new AxArtifactKey("AnomalyDetectionMatchEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - anomalyDetectionMatchEvent.setSource("Match"); - anomalyDetectionMatchEvent.setTarget("Establish"); - anomalyDetectionMatchEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(anomalyDetectionMatchEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - anomalyDetectionMatchEvent.getParameterMap().put("Iteration", - new AxField(new AxReferenceKey(anomalyDetectionMatchEvent.getKey(), "Iteration"), iteration.getKey())); - - final AxEvent anomalyDetectionEstablishEvent = - new AxEvent(new AxArtifactKey("AnomalyDetectionEstablishEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - anomalyDetectionEstablishEvent.setSource("Establish"); - anomalyDetectionEstablishEvent.setTarget("Decide"); - anomalyDetectionEstablishEvent.getParameterMap().put("MonitoredValue", - new AxField(new AxReferenceKey(anomalyDetectionEstablishEvent.getKey(), "MonitoredValue"), - monitoredValue.getKey())); - anomalyDetectionEstablishEvent.getParameterMap().put("Iteration", new AxField( - new AxReferenceKey(anomalyDetectionEstablishEvent.getKey(), "Iteration"), iteration.getKey())); - - final AxEvent anomalyDetectionDecideEvent = - new AxEvent(new AxArtifactKey("AnomalyDetectionDecideEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - anomalyDetectionDecideEvent.setSource("Decide"); + final AxEvent anomalyDetectionTriggerEvent = new AxEvent( + new AxArtifactKey("AnomalyDetectionTriggerEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + anomalyDetectionTriggerEvent.setSource(EXTERNAL); + anomalyDetectionTriggerEvent.setTarget(MATCH); + anomalyDetectionTriggerEvent.getParameterMap().put(MONITORED_VALUE, + new AxField(new AxReferenceKey(anomalyDetectionTriggerEvent.getKey(), MONITORED_VALUE), + monitoredValue.getKey())); + anomalyDetectionTriggerEvent.getParameterMap().put(ITERATION2, new AxField( + new AxReferenceKey(anomalyDetectionTriggerEvent.getKey(), ITERATION2), iteration.getKey())); + + final AxEvent anomalyDetectionMatchEvent = new AxEvent( + new AxArtifactKey("AnomalyDetectionMatchEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + anomalyDetectionMatchEvent.setSource(MATCH); + anomalyDetectionMatchEvent.setTarget(ESTABLISH); + anomalyDetectionMatchEvent.getParameterMap().put(MONITORED_VALUE, + new AxField(new AxReferenceKey(anomalyDetectionMatchEvent.getKey(), MONITORED_VALUE), + monitoredValue.getKey())); + anomalyDetectionMatchEvent.getParameterMap().put(ITERATION2, new AxField( + new AxReferenceKey(anomalyDetectionMatchEvent.getKey(), ITERATION2), iteration.getKey())); + + final AxEvent anomalyDetectionEstablishEvent = new AxEvent( + new AxArtifactKey("AnomalyDetectionEstablishEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + anomalyDetectionEstablishEvent.setSource(ESTABLISH); + anomalyDetectionEstablishEvent.setTarget(DECIDE); + anomalyDetectionEstablishEvent.getParameterMap().put(MONITORED_VALUE, + new AxField(new AxReferenceKey(anomalyDetectionEstablishEvent.getKey(), MONITORED_VALUE), + monitoredValue.getKey())); + anomalyDetectionEstablishEvent.getParameterMap().put(ITERATION2, new AxField( + new AxReferenceKey(anomalyDetectionEstablishEvent.getKey(), ITERATION2), iteration.getKey())); + + final AxEvent anomalyDetectionDecideEvent = new AxEvent( + new AxArtifactKey("AnomalyDetectionDecideEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + anomalyDetectionDecideEvent.setSource(DECIDE); anomalyDetectionDecideEvent.setTarget("Act"); - anomalyDetectionDecideEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(anomalyDetectionDecideEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - anomalyDetectionDecideEvent.getParameterMap().put("Iteration", - new AxField(new AxReferenceKey(anomalyDetectionDecideEvent.getKey(), "Iteration"), iteration.getKey())); - - final AxEvent anomalyDetectionActEvent = new AxEvent(new AxArtifactKey("AnomalyDetectionActEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); + anomalyDetectionDecideEvent.getParameterMap().put(MONITORED_VALUE, + new AxField(new AxReferenceKey(anomalyDetectionDecideEvent.getKey(), MONITORED_VALUE), + monitoredValue.getKey())); + anomalyDetectionDecideEvent.getParameterMap().put(ITERATION2, new AxField( + new AxReferenceKey(anomalyDetectionDecideEvent.getKey(), ITERATION2), iteration.getKey())); + + final AxEvent anomalyDetectionActEvent = new AxEvent( + new AxArtifactKey("AnomalyDetectionActEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); anomalyDetectionActEvent.setSource("Act"); - anomalyDetectionActEvent.setTarget("External"); - anomalyDetectionActEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(anomalyDetectionActEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - anomalyDetectionActEvent.getParameterMap().put("Iteration", - new AxField(new AxReferenceKey(anomalyDetectionActEvent.getKey(), "Iteration"), iteration.getKey())); - - final AxEvents anomalyDetectionEvents = new AxEvents(new AxArtifactKey("AnomalyDetectionEvents", "0.0.1")); + anomalyDetectionActEvent.setTarget(EXTERNAL); + anomalyDetectionActEvent.getParameterMap().put(MONITORED_VALUE, + new AxField(new AxReferenceKey(anomalyDetectionActEvent.getKey(), MONITORED_VALUE), + monitoredValue.getKey())); + anomalyDetectionActEvent.getParameterMap().put(ITERATION2, new AxField( + new AxReferenceKey(anomalyDetectionActEvent.getKey(), ITERATION2), iteration.getKey())); + + final AxEvents anomalyDetectionEvents = new AxEvents( + new AxArtifactKey("AnomalyDetectionEvents", DEFAULT_VERSION)); anomalyDetectionEvents.getEventMap().put(anomalyDetectionTriggerEvent.getKey(), anomalyDetectionTriggerEvent); anomalyDetectionEvents.getEventMap().put(anomalyDetectionMatchEvent.getKey(), anomalyDetectionMatchEvent); anomalyDetectionEvents.getEventMap().put(anomalyDetectionEstablishEvent.getKey(), - anomalyDetectionEstablishEvent); + anomalyDetectionEstablishEvent); anomalyDetectionEvents.getEventMap().put(anomalyDetectionDecideEvent.getKey(), anomalyDetectionDecideEvent); anomalyDetectionEvents.getEventMap().put(anomalyDetectionActEvent.getKey(), anomalyDetectionActEvent); // Data types for context - final AxContextSchema anomalyDetection = new AxContextSchema(new AxArtifactKey("AnomalyDetection", "0.0.1"), - "Java", "org.onap.policy.apex.examples.adaptive.concepts.AnomalyDetection"); + final AxContextSchema anomalyDetection = new AxContextSchema( + new AxArtifactKey("AnomalyDetection", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.examples.adaptive.concepts.AnomalyDetection"); adContextSchemas.getSchemasMap().put(anomalyDetection.getKey(), anomalyDetection); // One context map final AxContextAlbum anomalyDetectionAlbum = new AxContextAlbum( - new AxArtifactKey("AnomalyDetectionAlbum", "0.0.1"), "APPLICATION", true, anomalyDetection.getKey()); - final AxContextAlbums anomalyDetectionAlbums = - new AxContextAlbums(new AxArtifactKey("AnomalyDetectionAlbums", "0.0.1")); + new AxArtifactKey("AnomalyDetectionAlbum", DEFAULT_VERSION), "APPLICATION", true, + anomalyDetection.getKey()); + final AxContextAlbums anomalyDetectionAlbums = new AxContextAlbums( + new AxArtifactKey("AnomalyDetectionAlbums", DEFAULT_VERSION)); anomalyDetectionAlbums.getAlbumsMap().put(anomalyDetectionAlbum.getKey(), anomalyDetectionAlbum); // Tasks - final AxLogicReader logicReader = - new PolicyLogicReader().setLogicPackage(this.getClass().getPackage().getName()) + final AxLogicReader logicReader = new PolicyLogicReader() + .setLogicPackage(this.getClass().getPackage().getName()) .setDefaultLogic("DefaultAnomalyDetectionTask_Logic"); - final AxTask anomalyDetectionMatchTask = new AxTask(new AxArtifactKey("AnomalyDetectionMatchTask", "0.0.1")); + final AxTask anomalyDetectionMatchTask = new AxTask( + new AxArtifactKey("AnomalyDetectionMatchTask", DEFAULT_VERSION)); anomalyDetectionMatchTask.duplicateInputFields(anomalyDetectionTriggerEvent.getParameterMap()); anomalyDetectionMatchTask.duplicateOutputFields(anomalyDetectionMatchEvent.getParameterMap()); - anomalyDetectionMatchTask - .setTaskLogic(new AxTaskLogic(anomalyDetectionMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + anomalyDetectionMatchTask.setTaskLogic( + new AxTaskLogic(anomalyDetectionMatchTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask anomalyDetectionEstablishTask = - new AxTask(new AxArtifactKey("AnomalyDetectionEstablishTask", "0.0.1")); + final AxTask anomalyDetectionEstablishTask = new AxTask( + new AxArtifactKey("AnomalyDetectionEstablishTask", DEFAULT_VERSION)); anomalyDetectionEstablishTask.duplicateInputFields(anomalyDetectionMatchEvent.getParameterMap()); anomalyDetectionEstablishTask.duplicateOutputFields(anomalyDetectionEstablishEvent.getParameterMap()); anomalyDetectionEstablishTask.setTaskLogic( - new AxTaskLogic(anomalyDetectionEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + new AxTaskLogic(anomalyDetectionEstablishTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask anomalyDetectionDecideTask0 = - new AxTask(new AxArtifactKey("AnomalyDetectionDecideTask0", "0.0.1")); + final AxTask anomalyDetectionDecideTask0 = new AxTask( + new AxArtifactKey("AnomalyDetectionDecideTask0", DEFAULT_VERSION)); anomalyDetectionDecideTask0.duplicateInputFields(anomalyDetectionEstablishEvent.getParameterMap()); anomalyDetectionDecideTask0.duplicateOutputFields(anomalyDetectionDecideEvent.getParameterMap()); - anomalyDetectionDecideTask0 - .setTaskLogic(new AxTaskLogic(anomalyDetectionDecideTask0.getKey(), "TaskLogic", "MVEL", logicReader)); + anomalyDetectionDecideTask0.setTaskLogic( + new AxTaskLogic(anomalyDetectionDecideTask0.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask anomalyDetectionDecideTask1 = - new AxTask(new AxArtifactKey("AnomalyDetectionDecideTask1", "0.0.1")); + final AxTask anomalyDetectionDecideTask1 = new AxTask( + new AxArtifactKey("AnomalyDetectionDecideTask1", DEFAULT_VERSION)); anomalyDetectionDecideTask1.duplicateInputFields(anomalyDetectionEstablishEvent.getParameterMap()); anomalyDetectionDecideTask1.duplicateOutputFields(anomalyDetectionDecideEvent.getParameterMap()); - anomalyDetectionDecideTask1 - .setTaskLogic(new AxTaskLogic(anomalyDetectionDecideTask1.getKey(), "TaskLogic", "MVEL", logicReader)); + anomalyDetectionDecideTask1.setTaskLogic( + new AxTaskLogic(anomalyDetectionDecideTask1.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask anomalyDetectionDecideTask2 = - new AxTask(new AxArtifactKey("AnomalyDetectionDecideTask2", "0.0.1")); + final AxTask anomalyDetectionDecideTask2 = new AxTask( + new AxArtifactKey("AnomalyDetectionDecideTask2", DEFAULT_VERSION)); anomalyDetectionDecideTask2.duplicateInputFields(anomalyDetectionEstablishEvent.getParameterMap()); anomalyDetectionDecideTask2.duplicateOutputFields(anomalyDetectionDecideEvent.getParameterMap()); - anomalyDetectionDecideTask2 - .setTaskLogic(new AxTaskLogic(anomalyDetectionDecideTask2.getKey(), "TaskLogic", "MVEL", logicReader)); + anomalyDetectionDecideTask2.setTaskLogic( + new AxTaskLogic(anomalyDetectionDecideTask2.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask anomalyDetectionActTask = new AxTask(new AxArtifactKey("AnomalyDetectionActTask", "0.0.1")); + final AxTask anomalyDetectionActTask = new AxTask( + new AxArtifactKey("AnomalyDetectionActTask", DEFAULT_VERSION)); anomalyDetectionActTask.duplicateInputFields(anomalyDetectionDecideEvent.getParameterMap()); anomalyDetectionActTask.duplicateOutputFields(anomalyDetectionActEvent.getParameterMap()); - anomalyDetectionActTask - .setTaskLogic(new AxTaskLogic(anomalyDetectionActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + anomalyDetectionActTask.setTaskLogic( + new AxTaskLogic(anomalyDetectionActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTasks anomalyDetectionTasks = new AxTasks(new AxArtifactKey("AnomalyDetectionTasks", "0.0.1")); + final AxTasks anomalyDetectionTasks = new AxTasks(new AxArtifactKey("AnomalyDetectionTasks", DEFAULT_VERSION)); anomalyDetectionTasks.getTaskMap().put(anomalyDetectionMatchTask.getKey(), anomalyDetectionMatchTask); anomalyDetectionTasks.getTaskMap().put(anomalyDetectionEstablishTask.getKey(), anomalyDetectionEstablishTask); anomalyDetectionTasks.getTaskMap().put(anomalyDetectionDecideTask0.getKey(), anomalyDetectionDecideTask0); @@ -192,92 +217,98 @@ public class AdaptiveDomainModelFactory { anomalyDetectionTasks.getTaskMap().put(anomalyDetectionActTask.getKey(), anomalyDetectionActTask); // Policies - logicReader.setDefaultLogic("DefaultState_Logic"); + logicReader.setDefaultLogic(DEFAULT_STATE_LOGIC); - final AxPolicy anomalyDetectionPolicy = new AxPolicy(new AxArtifactKey("AnomalyDetectionPolicy", "0.0.1")); + final AxPolicy anomalyDetectionPolicy = new AxPolicy( + new AxArtifactKey("AnomalyDetectionPolicy", DEFAULT_VERSION)); anomalyDetectionPolicy.setTemplate("MEDA"); - final AxState anomalyDetectionActState = - new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Act")); + final AxState anomalyDetectionActState = new AxState( + new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Act")); anomalyDetectionActState.setTrigger(anomalyDetectionDecideEvent.getKey()); final AxStateOutput adAct2Out = new AxStateOutput(anomalyDetectionActState.getKey(), - AxReferenceKey.getNullKey(), anomalyDetectionActEvent.getKey()); + AxReferenceKey.getNullKey(), anomalyDetectionActEvent.getKey()); anomalyDetectionActState.getStateOutputs().put(adAct2Out.getKey().getLocalName(), adAct2Out); - anomalyDetectionActState.setTaskSelectionLogic( - new AxTaskSelectionLogic(anomalyDetectionActState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + anomalyDetectionActState.setTaskSelectionLogic(new AxTaskSelectionLogic(anomalyDetectionActState.getKey(), + TASK_SELECTION_LOGIC, "MVEL", logicReader)); anomalyDetectionActState.setDefaultTask(anomalyDetectionActTask.getKey()); anomalyDetectionActState.getTaskReferences().put(anomalyDetectionActTask.getKey(), - new AxStateTaskReference(anomalyDetectionActState.getKey(), anomalyDetectionActTask.getKey(), - AxStateTaskOutputType.DIRECT, adAct2Out.getKey())); + new AxStateTaskReference(anomalyDetectionActState.getKey(), anomalyDetectionActTask.getKey(), + AxStateTaskOutputType.DIRECT, adAct2Out.getKey())); logicReader.setDefaultLogic(null); - final AxState anomalyDetectionDecideState = - new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Decide")); + final AxState anomalyDetectionDecideState = new AxState( + new AxReferenceKey(anomalyDetectionPolicy.getKey(), DECIDE)); anomalyDetectionDecideState.setTrigger(anomalyDetectionEstablishEvent.getKey()); final AxStateOutput adDec2Act = new AxStateOutput(anomalyDetectionDecideState.getKey(), - anomalyDetectionActState.getKey(), anomalyDetectionDecideEvent.getKey()); + anomalyDetectionActState.getKey(), anomalyDetectionDecideEvent.getKey()); anomalyDetectionDecideState.getStateOutputs().put(adDec2Act.getKey().getLocalName(), adDec2Act); anomalyDetectionDecideState.setTaskSelectionLogic(new AxTaskSelectionLogic(anomalyDetectionDecideState.getKey(), - "TaskSelectionLogic", "JAVA", logicReader)); + TASK_SELECTION_LOGIC, "JAVA", logicReader)); anomalyDetectionDecideState.setDefaultTask(anomalyDetectionDecideTask0.getKey()); anomalyDetectionDecideState.getContextAlbumReferences().add(anomalyDetectionAlbum.getKey()); anomalyDetectionDecideState.getTaskReferences().put(anomalyDetectionDecideTask0.getKey(), - new AxStateTaskReference(anomalyDetectionDecideState.getKey(), anomalyDetectionDecideTask0.getKey(), - AxStateTaskOutputType.DIRECT, adDec2Act.getKey())); + new AxStateTaskReference(anomalyDetectionDecideState.getKey(), + anomalyDetectionDecideTask0.getKey(), AxStateTaskOutputType.DIRECT, + adDec2Act.getKey())); anomalyDetectionDecideState.getTaskReferences().put(anomalyDetectionDecideTask1.getKey(), - new AxStateTaskReference(anomalyDetectionDecideState.getKey(), anomalyDetectionDecideTask1.getKey(), - AxStateTaskOutputType.DIRECT, adDec2Act.getKey())); + new AxStateTaskReference(anomalyDetectionDecideState.getKey(), + anomalyDetectionDecideTask1.getKey(), AxStateTaskOutputType.DIRECT, + adDec2Act.getKey())); anomalyDetectionDecideState.getTaskReferences().put(anomalyDetectionDecideTask2.getKey(), - new AxStateTaskReference(anomalyDetectionDecideState.getKey(), anomalyDetectionDecideTask2.getKey(), - AxStateTaskOutputType.DIRECT, adDec2Act.getKey())); + new AxStateTaskReference(anomalyDetectionDecideState.getKey(), + anomalyDetectionDecideTask2.getKey(), AxStateTaskOutputType.DIRECT, + adDec2Act.getKey())); - logicReader.setDefaultLogic("DefaultState_Logic"); + logicReader.setDefaultLogic(DEFAULT_STATE_LOGIC); - final AxState anomalyDetectionEstablishState = - new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Establish")); + final AxState anomalyDetectionEstablishState = new AxState( + new AxReferenceKey(anomalyDetectionPolicy.getKey(), ESTABLISH)); anomalyDetectionEstablishState.setTrigger(anomalyDetectionMatchEvent.getKey()); final AxStateOutput adEst2Dec = new AxStateOutput(anomalyDetectionEstablishState.getKey(), - anomalyDetectionDecideState.getKey(), anomalyDetectionEstablishEvent.getKey()); + anomalyDetectionDecideState.getKey(), anomalyDetectionEstablishEvent.getKey()); anomalyDetectionEstablishState.getStateOutputs().put(adEst2Dec.getKey().getLocalName(), adEst2Dec); anomalyDetectionEstablishState.setTaskSelectionLogic(new AxTaskSelectionLogic( - anomalyDetectionEstablishState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + anomalyDetectionEstablishState.getKey(), TASK_SELECTION_LOGIC, "MVEL", logicReader)); anomalyDetectionEstablishState.setDefaultTask(anomalyDetectionEstablishTask.getKey()); anomalyDetectionEstablishState.getTaskReferences().put(anomalyDetectionEstablishTask.getKey(), - new AxStateTaskReference(anomalyDetectionEstablishState.getKey(), - anomalyDetectionEstablishTask.getKey(), AxStateTaskOutputType.DIRECT, adEst2Dec.getKey())); + new AxStateTaskReference(anomalyDetectionEstablishState.getKey(), + anomalyDetectionEstablishTask.getKey(), AxStateTaskOutputType.DIRECT, + adEst2Dec.getKey())); - final AxState anomalyDetectionMatchState = - new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Match")); + final AxState anomalyDetectionMatchState = new AxState( + new AxReferenceKey(anomalyDetectionPolicy.getKey(), MATCH)); anomalyDetectionMatchState.setTrigger(anomalyDetectionTriggerEvent.getKey()); final AxStateOutput adMat2Est = new AxStateOutput(anomalyDetectionMatchState.getKey(), - anomalyDetectionEstablishState.getKey(), anomalyDetectionMatchEvent.getKey()); + anomalyDetectionEstablishState.getKey(), anomalyDetectionMatchEvent.getKey()); anomalyDetectionMatchState.getStateOutputs().put(adMat2Est.getKey().getLocalName(), adMat2Est); anomalyDetectionMatchState.setTaskSelectionLogic(new AxTaskSelectionLogic(anomalyDetectionMatchState.getKey(), - "TaskSelectionLogic", "MVEL", logicReader)); + TASK_SELECTION_LOGIC, "MVEL", logicReader)); anomalyDetectionMatchState.setDefaultTask(anomalyDetectionMatchTask.getKey()); anomalyDetectionMatchState.getTaskReferences().put(anomalyDetectionMatchTask.getKey(), - new AxStateTaskReference(anomalyDetectionMatchState.getKey(), anomalyDetectionMatchTask.getKey(), - AxStateTaskOutputType.DIRECT, adMat2Est.getKey())); + new AxStateTaskReference(anomalyDetectionMatchState.getKey(), + anomalyDetectionMatchTask.getKey(), AxStateTaskOutputType.DIRECT, + adMat2Est.getKey())); anomalyDetectionPolicy.setFirstState(anomalyDetectionMatchState.getKey().getLocalName()); anomalyDetectionPolicy.getStateMap().put(anomalyDetectionMatchState.getKey().getLocalName(), - anomalyDetectionMatchState); + anomalyDetectionMatchState); anomalyDetectionPolicy.getStateMap().put(anomalyDetectionEstablishState.getKey().getLocalName(), - anomalyDetectionEstablishState); + anomalyDetectionEstablishState); anomalyDetectionPolicy.getStateMap().put(anomalyDetectionDecideState.getKey().getLocalName(), - anomalyDetectionDecideState); + anomalyDetectionDecideState); anomalyDetectionPolicy.getStateMap().put(anomalyDetectionActState.getKey().getLocalName(), - anomalyDetectionActState); + anomalyDetectionActState); - final AxPolicies anomalyDetectionPolicies = - new AxPolicies(new AxArtifactKey("AnomalyDetectionPolicies", "0.0.1")); + final AxPolicies anomalyDetectionPolicies = new AxPolicies( + new AxArtifactKey("AnomalyDetectionPolicies", DEFAULT_VERSION)); anomalyDetectionPolicies.getPolicyMap().put(anomalyDetectionPolicy.getKey(), anomalyDetectionPolicy); - final AxKeyInformation keyInformation = - new AxKeyInformation(new AxArtifactKey("AnomalyDetectionKeyInformation", "0.0.1")); - final AxPolicyModel anomalyDetectionPolicyModel = - new AxPolicyModel(new AxArtifactKey("AnomalyDetectionPolicyModel", "0.0.1")); + final AxKeyInformation keyInformation = new AxKeyInformation( + new AxArtifactKey("AnomalyDetectionKeyInformation", DEFAULT_VERSION)); + final AxPolicyModel anomalyDetectionPolicyModel = new AxPolicyModel( + new AxArtifactKey("AnomalyDetectionPolicyModel", DEFAULT_VERSION)); anomalyDetectionPolicyModel.setPolicies(anomalyDetectionPolicies); anomalyDetectionPolicyModel.setEvents(anomalyDetectionEvents); anomalyDetectionPolicyModel.setTasks(anomalyDetectionTasks); @@ -302,58 +333,65 @@ public class AdaptiveDomainModelFactory { public AxPolicyModel getAutoLearnPolicyModel() { // CHECKSTYLE:ON: checkstyle:maximumMethodLength // Data types for event parameters - final AxContextSchema monitoredValue = - new AxContextSchema(new AxArtifactKey("MonitoredValue", "0.0.1"), "Java", "java.lang.Double"); + final AxContextSchema monitoredValue = new AxContextSchema(new AxArtifactKey(MONITORED_VALUE, DEFAULT_VERSION), + "Java", "java.lang.Double"); - final AxContextSchemas alContextSchemas = new AxContextSchemas(new AxArtifactKey("ALDatatypes", "0.0.1")); + final AxContextSchemas alContextSchemas = new AxContextSchemas( + new AxArtifactKey("ALDatatypes", DEFAULT_VERSION)); alContextSchemas.getSchemasMap().put(monitoredValue.getKey(), monitoredValue); - final AxEvent autoLearnTriggerEvent = new AxEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - autoLearnTriggerEvent.setSource("External"); - autoLearnTriggerEvent.setTarget("Match"); - autoLearnTriggerEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(autoLearnTriggerEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - autoLearnTriggerEvent.getParameterMap().put("LastMonitoredValue", new AxField( - new AxReferenceKey(autoLearnTriggerEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); - - final AxEvent autoLearnMatchEvent = new AxEvent(new AxArtifactKey("AutoLearnMatchEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - autoLearnMatchEvent.setSource("Match"); - autoLearnMatchEvent.setTarget("Establish"); - autoLearnMatchEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(autoLearnMatchEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - autoLearnMatchEvent.getParameterMap().put("LastMonitoredValue", new AxField( - new AxReferenceKey(autoLearnMatchEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); - - final AxEvent autoLearnEstablishEvent = new AxEvent(new AxArtifactKey("AutoLearnEstablishEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - autoLearnEstablishEvent.setSource("Establish"); - autoLearnEstablishEvent.setTarget("Decide"); - autoLearnEstablishEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(autoLearnEstablishEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - autoLearnEstablishEvent.getParameterMap().put("LastMonitoredValue", new AxField( - new AxReferenceKey(autoLearnEstablishEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); - - final AxEvent autoLearnDecideEvent = new AxEvent(new AxArtifactKey("AutoLearnDecideEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); - autoLearnDecideEvent.setSource("Decide"); + final AxEvent autoLearnTriggerEvent = new AxEvent(new AxArtifactKey("AutoLearnTriggerEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + autoLearnTriggerEvent.setSource(EXTERNAL); + autoLearnTriggerEvent.setTarget(MATCH); + autoLearnTriggerEvent.getParameterMap().put(MONITORED_VALUE, new AxField( + new AxReferenceKey(autoLearnTriggerEvent.getKey(), MONITORED_VALUE), monitoredValue.getKey())); + autoLearnTriggerEvent.getParameterMap().put(LAST_MONITORED_VALUE, + new AxField(new AxReferenceKey(autoLearnTriggerEvent.getKey(), LAST_MONITORED_VALUE), + monitoredValue.getKey())); + + final AxEvent autoLearnMatchEvent = new AxEvent(new AxArtifactKey("AutoLearnMatchEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + autoLearnMatchEvent.setSource(MATCH); + autoLearnMatchEvent.setTarget(ESTABLISH); + autoLearnMatchEvent.getParameterMap().put(MONITORED_VALUE, new AxField( + new AxReferenceKey(autoLearnMatchEvent.getKey(), MONITORED_VALUE), monitoredValue.getKey())); + autoLearnMatchEvent.getParameterMap().put(LAST_MONITORED_VALUE, + new AxField(new AxReferenceKey(autoLearnMatchEvent.getKey(), LAST_MONITORED_VALUE), + monitoredValue.getKey())); + + final AxEvent autoLearnEstablishEvent = new AxEvent( + new AxArtifactKey("AutoLearnEstablishEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + autoLearnEstablishEvent.setSource(ESTABLISH); + autoLearnEstablishEvent.setTarget(DECIDE); + autoLearnEstablishEvent.getParameterMap().put(MONITORED_VALUE, + new AxField(new AxReferenceKey(autoLearnEstablishEvent.getKey(), MONITORED_VALUE), + monitoredValue.getKey())); + autoLearnEstablishEvent.getParameterMap().put(LAST_MONITORED_VALUE, + new AxField(new AxReferenceKey(autoLearnEstablishEvent.getKey(), LAST_MONITORED_VALUE), + monitoredValue.getKey())); + + final AxEvent autoLearnDecideEvent = new AxEvent(new AxArtifactKey("AutoLearnDecideEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + autoLearnDecideEvent.setSource(DECIDE); autoLearnDecideEvent.setTarget("Act"); - autoLearnDecideEvent.getParameterMap().put("MonitoredValue", new AxField( - new AxReferenceKey(autoLearnDecideEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - autoLearnDecideEvent.getParameterMap().put("LastMonitoredValue", new AxField( - new AxReferenceKey(autoLearnDecideEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); - - final AxEvent autoLearnActEvent = new AxEvent(new AxArtifactKey("AutoLearnActEvent", "0.0.1"), - "org.onap.policy.apex.examples.adaptive.events"); + autoLearnDecideEvent.getParameterMap().put(MONITORED_VALUE, new AxField( + new AxReferenceKey(autoLearnDecideEvent.getKey(), MONITORED_VALUE), monitoredValue.getKey())); + autoLearnDecideEvent.getParameterMap().put(LAST_MONITORED_VALUE, + new AxField(new AxReferenceKey(autoLearnDecideEvent.getKey(), LAST_MONITORED_VALUE), + monitoredValue.getKey())); + + final AxEvent autoLearnActEvent = new AxEvent(new AxArtifactKey("AutoLearnActEvent", DEFAULT_VERSION), + DEFAULT_NAMESPACE); autoLearnActEvent.setSource("Act"); - autoLearnActEvent.setTarget("External"); - autoLearnActEvent.getParameterMap().put("MonitoredValue", - new AxField(new AxReferenceKey(autoLearnActEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); - autoLearnActEvent.getParameterMap().put("LastMonitoredValue", new AxField( - new AxReferenceKey(autoLearnActEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); + autoLearnActEvent.setTarget(EXTERNAL); + autoLearnActEvent.getParameterMap().put(MONITORED_VALUE, new AxField( + new AxReferenceKey(autoLearnActEvent.getKey(), MONITORED_VALUE), monitoredValue.getKey())); + autoLearnActEvent.getParameterMap().put(LAST_MONITORED_VALUE, new AxField( + new AxReferenceKey(autoLearnActEvent.getKey(), LAST_MONITORED_VALUE), monitoredValue.getKey())); - final AxEvents autoLearnEvents = new AxEvents(new AxArtifactKey("AutoLearnEvents", "0.0.1")); + final AxEvents autoLearnEvents = new AxEvents(new AxArtifactKey("AutoLearnEvents", DEFAULT_VERSION)); autoLearnEvents.getEventMap().put(autoLearnTriggerEvent.getKey(), autoLearnTriggerEvent); autoLearnEvents.getEventMap().put(autoLearnMatchEvent.getKey(), autoLearnMatchEvent); autoLearnEvents.getEventMap().put(autoLearnEstablishEvent.getKey(), autoLearnEstablishEvent); @@ -361,84 +399,86 @@ public class AdaptiveDomainModelFactory { autoLearnEvents.getEventMap().put(autoLearnActEvent.getKey(), autoLearnActEvent); // Data types for context - final AxContextSchema autoLearn = new AxContextSchema(new AxArtifactKey("AutoLearn", "0.0.1"), "Java", - "org.onap.policy.apex.examples.adaptive.concepts.AutoLearn"); + final AxContextSchema autoLearn = new AxContextSchema(new AxArtifactKey("AutoLearn", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.examples.adaptive.concepts.AutoLearn"); alContextSchemas.getSchemasMap().put(autoLearn.getKey(), autoLearn); // One context map - final AxContextAlbum autoLearnAlbum = new AxContextAlbum(new AxArtifactKey("AutoLearnAlbum", "0.0.1"), - "APPLICATION", true, autoLearn.getKey()); + final AxContextAlbum autoLearnAlbum = new AxContextAlbum(new AxArtifactKey("AutoLearnAlbum", DEFAULT_VERSION), + "APPLICATION", true, autoLearn.getKey()); - final AxContextAlbums autoLearnAlbums = new AxContextAlbums(new AxArtifactKey("AutoLearnContext", "0.0.1")); + final AxContextAlbums autoLearnAlbums = new AxContextAlbums( + new AxArtifactKey("AutoLearnContext", DEFAULT_VERSION)); autoLearnAlbums.getAlbumsMap().put(autoLearnAlbum.getKey(), autoLearnAlbum); // Tasks final AxLogicReader logicReader = new PolicyLogicReader() - .setLogicPackage(this.getClass().getPackage().getName()).setDefaultLogic("DefaultAutoLearnTask_Logic"); + .setLogicPackage(this.getClass().getPackage().getName()) + .setDefaultLogic("DefaultAutoLearnTask_Logic"); - final AxTask autoLearnMatchTask = new AxTask(new AxArtifactKey("AutoLearnMatchTask", "0.0.1")); + final AxTask autoLearnMatchTask = new AxTask(new AxArtifactKey("AutoLearnMatchTask", DEFAULT_VERSION)); autoLearnMatchTask.duplicateInputFields(autoLearnTriggerEvent.getParameterMap()); autoLearnMatchTask.duplicateOutputFields(autoLearnMatchEvent.getParameterMap()); - autoLearnMatchTask.setTaskLogic(new AxTaskLogic(autoLearnMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + autoLearnMatchTask.setTaskLogic(new AxTaskLogic(autoLearnMatchTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask autoLearnEstablishTask = new AxTask(new AxArtifactKey("AutoLearnEstablishTask", "0.0.1")); + final AxTask autoLearnEstablishTask = new AxTask(new AxArtifactKey("AutoLearnEstablishTask", DEFAULT_VERSION)); autoLearnEstablishTask.duplicateInputFields(autoLearnMatchEvent.getParameterMap()); autoLearnEstablishTask.duplicateOutputFields(autoLearnEstablishEvent.getParameterMap()); - autoLearnEstablishTask - .setTaskLogic(new AxTaskLogic(autoLearnEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + autoLearnEstablishTask.setTaskLogic( + new AxTaskLogic(autoLearnEstablishTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); logicReader.setDefaultLogic(null); - final AxTask autoLearnDecideTask0 = new AxTask(new AxArtifactKey("AutoLearnDecideTask0", "0.0.1")); + final AxTask autoLearnDecideTask0 = new AxTask(new AxArtifactKey("AutoLearnDecideTask0", DEFAULT_VERSION)); autoLearnDecideTask0.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); autoLearnDecideTask0.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); autoLearnDecideTask0 - .setTaskLogic(new AxTaskLogic(autoLearnDecideTask0.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask0.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask autoLearnDecideTask1 = new AxTask(new AxArtifactKey("AutoLearnDecideTask1", "0.0.1")); + final AxTask autoLearnDecideTask1 = new AxTask(new AxArtifactKey("AutoLearnDecideTask1", DEFAULT_VERSION)); autoLearnDecideTask1.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); autoLearnDecideTask1.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); autoLearnDecideTask1 - .setTaskLogic(new AxTaskLogic(autoLearnDecideTask1.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask1.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask autoLearnDecideTask2 = new AxTask(new AxArtifactKey("AutoLearnDecideTask2", "0.0.1")); + final AxTask autoLearnDecideTask2 = new AxTask(new AxArtifactKey("AutoLearnDecideTask2", DEFAULT_VERSION)); autoLearnDecideTask2.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); autoLearnDecideTask2.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); autoLearnDecideTask2 - .setTaskLogic(new AxTaskLogic(autoLearnDecideTask2.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask2.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask autoLearnDecideTask3 = new AxTask(new AxArtifactKey("AutoLearnDecideTask3", "0.0.1")); + final AxTask autoLearnDecideTask3 = new AxTask(new AxArtifactKey("AutoLearnDecideTask3", DEFAULT_VERSION)); autoLearnDecideTask3.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); autoLearnDecideTask3.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); autoLearnDecideTask3 - .setTaskLogic(new AxTaskLogic(autoLearnDecideTask3.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask3.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask autoLearnDecideTask4 = new AxTask(new AxArtifactKey("AutoLearnDecideTask4", "0.0.1")); + final AxTask autoLearnDecideTask4 = new AxTask(new AxArtifactKey("AutoLearnDecideTask4", DEFAULT_VERSION)); autoLearnDecideTask4.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); autoLearnDecideTask4.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); autoLearnDecideTask4 - .setTaskLogic(new AxTaskLogic(autoLearnDecideTask4.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask4.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask autoLearnDecideTask5 = new AxTask(new AxArtifactKey("AutoLearnDecideTask5", "0.0.1")); + final AxTask autoLearnDecideTask5 = new AxTask(new AxArtifactKey("AutoLearnDecideTask5", DEFAULT_VERSION)); autoLearnDecideTask5.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); autoLearnDecideTask5.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); autoLearnDecideTask5 - .setTaskLogic(new AxTaskLogic(autoLearnDecideTask5.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask5.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTask autoLearnDecideTask6 = new AxTask(new AxArtifactKey("AutoLearnDecideTask6", "0.0.1")); + final AxTask autoLearnDecideTask6 = new AxTask(new AxArtifactKey("AutoLearnDecideTask6", DEFAULT_VERSION)); autoLearnDecideTask6.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); autoLearnDecideTask6.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); autoLearnDecideTask6 - .setTaskLogic(new AxTaskLogic(autoLearnDecideTask6.getKey(), "TaskLogic", "MVEL", logicReader)); + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask6.getKey(), TASK_LOGIC, "MVEL", logicReader)); logicReader.setDefaultLogic("DefaultAutoLearnTask_Logic"); - final AxTask autoLearnActTask = new AxTask(new AxArtifactKey("AutoLearnActTask", "0.0.1")); + final AxTask autoLearnActTask = new AxTask(new AxArtifactKey("AutoLearnActTask", DEFAULT_VERSION)); autoLearnActTask.duplicateInputFields(autoLearnDecideEvent.getParameterMap()); autoLearnActTask.duplicateOutputFields(autoLearnActEvent.getParameterMap()); - autoLearnActTask.setTaskLogic(new AxTaskLogic(autoLearnActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + autoLearnActTask.setTaskLogic(new AxTaskLogic(autoLearnActTask.getKey(), TASK_LOGIC, "MVEL", logicReader)); - final AxTasks autoLearnTasks = new AxTasks(new AxArtifactKey("AutoLearnTasks", "0.0.1")); + final AxTasks autoLearnTasks = new AxTasks(new AxArtifactKey("AutoLearnTasks", DEFAULT_VERSION)); autoLearnTasks.getTaskMap().put(autoLearnMatchTask.getKey(), autoLearnMatchTask); autoLearnTasks.getTaskMap().put(autoLearnEstablishTask.getKey(), autoLearnEstablishTask); autoLearnTasks.getTaskMap().put(autoLearnDecideTask0.getKey(), autoLearnDecideTask0); @@ -451,81 +491,81 @@ public class AdaptiveDomainModelFactory { autoLearnTasks.getTaskMap().put(autoLearnActTask.getKey(), autoLearnActTask); // Policies - logicReader.setDefaultLogic("DefaultState_Logic"); + logicReader.setDefaultLogic(DEFAULT_STATE_LOGIC); - final AxPolicy autoLearnPolicy = new AxPolicy(new AxArtifactKey("AutoLearnPolicy", "0.0.1")); + final AxPolicy autoLearnPolicy = new AxPolicy(new AxArtifactKey("AutoLearnPolicy", DEFAULT_VERSION)); autoLearnPolicy.setTemplate("MEDA"); final AxState autoLearnActState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Act")); autoLearnActState.setTrigger(autoLearnDecideEvent.getKey()); - final AxStateOutput alAct2Out = - new AxStateOutput(autoLearnActState.getKey(), AxReferenceKey.getNullKey(), autoLearnActEvent.getKey()); + final AxStateOutput alAct2Out = new AxStateOutput(autoLearnActState.getKey(), AxReferenceKey.getNullKey(), + autoLearnActEvent.getKey()); autoLearnActState.getStateOutputs().put(alAct2Out.getKey().getLocalName(), alAct2Out); - autoLearnActState.setTaskSelectionLogic( - new AxTaskSelectionLogic(autoLearnActState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + autoLearnActState.setTaskSelectionLogic(new AxTaskSelectionLogic(autoLearnActState.getKey(), + TASK_SELECTION_LOGIC, "MVEL", logicReader)); autoLearnActState.setDefaultTask(autoLearnActTask.getKey()); autoLearnActState.getTaskReferences().put(autoLearnActTask.getKey(), - new AxStateTaskReference(autoLearnActState.getKey(), autoLearnActTask.getKey(), - AxStateTaskOutputType.DIRECT, alAct2Out.getKey())); + new AxStateTaskReference(autoLearnActState.getKey(), autoLearnActTask.getKey(), + AxStateTaskOutputType.DIRECT, alAct2Out.getKey())); logicReader.setDefaultLogic(null); - final AxState autoLearnDecideState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Decide")); + final AxState autoLearnDecideState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), DECIDE)); autoLearnDecideState.setTrigger(autoLearnEstablishEvent.getKey()); final AxStateOutput alDec2Act = new AxStateOutput(autoLearnDecideState.getKey(), autoLearnActState.getKey(), - autoLearnDecideEvent.getKey()); + autoLearnDecideEvent.getKey()); autoLearnDecideState.getStateOutputs().put(alDec2Act.getKey().getLocalName(), alDec2Act); autoLearnDecideState.getContextAlbumReferences().add(autoLearnAlbum.getKey()); - autoLearnDecideState.setTaskSelectionLogic( - new AxTaskSelectionLogic(autoLearnDecideState.getKey(), "TaskSelectionLogic", "JAVA", logicReader)); + autoLearnDecideState.setTaskSelectionLogic(new AxTaskSelectionLogic(autoLearnDecideState.getKey(), + TASK_SELECTION_LOGIC, "JAVA", logicReader)); autoLearnDecideState.setDefaultTask(autoLearnDecideTask0.getKey()); autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask0.getKey(), - new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask0.getKey(), - AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask0.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask1.getKey(), - new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask1.getKey(), - AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask1.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask2.getKey(), - new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask2.getKey(), - AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask2.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask3.getKey(), - new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask3.getKey(), - AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask3.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask4.getKey(), - new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask4.getKey(), - AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask4.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask5.getKey(), - new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask5.getKey(), - AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask5.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask6.getKey(), - new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask6.getKey(), - AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask6.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); - logicReader.setDefaultLogic("DefaultState_Logic"); + logicReader.setDefaultLogic(DEFAULT_STATE_LOGIC); - final AxState autoLearnEstablishState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Establish")); + final AxState autoLearnEstablishState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), ESTABLISH)); autoLearnEstablishState.setTrigger(autoLearnMatchEvent.getKey()); final AxStateOutput alEst2Dec = new AxStateOutput(autoLearnEstablishState.getKey(), - autoLearnDecideState.getKey(), autoLearnEstablishEvent.getKey()); + autoLearnDecideState.getKey(), autoLearnEstablishEvent.getKey()); autoLearnEstablishState.getStateOutputs().put(alEst2Dec.getKey().getLocalName(), alEst2Dec); - autoLearnEstablishState.setTaskSelectionLogic( - new AxTaskSelectionLogic(autoLearnEstablishState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + autoLearnEstablishState.setTaskSelectionLogic(new AxTaskSelectionLogic(autoLearnEstablishState.getKey(), + TASK_SELECTION_LOGIC, "MVEL", logicReader)); autoLearnEstablishState.setDefaultTask(autoLearnEstablishTask.getKey()); autoLearnEstablishState.getTaskReferences().put(autoLearnEstablishTask.getKey(), - new AxStateTaskReference(autoLearnEstablishState.getKey(), autoLearnEstablishTask.getKey(), - AxStateTaskOutputType.DIRECT, alEst2Dec.getKey())); + new AxStateTaskReference(autoLearnEstablishState.getKey(), autoLearnEstablishTask.getKey(), + AxStateTaskOutputType.DIRECT, alEst2Dec.getKey())); - final AxState autoLearnMatchState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Match")); + final AxState autoLearnMatchState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), MATCH)); autoLearnMatchState.setTrigger(autoLearnTriggerEvent.getKey()); final AxStateOutput alMat2Est = new AxStateOutput(autoLearnMatchState.getKey(), - autoLearnEstablishState.getKey(), autoLearnMatchEvent.getKey()); + autoLearnEstablishState.getKey(), autoLearnMatchEvent.getKey()); autoLearnMatchState.getStateOutputs().put(alMat2Est.getKey().getLocalName(), alMat2Est); - autoLearnMatchState.setTaskSelectionLogic( - new AxTaskSelectionLogic(autoLearnMatchState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + autoLearnMatchState.setTaskSelectionLogic(new AxTaskSelectionLogic(autoLearnMatchState.getKey(), + TASK_SELECTION_LOGIC, "MVEL", logicReader)); autoLearnMatchState.setDefaultTask(autoLearnMatchTask.getKey()); autoLearnMatchState.getTaskReferences().put(autoLearnMatchTask.getKey(), - new AxStateTaskReference(autoLearnMatchState.getKey(), autoLearnMatchTask.getKey(), - AxStateTaskOutputType.DIRECT, alMat2Est.getKey())); + new AxStateTaskReference(autoLearnMatchState.getKey(), autoLearnMatchTask.getKey(), + AxStateTaskOutputType.DIRECT, alMat2Est.getKey())); autoLearnPolicy.setFirstState(autoLearnMatchState.getKey().getLocalName()); autoLearnPolicy.getStateMap().put(autoLearnMatchState.getKey().getLocalName(), autoLearnMatchState); @@ -533,13 +573,13 @@ public class AdaptiveDomainModelFactory { autoLearnPolicy.getStateMap().put(autoLearnDecideState.getKey().getLocalName(), autoLearnDecideState); autoLearnPolicy.getStateMap().put(autoLearnActState.getKey().getLocalName(), autoLearnActState); - final AxPolicies autoLearnPolicies = new AxPolicies(new AxArtifactKey("AutoLearnPolicies", "0.0.1")); + final AxPolicies autoLearnPolicies = new AxPolicies(new AxArtifactKey("AutoLearnPolicies", DEFAULT_VERSION)); autoLearnPolicies.getPolicyMap().put(autoLearnPolicy.getKey(), autoLearnPolicy); - final AxKeyInformation keyInformation = - new AxKeyInformation(new AxArtifactKey("AutoLearnKeyInformation", "0.0.1")); - final AxPolicyModel autoLearnPolicyModel = - new AxPolicyModel(new AxArtifactKey("AutoLearnPolicyModel", "0.0.1")); + final AxKeyInformation keyInformation = new AxKeyInformation( + new AxArtifactKey("AutoLearnKeyInformation", DEFAULT_VERSION)); + final AxPolicyModel autoLearnPolicyModel = new AxPolicyModel( + new AxArtifactKey("AutoLearnPolicyModel", DEFAULT_VERSION)); autoLearnPolicyModel.setPolicies(autoLearnPolicies); autoLearnPolicyModel.setEvents(autoLearnEvents); autoLearnPolicyModel.setTasks(autoLearnTasks); diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelSaver.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelSaver.java index 9c860e3c8..4949edd30 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelSaver.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelSaver.java @@ -23,6 +23,8 @@ package org.onap.policy.apex.examples.adaptive.model; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.onap.policy.apex.model.basicmodel.handling.ApexModelSaver; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; /** * This class saves sample domain models to disk in XML and JSON format. @@ -30,10 +32,15 @@ import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; * @author Liam Fallon (liam.fallon@ericsson.com) */ public final class AdaptiveDomainModelSaver { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(AdaptiveDomainModelSaver.class); + /** * Private default constructor to prevent subclassing. */ - private AdaptiveDomainModelSaver() {} + private AdaptiveDomainModelSaver() { + // Prevent subclassing + } /** * Write the AADM model to args[0]. @@ -43,21 +50,21 @@ public final class AdaptiveDomainModelSaver { */ public static void main(final String[] args) throws ApexException { if (args.length != 1) { - System.err.println("usage: " + AdaptiveDomainModelSaver.class.getCanonicalName() + " modelDirectory"); + LOGGER.error("usage: " + AdaptiveDomainModelSaver.class.getCanonicalName() + " modelDirectory"); return; } // Save Anomaly Detection model final AxPolicyModel adPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel(); final ApexModelSaver adModelSaver = - new ApexModelSaver<>(AxPolicyModel.class, adPolicyModel, args[0]); + new ApexModelSaver<>(AxPolicyModel.class, adPolicyModel, args[0]); adModelSaver.apexModelWriteJson(); adModelSaver.apexModelWriteXml(); // Save Auto Learn model final AxPolicyModel alPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel(); final ApexModelSaver alModelSaver = - new ApexModelSaver<>(AxPolicyModel.class, alPolicyModel, args[0]); + new ApexModelSaver<>(AxPolicyModel.class, alPolicyModel, args[0]); alModelSaver.apexModelWriteJson(); alModelSaver.apexModelWriteXml(); } diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java new file mode 100644 index 000000000..5ee114e0e --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java @@ -0,0 +1,410 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.model.java; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.math3.distribution.TDistribution; +import org.apache.commons.math3.util.FastMath; +import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; +import org.onap.policy.apex.examples.adaptive.concepts.AnomalyDetection; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.slf4j.Logger; + +/** + * The Class AnomalyDetectionPolicyDecideTaskSelectionLogic. + */ +public class AnomalyDetectionPolicyDecideTaskSelectionLogic { + private Logger logger; + + // Recurring string constants + private static final String ANOMALY_DETECTION_ALBUM = "AnomalyDetectionAlbum"; + private static final String ANOMALY_DETECTION = "AnomalyDetection"; + + // configuration + private static final double ANOMALY_SENSITIVITY = 0.05; + private static final int FREQUENCY = 360; + + /** + * A map to hold the Anomaly degree/levels/probabilities required for each task.
+ * If there is no task defined for a calculated anomaly-degree, then the default task is + * used.
+ * The map use (LinkedHashMap) is an insertion-ordered map, so the first interval matching a + * query is used. + */ + // CHECKSTYLE:OFF: checkstyle:magicNumber + private static final Map TASK_INTERVALS = new LinkedHashMap<>(); + + static { + TASK_INTERVALS.put(new double[] {0.0, 0.1}, null); // null will mean default task + TASK_INTERVALS.put(new double[] {0.25, 0.5}, "AnomalyDetectionDecideTask1"); + TASK_INTERVALS.put(new double[] {0.5, 1.01}, "AnomalyDetectionDecideTask2"); + } + // CHECKSTYLE:ON: checkstyle:magicNumber + + private volatile TaskSelectionExecutionContext executionContext; + + /** + * Gets the task. + * + * @param executor the executor + * @return the task + */ + public boolean getTask(final TaskSelectionExecutionContext executor) { + executionContext = executor; + logger = executionContext.logger; + String id = executor.subject.getId(); + logger.debug(id); + String inFields = executor.inFields.toString(); + logger.debug(inFields); + final double now = (Double) (executor.inFields.get("MonitoredValue")); + final Integer iteration = (Integer) (executor.inFields.get("Iteration")); + // get the double[forecastedValue, AnomalyScore, AnomalyProbability] + final double[] vals = this.forecastingAndAnomaly(now); + final double anomalyness = vals[2]; + String task = null; + for (final Map.Entry i : TASK_INTERVALS.entrySet()) { + if (checkInterval(anomalyness, i.getKey())) { + task = i.getValue(); + break; + } + } + if (task == null) { + executionContext.subject.getDefaultTaskKey().copyTo(executionContext.selectedTask); + } else { + executionContext.subject.getTaskKey(task).copyTo(executionContext.selectedTask); + } + if (logger.isDebugEnabled()) { + logger.debug( + "TestAnomalyDetectionTSLPolicy0000DecideStateTaskSelectionLogic.getTask():\t************\t\t\t\t" + + "Iteration:\t" + iteration + "\tValue:\t" + now + "\tForecast:\t" + vals[0] + + "\tAnomalyScore:\t" + vals[1] + "\tAnomalyProbability:\t" + vals[2] + "\tInvoking Task:\t" + + executionContext.selectedTask); + } + return true; + } + + /** + * Anomaly detection and forecast. + * + * @param value The current value + * @return Null if the function can not be executed correctly, otherwise double[forecastedValue, + * AnomalyScore, AnomalyProbability] + */ + public double[] forecastingAndAnomaly(final double value) { + try { + executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).lockForWriting(ANOMALY_DETECTION); + } catch (final ApexException e) { + logger.error("Failed to acquire write lock on \"AnomalyDetection\" context", e); + return new double[0]; + } + + // Get the context object + AnomalyDetection anomalyDetection = + (AnomalyDetection) executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).get(ANOMALY_DETECTION); + if (anomalyDetection == null) { + anomalyDetection = new AnomalyDetection(); + executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).put(ANOMALY_DETECTION, anomalyDetection); + } + + // Check the lists are initialized + if (!anomalyDetection.isInitialized()) { + anomalyDetection.init(FREQUENCY); + } + + boolean unsetfirstround = false; + + int frequency = anomalyDetection.getFrequency(); + frequency = frequency + 1; + + // reset frequency counter + if (frequency >= FREQUENCY) { + unsetfirstround = true; + frequency = 0; + } + anomalyDetection.setFrequency(frequency); + + if (unsetfirstround && anomalyDetection.getFirstRound()) { + anomalyDetection.setFirstRound(false); + } + + // --------- calculate the forecasted value - simple version + final Double lastForecast = anomalyDetection.getFrequencyForecasted().get(frequency); + + // get forecast for current value + final double forecastedValue = lastForecast == null ? value : expMovingAverage(value, lastForecast); + + // --------- calculate the anomalyScore + final double anomalyScore = lastForecast == null ? 0.0 : FastMath.abs(lastForecast - value); + + anomalyDetection.getFrequencyForecasted().set(frequency, forecastedValue); + + // anomaly score is ignored in the first frequency period + if (!anomalyDetection.getFirstRound()) { + ((LinkedList) anomalyDetection.getAnomalyScores()).addLast(anomalyScore); + } + + // CHECKSTYLE:OFF: checkstyle:magicNumber + // max FREQUENCY*4 anomaly scores history + listSizeControl(anomalyDetection.getAnomalyScores(), FREQUENCY * 4); + + // ---------- calculate the anomaly probability + double anomalyProbability = 0.0; + if (anomalyDetection.getAnomalyScores().size() > 30) { + // 0.5 + anomalyProbability = getStatsTest(anomalyDetection.getAnomalyScores(), ANOMALY_SENSITIVITY); + } + // CHECKSTYLE:ON: checkstyle:magicNumber + + try { + executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).unlockForWriting(ANOMALY_DETECTION); + } catch (final ApexException e) { + logger.error("Failed to release write lock on \"AnomalyDetection\" context", e); + return new double[0]; + } + + return new double[] {forecastedValue, anomalyScore, anomalyProbability}; + } + + /** + * Is the passed value inside the interval, i.e. (value < interval[1] && value>=interval[0]). + * + * @param value The value to check + * @param interval A 2 element double array describing an interval + * @return true if the value is between interval[0] (inclusive) and interval[1] (exclusive), + * i.e. (value < interval[1] && value>=interval[0]). Otherwise false; + */ + private static boolean checkInterval(final double value, final double[] interval) { + if (interval == null || interval.length != 2) { + throw new IllegalArgumentException("something other than an interval passed to checkInterval"); + } + final double min = interval[0]; + final double max = interval[1]; + return (value < max && value >= min); + } + + /** + * calculate the anomaly probability using statistical test. + * + * @param values the values + * @param significanceLevel the significance level + * @return the anomaly probability + */ + private static double getStatsTest(final List values, final double significanceLevel) { + if (isAllEqual(values)) { + return 0.0; + } + // the targeted value or the last value + final double currentV = values.get(values.size() - 1); + Double[] lvaluesCopy = values.toArray(new Double[values.size()]); + Arrays.sort(lvaluesCopy); // takes ~40% of method time + // get mean + double mean = getMean(lvaluesCopy); + // get the test value: val + double val = getV(lvaluesCopy, mean, true); + // get the p value for the test value + double pvalue = getPValue(lvaluesCopy, val, mean); // takes approx 25% of method time + + // check the critical level + while (pvalue < significanceLevel) { // takes approx 20% of method time + // the score value as the anomaly probability + final double score = (significanceLevel - pvalue) / significanceLevel; + if (Double.compare(val, currentV) == 0) { + return score; + } + // do the critical check again for the left values + lvaluesCopy = removevalue(lvaluesCopy, val); + if (isAllEqual(lvaluesCopy)) { + return 0.0; + } + + mean = getMean(lvaluesCopy); + val = getV(lvaluesCopy, mean, true); + pvalue = getPValue(lvaluesCopy, val, mean); + } + return 0.0; + } + + /** + * Get the test value based on mean from sorted values. + * + * @param lvalues the l values + * @param mean the mean + * @param maxValueOnly : only the max extreme value will be tested + * @return the value to be tested + */ + private static double getV(final Double[] lvalues, final double mean, final boolean maxValueOnly) { + double val = lvalues[lvalues.length - 1]; + // max value as the extreme value + if (maxValueOnly) { + return val; + } + // check the extreme side + if ((val - mean) < (mean - lvalues[0])) { + val = lvalues[0]; + } + return val; + } + + /** + * calculate the P value for the t distribution. + * + * @param lvalues the l values + * @param val the value + * @param mean the mean + * @return the p value + */ + private static double getPValue(final Double[] lvalues, final double val, final double mean) { + // calculate z value + final double z = FastMath.abs(val - mean) / getStdDev(lvalues, mean); + // calculate T + final double n = lvalues.length; + final double s = (z * z * n * (2.0 - n)) / (z * z * n - (n - 1.0) * (n - 1.0)); + final double t = FastMath.sqrt(s); + // default p value = 0 + double pvalue = 0.0; + if (!Double.isNaN(t)) { + // t distribution with n-2 degrees of freedom + final TDistribution tDist = new TDistribution(n - 2); + pvalue = n * (1.0 - tDist.cumulativeProbability(t)); + // set max pvalue = 1 + pvalue = pvalue > 1.0 ? 1.0 : pvalue; + } + return pvalue; + } + + /* + * Some utility methods + */ + // exponential = 2(n+1) + private static final double EMA_EXPONENT = 2.0 / (7.0 + 1.0); + private static final double EMA_EXPONENT_1 = (1.0 - EMA_EXPONENT); + + /** + * exponential moving average. + * + * @param value the value + * @param lastForecast the last forecast + * @return the double + */ + private static double expMovingAverage(final double value, final double lastForecast) { + return (value * EMA_EXPONENT) + (lastForecast * EMA_EXPONENT_1); + } + + /** + * Remove the first occurrence of the value val from the array. + * + * @param lvalues the l values + * @param val the value + * @return the double[] + */ + private static Double[] removevalue(final Double[] lvalues, final double val) { + for (int i = 0; i < lvalues.length; i++) { + if (Double.compare(lvalues[i], val) == 0) { + final Double[] ret = new Double[lvalues.length - 1]; + System.arraycopy(lvalues, 0, ret, 0, i); + System.arraycopy(lvalues, i + 1, ret, i, lvalues.length - i - 1); + return ret; + } + } + return lvalues; + } + + /** + * get mean value of double list. + * + * @param lvalues the l values + * @return the mean + */ + private static double getMean(final Double[] lvalues) { + double sum = 0.0; + for (final double d : lvalues) { + + sum += d; + } + return sum / lvalues.length; + } + + /** + * get standard deviation of double list. + * + * @param lvalues the l values + * @param mean the mean + * @return stddev + */ + private static double getStdDev(final Double[] lvalues, final double mean) { + double temp = 0.0; + for (final double d : lvalues) { + temp += (mean - d) * (mean - d); + } + return FastMath.sqrt(temp / lvalues.length); + } + + /** + * Chop head off list to make it length max . + * + * @param list the list to chop + * @param max the max size + */ + private static void listSizeControl(final List list, final int max) { + final int k = list.size(); + if (k > max) { + // Chop the head off the list. + list.subList(0, k - max).clear(); + } + } + + /** + * return true if all values are equal. + * + * @param lvalues the l values + * @return true, if checks if is all equal + */ + private static boolean isAllEqual(final List lvalues) { + final double first = lvalues.get(0); + for (final Double d : lvalues) { + if (Double.compare(d, first) != 0) { + return false; + } + } + return true; + } + + /** + * return true if all values are equal. + * + * @param lvalues the l values + * @return true, if checks if is all equal + */ + private static boolean isAllEqual(final Double[] lvalues) { + final double first = lvalues[0]; + for (final Double d : lvalues) { + if (Double.compare(d, first) != 0) { + return false; + } + } + return true; + } +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java deleted file mode 100644 index 2a654c38e..000000000 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java +++ /dev/null @@ -1,406 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive.model.java; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.math3.distribution.TDistribution; -import org.apache.commons.math3.util.FastMath; -import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; -import org.onap.policy.apex.examples.adaptive.concepts.AnomalyDetection; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.slf4j.Logger; - -/** - * The Class AnomalyDetectionPolicy_Decide_TaskSelectionLogic. - */ -// CHECKSTYLE:OFF: checkstyle:className -public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { - // CHECKSTYLE:ON: checkstyle:className - - private Logger logger; - // configuration - private static final double ANOMALY_SENSITIVITY = 0.05; - private static final int FREQUENCY = 360; - - /** - * A map to hold the Anomaly degree/levels/probabilities required for each task.
- * If there is no task defined for a calculated anomaly-degree, then the default task is - * used.
- * The map use (LinkedHashMap) is an insertion-ordered map, so the first interval matching a - * query is used. - */ - // CHECKSTYLE:OFF: checkstyle:magicNumber - private static final Map TASK_INTERVALS = new LinkedHashMap<>(); - - static { - TASK_INTERVALS.put(new double[] {0.0, 0.1}, null); // null will mean default task - TASK_INTERVALS.put(new double[] {0.25, 0.5}, "AnomalyDetectionDecideTask1"); - TASK_INTERVALS.put(new double[] {0.5, 1.01}, "AnomalyDetectionDecideTask2"); - } - // CHECKSTYLE:ON: checkstyle:magicNumber - - private volatile TaskSelectionExecutionContext executionContext; - - /** - * Gets the task. - * - * @param executor the executor - * @return the task - */ - public boolean getTask(final TaskSelectionExecutionContext executor) { - executionContext = executor; - logger = executionContext.logger; - logger.debug(executor.subject.getId()); - logger.debug(executor.inFields.toString()); - final double now = (Double) (executor.inFields.get("MonitoredValue")); - final Integer iteration = (Integer) (executor.inFields.get("Iteration")); - // get the double[forecastedValue, AnomalyScore, AnomalyProbability] - final double[] vals = this.forecastingAndAnomaly(now); - final double anomalyness = vals[2]; - String task = null; - for (final Map.Entry i : TASK_INTERVALS.entrySet()) { - if (checkInterval(anomalyness, i.getKey())) { - task = i.getValue(); - break; - } - } - if (task == null) { - executionContext.subject.getDefaultTaskKey().copyTo(executionContext.selectedTask); - } else { - executionContext.subject.getTaskKey(task).copyTo(executionContext.selectedTask); - } - if (logger.isDebugEnabled()) { - logger.debug( - "TestAnomalyDetectionTSLPolicy0000DecideStateTaskSelectionLogic.getTask():\t************\t\t\t\t" - + "Iteration:\t" + iteration + "\tValue:\t" + now + "\tForecast:\t" + vals[0] - + "\tAnomalyScore:\t" + vals[1] + "\tAnomalyProbability:\t" + vals[2] + "\tInvoking Task:\t" - + executionContext.selectedTask); - } - return true; - } - - /** - * Anomaly detection and forecast. - * - * @param value The current value - * @return Null if the function can not be executed correctly, otherwise double[forecastedValue, - * AnomalyScore, AnomalyProbability] - */ - public double[] forecastingAndAnomaly(final double value) { - try { - executionContext.getContextAlbum("AnomalyDetectionAlbum").lockForWriting("AnomalyDetection"); - } catch (final ApexException e) { - logger.error("Failed to acquire write lock on \"AnomalyDetection\" context", e); - return null; - } - - // Get the context object - AnomalyDetection anomalyDetection = - (AnomalyDetection) executionContext.getContextAlbum("AnomalyDetectionAlbum").get("AnomalyDetection"); - if (anomalyDetection == null) { - anomalyDetection = new AnomalyDetection(); - executionContext.getContextAlbum("AnomalyDetectionAlbum").put("AnomalyDetection", anomalyDetection); - } - - // Check the lists are initialized - if (!anomalyDetection.isInitialized()) { - anomalyDetection.init(FREQUENCY); - } - - boolean unsetfirstround = false; - - int frequency = anomalyDetection.getFrequency(); - frequency = frequency + 1; - - // reset frequency counter - if (frequency >= FREQUENCY) { - unsetfirstround = true; - frequency = 0; - } - anomalyDetection.setFrequency(frequency); - - if (unsetfirstround && anomalyDetection.getFirstRound()) { - anomalyDetection.setFirstRound(false); - } - - // --------- calculate the forecasted value - simple version - final Double lastForecast = anomalyDetection.getFrequencyForecasted().get(frequency); - - // get forecast for current value - final double forecastedValue = lastForecast == null ? value : expMovingAverage(value, lastForecast); - - // --------- calculate the anomalyScore - final double anomalyScore = lastForecast == null ? 0.0 : FastMath.abs(lastForecast - value); - - anomalyDetection.getFrequencyForecasted().set(frequency, forecastedValue); - - // anomaly score is ignored in the first frequency period - if (!anomalyDetection.getFirstRound()) { - ((LinkedList) anomalyDetection.getAnomalyScores()).addLast(anomalyScore); - } - - // CHECKSTYLE:OFF: checkstyle:magicNumber - // max FREQUENCY*4 anomaly scores history - listSizeControl(anomalyDetection.getAnomalyScores(), FREQUENCY * 4); - - // ---------- calculate the anomaly probability - double anomalyProbability = 0.0; - if (anomalyDetection.getAnomalyScores().size() > 30) { - // 0.5 - anomalyProbability = getStatsTest(anomalyDetection.getAnomalyScores(), ANOMALY_SENSITIVITY); - } - // CHECKSTYLE:ON: checkstyle:magicNumber - - try { - executionContext.getContextAlbum("AnomalyDetectionAlbum").unlockForWriting("AnomalyDetection"); - } catch (final ApexException e) { - logger.error("Failed to release write lock on \"AnomalyDetection\" context", e); - return null; - } - - return new double[] {forecastedValue, anomalyScore, anomalyProbability}; - } - - /** - * Is the passed value inside the interval, i.e. (value < interval[1] && value>=interval[0]). - * - * @param value The value to check - * @param interval A 2 element double array describing an interval - * @return true if the value is between interval[0] (inclusive) and interval[1] (exclusive), - * i.e. (value < interval[1] && value>=interval[0]). Otherwise false; - */ - private static boolean checkInterval(final double value, final double[] interval) { - if (interval == null || interval.length != 2) { - throw new IllegalArgumentException("something other than an interval passed to checkInterval"); - } - final double min = interval[0]; - final double max = interval[1]; - return (value < max && value >= min); - } - - /** - * calculate the anomaly probability using statistical test. - * - * @param values the values - * @param significanceLevel the significance level - * @return the anomaly probability - */ - private static double getStatsTest(final List values, final double significanceLevel) { - if (isAllEqual(values)) { - return 0.0; - } - // the targeted value or the last value - final double currentV = values.get(values.size() - 1); - Double[] lvaluesCopy = values.toArray(new Double[values.size()]); - Arrays.sort(lvaluesCopy); // takes ~40% of method time - // get mean - double mean = getMean(lvaluesCopy); - // get the test value: val - double val = getV(lvaluesCopy, mean, true); - // get the p value for the test value - double pvalue = getPValue(lvaluesCopy, val, mean); // takes approx 25% of method time - - // check the critical level - while (pvalue < significanceLevel) { // takes approx 20% of method time - // the score value as the anomaly probability - final double score = (significanceLevel - pvalue) / significanceLevel; - if (Double.compare(val, currentV) == 0) { - return score; - } - // do the critical check again for the left values - lvaluesCopy = removevalue(lvaluesCopy, val); - if (isAllEqual(lvaluesCopy)) { - return 0.0; - } - - mean = getMean(lvaluesCopy); - val = getV(lvaluesCopy, mean, true); - pvalue = getPValue(lvaluesCopy, val, mean); - } - return 0.0; - } - - /** - * Get the test value based on mean from sorted values. - * - * @param lvalues the l values - * @param mean the mean - * @param maxValueOnly : only the max extreme value will be tested - * @return the value to be tested - */ - private static double getV(final Double[] lvalues, final double mean, final boolean maxValueOnly) { - double val = lvalues[lvalues.length - 1]; - // max value as the extreme value - if (maxValueOnly) { - return val; - } - // check the extreme side - if ((val - mean) < (mean - lvalues[0])) { - val = lvalues[0]; - } - return val; - } - - /** - * calculate the P value for the t distribution. - * - * @param lvalues the l values - * @param val the value - * @param mean the mean - * @return the p value - */ - private static double getPValue(final Double[] lvalues, final double val, final double mean) { - // calculate z value - final double z = FastMath.abs(val - mean) / getStdDev(lvalues, mean); - // calculate T - final double n = lvalues.length; - final double s = (z * z * n * (2.0 - n)) / (z * z * n - (n - 1.0) * (n - 1.0)); - final double t = FastMath.sqrt(s); - // default p value = 0 - double pvalue = 0.0; - if (!Double.isNaN(t)) { - // t distribution with n-2 degrees of freedom - final TDistribution tDist = new TDistribution(n - 2); - pvalue = n * (1.0 - tDist.cumulativeProbability(t)); - // set max pvalue = 1 - pvalue = pvalue > 1.0 ? 1.0 : pvalue; - } - return pvalue; - } - - /* - * Some utility methods - */ - // exponential = 2(n+1) - private static final double EMA_EXPONENT = 2.0 / (7.0 + 1.0); - private static final double EMA_EXPONENT_1 = (1.0 - EMA_EXPONENT); - - /** - * exponential moving average. - * - * @param value the value - * @param lastForecast the last forecast - * @return the double - */ - private static double expMovingAverage(final double value, final double lastForecast) { - return (value * EMA_EXPONENT) + (lastForecast * EMA_EXPONENT_1); - } - - /** - * Remove the first occurrence of the value val from the array. - * - * @param lvalues the l values - * @param val the value - * @return the double[] - */ - private static Double[] removevalue(final Double[] lvalues, final double val) { - for (int i = 0; i < lvalues.length; i++) { - if (Double.compare(lvalues[i], val) == 0) { - final Double[] ret = new Double[lvalues.length - 1]; - System.arraycopy(lvalues, 0, ret, 0, i); - System.arraycopy(lvalues, i + 1, ret, i, lvalues.length - i - 1); - return ret; - } - } - return lvalues; - } - - /** - * get mean value of double list. - * - * @param lvalues the l values - * @return the mean - */ - private static double getMean(final Double[] lvalues) { - double sum = 0.0; - for (final double d : lvalues) { - - sum += d; - } - return sum / lvalues.length; - } - - /** - * get standard deviation of double list. - * - * @param lvalues the l values - * @param mean the mean - * @return stddev - */ - private static double getStdDev(final Double[] lvalues, final double mean) { - double temp = 0.0; - for (final double d : lvalues) { - temp += (mean - d) * (mean - d); - } - return FastMath.sqrt(temp / lvalues.length); - } - - /** - * Chop head off list to make it length max . - * - * @param list the list to chop - * @param max the max size - */ - private static void listSizeControl(final List list, final int max) { - final int k = list.size(); - if (k > max) { - // Chop the head off the list. - list.subList(0, k - max).clear(); - } - } - - /** - * return true if all values are equal. - * - * @param lvalues the l values - * @return true, if checks if is all equal - */ - private static boolean isAllEqual(final List lvalues) { - final double first = lvalues.get(0); - for (final Double d : lvalues) { - if (Double.compare(d, first) != 0) { - return false; - } - } - return true; - } - - /** - * return true if all values are equal. - * - * @param lvalues the l values - * @return true, if checks if is all equal - */ - private static boolean isAllEqual(final Double[] lvalues) { - final double first = lvalues[0]; - for (final Double d : lvalues) { - if (Double.compare(d, first) != 0) { - return false; - } - } - return true; - } -} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java new file mode 100644 index 000000000..d60b04c00 --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.model.java; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.onap.policy.apex.context.ContextException; +import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; +import org.onap.policy.apex.examples.adaptive.concepts.AutoLearn; + +/** + * The Class AutoLearnPolicyDecideTaskSelectionLogic. + */ +public class AutoLearnPolicyDecideTaskSelectionLogic { + // Recurring string constants + private static final String AUTO_LEARN_ALBUM = "AutoLearnAlbum"; + private static final String AUTO_LEARN = "AutoLearn"; + + private static final Random RAND = new Random(System.currentTimeMillis()); + private static final double WANT = 50.0; + private int size; + + /** + * Gets the task. + * + * @param executor the executor + * @return the task + */ + public boolean getTask(final TaskSelectionExecutionContext executor) { + String idString = executor.subject.getId(); + executor.logger.debug(idString); + + String inFieldsString = executor.inFields.toString(); + executor.logger.debug(inFieldsString); + + final List tasks = executor.subject.getTaskNames(); + size = tasks.size(); + + try { + executor.getContextAlbum(AUTO_LEARN_ALBUM).lockForWriting(AUTO_LEARN); + } catch (final ContextException e) { + executor.logger.error("Failed to acquire write lock on \"autoLearn\" context", e); + return false; + } + + // Get the context object + AutoLearn autoLearn = (AutoLearn) executor.getContextAlbum(AUTO_LEARN_ALBUM).get(AUTO_LEARN); + if (autoLearn == null) { + autoLearn = new AutoLearn(); + } + + // Check the lists are initialized + if (!autoLearn.isInitialized()) { + autoLearn.init(size); + } + + final double now = (Double) (executor.inFields.get("MonitoredValue")); + final double diff = now - WANT; + final int option = getOption(diff, autoLearn); + learn(option, diff, autoLearn); + + executor.getContextAlbum(AUTO_LEARN_ALBUM).put(AUTO_LEARN_ALBUM, autoLearn); + + try { + executor.getContextAlbum(AUTO_LEARN_ALBUM).unlockForWriting(AUTO_LEARN); + } catch (final ContextException e) { + executor.logger.error("Failed to acquire write lock on \"autoLearn\" context", e); + return false; + } + + executor.subject.getTaskKey(tasks.get(option)).copyTo(executor.selectedTask); + return true; + } + + /** + * Gets the option. + * + * @param diff the diff + * @param autoLearn the auto learn + * @return the option + */ + private int getOption(final double diff, final AutoLearn autoLearn) { + final Double[] avdiffs = autoLearn.getAvDiffs().toArray(new Double[autoLearn.getAvDiffs().size()]); + final int r = RAND.nextInt(size); + int closestupi = -1; + int closestdowni = -1; + double closestup = Double.MAX_VALUE; + double closestdown = Double.MIN_VALUE; + for (int i = 0; i < size; i++) { + if (Double.isNaN(avdiffs[i])) { + return r; + } + if (avdiffs[i] >= diff && avdiffs[i] <= closestup) { + closestup = avdiffs[i]; + closestupi = i; + } + if (avdiffs[i] <= diff && avdiffs[i] >= closestdown) { + closestdown = avdiffs[i]; + closestdowni = i; + } + } + if (closestupi == -1 || closestdowni == -1) { + return r; + } + if (closestupi == closestdowni) { + return closestupi; + } + if (Math.abs(closestdown - diff) > Math.abs(closestup - diff)) { + return closestupi; + } else { + return closestdowni; + } + } + + /** + * Learn. + * + * @param option the option + * @param diff the diff + * @param autoLearn the auto learn + */ + private void learn(final int option, final double diff, final AutoLearn autoLearn) { + final Double[] avdiffs = autoLearn.getAvDiffs().toArray(new Double[autoLearn.getAvDiffs().size()]); + final Long[] counts = autoLearn.getCounts().toArray(new Long[autoLearn.getCounts().size()]); + if (option < 0 || option >= avdiffs.length) { + throw new IllegalArgumentException("Error: option" + option); + } + counts[option]++; + if (Double.isNaN(avdiffs[option])) { + avdiffs[option] = diff; + } else { + avdiffs[option] = (avdiffs[option] * (counts[option] - 1) + diff) / counts[option]; + } + autoLearn.setAvDiffs(Arrays.asList(avdiffs)); + autoLearn.setCounts(Arrays.asList(counts)); + } +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicy_Decide_TaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicy_Decide_TaskSelectionLogic.java deleted file mode 100644 index 23d4e2486..000000000 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicy_Decide_TaskSelectionLogic.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive.model.java; - -import java.util.Arrays; -import java.util.List; -import java.util.Random; - -import org.onap.policy.apex.context.ContextException; -import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; -import org.onap.policy.apex.examples.adaptive.concepts.AutoLearn; - -/** - * The Class AutoLearnPolicy_Decide_TaskSelectionLogic. - */ -// CHECKSTYLE:OFF: checkstyle:typeName -public class AutoLearnPolicy_Decide_TaskSelectionLogic { - // CHECKSTYLE:ON: checkstyle:typeName - private static final Random RAND = new Random(System.currentTimeMillis()); - private static final double WANT = 50.0; - private int size; - - /** - * Gets the task. - * - * @param executor the executor - * @return the task - */ - public boolean getTask(final TaskSelectionExecutionContext executor) { - executor.logger.debug(executor.subject.getId()); - executor.logger.debug(executor.inFields.toString()); - final List tasks = executor.subject.getTaskNames(); - size = tasks.size(); - - try { - executor.getContextAlbum("AutoLearnAlbum").lockForWriting("AutoLearn"); - } catch (final ContextException e) { - executor.logger.error("Failed to acquire write lock on \"autoLearn\" context", e); - return false; - } - - // Get the context object - AutoLearn autoLearn = (AutoLearn) executor.getContextAlbum("AutoLearnAlbum").get("AutoLearn"); - if (autoLearn == null) { - autoLearn = new AutoLearn(); - } - - // Check the lists are initialized - if (!autoLearn.isInitialized()) { - autoLearn.init(size); - } - - final double now = (Double) (executor.inFields.get("MonitoredValue")); - final double diff = now - WANT; - final int option = getOption(diff, autoLearn); - learn(option, diff, autoLearn); - - executor.getContextAlbum("AutoLearnAlbum").put("AutoLearnAlbum", autoLearn); - - try { - executor.getContextAlbum("AutoLearnAlbum").unlockForWriting("AutoLearn"); - } catch (final ContextException e) { - executor.logger.error("Failed to acquire write lock on \"autoLearn\" context", e); - return false; - } - - executor.subject.getTaskKey(tasks.get(option)).copyTo(executor.selectedTask); - return true; - } - - /** - * Gets the option. - * - * @param diff the diff - * @param autoLearn the auto learn - * @return the option - */ - private int getOption(final double diff, final AutoLearn autoLearn) { - final Double[] avdiffs = autoLearn.getAvDiffs().toArray(new Double[autoLearn.getAvDiffs().size()]); - final int r = RAND.nextInt(size); - int closestupi = -1; - int closestdowni = -1; - double closestup = Double.MAX_VALUE; - double closestdown = Double.MIN_VALUE; - for (int i = 0; i < size; i++) { - if (Double.isNaN(avdiffs[i])) { - return r; - } - if (avdiffs[i] >= diff && avdiffs[i] <= closestup) { - closestup = avdiffs[i]; - closestupi = i; - } - if (avdiffs[i] <= diff && avdiffs[i] >= closestdown) { - closestdown = avdiffs[i]; - closestdowni = i; - } - } - if (closestupi == -1 || closestdowni == -1) { - return r; - } - if (closestupi == closestdowni) { - return closestupi; - } - if (Math.abs(closestdown - diff) > Math.abs(closestup - diff)) { - return closestupi; - } else { - return closestdowni; - } - } - - /** - * Learn. - * - * @param option the option - * @param diff the diff - * @param autoLearn the auto learn - */ - private void learn(final int option, final double diff, final AutoLearn autoLearn) { - final Double[] avdiffs = autoLearn.getAvDiffs().toArray(new Double[autoLearn.getAvDiffs().size()]); - final Long[] counts = autoLearn.getCounts().toArray(new Long[autoLearn.getCounts().size()]); - if (option < 0 || option >= avdiffs.length) { - throw new IllegalArgumentException("Error: option" + option); - } - counts[option]++; - if (Double.isNaN(avdiffs[option])) { - avdiffs[option] = diff; - } else { - avdiffs[option] = (avdiffs[option] * (counts[option] - 1) + diff) / counts[option]; - } - autoLearn.setAvDiffs(Arrays.asList(avdiffs)); - autoLearn.setCounts(Arrays.asList(counts)); - } -} diff --git a/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask0TaskLogic.mvel b/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask0TaskLogic.mvel new file mode 100644 index 000000000..758062b8e --- /dev/null +++ b/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask0TaskLogic.mvel @@ -0,0 +1,40 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug("AutoLearnDecideTask0: inFields:" + inFields); +java.util.Random rand = new java.util.Random(System.currentTimeMillis()); +double MIN = -100.0; +double MAX = 100.0; +double WANT = 50.0; + +double inval = (Double)(inFields["MonitoredValue"]); +double ret = inval; +/////////////// +double diff = (1.0/2.0) * (Math.abs(inval - WANT)); +/////////////// +ret = inval + diff; +if (ret > MAX) + ret = MAX; +if (ret MAX) - ret = MAX; -if (ret MAX) + ret = MAX; +if (ret MAX) - ret = MAX; -if (ret MAX) + ret = MAX; +if (ret MAX) - ret = MAX; -if (ret MAX) + ret = MAX; +if (ret MAX) - ret = MAX; -if (ret MAX) + ret = MAX; +if (ret MAX) - ret = MAX; -if (ret MAX) + ret = MAX; +if (ret < MIN) + ret = MIN; + +outFields["MonitoredValue"] = ret; +outFields["LastMonitoredValue"] = inval; +logger.debug("AutoLearnDecideTask5: outFields:" + outFields); +return true; diff --git a/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask5_TaskLogic.mvel b/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask5_TaskLogic.mvel deleted file mode 100644 index fc2005fdf..000000000 --- a/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask5_TaskLogic.mvel +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -logger.debug("AutoLearnDecideTask5: inFields:" + inFields); -java.util.Random rand = new java.util.Random(System.currentTimeMillis()); -double MIN = -100.0; -double MAX = 100.0; -double WANT = 50.0; - -double inval = (Double)(inFields["MonitoredValue"]); -double ret = inval; -/////////////// -double diff = (-1.0/5.0) * (Math.abs(inval - WANT)); -/////////////// -ret = inval + diff; -if (ret > MAX) - ret = MAX; -if (ret < MIN) - ret = MIN; - -outFields["MonitoredValue"] = ret; -outFields["LastMonitoredValue"] = inval; -logger.debug("AutoLearnDecideTask5: outFields:" + outFields); -return true; diff --git a/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask6TaskLogic.mvel b/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask6TaskLogic.mvel new file mode 100644 index 000000000..5eb44839c --- /dev/null +++ b/examples/examples-adaptive/src/main/resources/org/onap/policy/apex/examples/adaptive/model/mvel/AutoLearnDecideTask6TaskLogic.mvel @@ -0,0 +1,40 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +logger.debug("AutoLearnDecideTask6: inFields:" + inFields); +java.util.Random rand = new java.util.Random(System.currentTimeMillis()); +double MIN = -100.0; +double MAX = 100.0; +double WANT = 50.0; + +double inval = (Double)(inFields["MonitoredValue"]); +double ret = inval; +/////////////// +double diff = (-1.0/2.0) * (Math.abs(inval - WANT)); +/////////////// +ret = inval + diff; +if (ret > MAX) + ret = MAX; +if (ret MAX) - ret = MAX; -if (ret pcvsModelSaver = - new ApexModelSaver<>(AxPolicyModel.class, pcvsPolicyModel, args[1] + "vpnsla/"); + final ApexModelSaver pcvsModelSaver = new ApexModelSaver<>(AxPolicyModel.class, pcvsPolicyModel, + args[1] + "vpnsla/"); pcvsModelSaver.apexModelWriteJson(); pcvsModelSaver.apexModelWriteXml(); diff --git a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/handling/PolicyLogicReader.java b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/handling/PolicyLogicReader.java index aa57be552..a40a8100f 100644 --- a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/handling/PolicyLogicReader.java +++ b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/handling/PolicyLogicReader.java @@ -107,11 +107,11 @@ public class PolicyLogicReader implements AxLogicReader { } else { // Return the java class name for the logic if (axLogic.getKey().getParentLocalName().equals(AxKey.NULL_KEY_NAME)) { - return logicPackage + DOT_JAVA + axLogic.getKey().getParentKeyName() + '_' + return logicPackage + DOT_JAVA + axLogic.getKey().getParentKeyName() + axLogic.getKey().getLocalName(); } else { - return logicPackage + DOT_JAVA + axLogic.getKey().getParentKeyName() + '_' - + axLogic.getKey().getParentLocalName() + '_' + axLogic.getKey().getLocalName(); + return logicPackage + DOT_JAVA + axLogic.getKey().getParentKeyName() + + axLogic.getKey().getParentLocalName() + axLogic.getKey().getLocalName(); } } } @@ -129,10 +129,10 @@ public class PolicyLogicReader implements AxLogicReader { fullLogicFilePath += "/" + defaultLogic; } else { if (axLogic.getKey().getParentLocalName().equals(AxKey.NULL_KEY_NAME)) { - fullLogicFilePath += "/" + axLogic.getKey().getParentKeyName() + "_" + axLogic.getKey().getLocalName(); + fullLogicFilePath += "/" + axLogic.getKey().getParentKeyName() + axLogic.getKey().getLocalName(); } else { - fullLogicFilePath += "/" + axLogic.getKey().getParentKeyName() + "_" - + axLogic.getKey().getParentLocalName() + "_" + axLogic.getKey().getLocalName(); + fullLogicFilePath += "/" + axLogic.getKey().getParentKeyName() + + axLogic.getKey().getParentLocalName() + axLogic.getKey().getLocalName(); } } diff --git a/model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/TestPolicyLogicReader.java b/model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/TestPolicyLogicReader.java index bb16c90d1..528898d30 100644 --- a/model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/TestPolicyLogicReader.java +++ b/model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/TestPolicyLogicReader.java @@ -63,7 +63,7 @@ public class TestPolicyLogicReader { fail("test should throw an exception here"); } catch (final Exception e) { assertEquals("logic not found for logic " - + "\"somewhere/over/the/rainbow/funkylogic/LogicParent_LogicInstanceName.funkylogic\"", + + "\"somewhere/over/the/rainbow/funkylogic/LogicParentLogicInstanceName.funkylogic\"", e.getMessage()); } @@ -73,7 +73,7 @@ public class TestPolicyLogicReader { fail("test should throw an exception here"); } catch (final Exception e) { assertEquals("logic not found for logic " + "\"somewhere/over/the/rainbow/funkylogic/" - + "LogicParent_LogicParentLocalName_LogicInstanceName.funkylogic\"", e.getMessage()); + + "LogicParentLogicParentLocalNameLogicInstanceName.funkylogic\"", e.getMessage()); } plReader.setLogicPackage("path.to.apex.logic"); @@ -97,7 +97,7 @@ public class TestPolicyLogicReader { plReader.setDefaultLogic(null); try { final AxLogic logic = new AxLogic(logicKey, "JAVA", plReader); - assertEquals("somewhere.over.the.rainbow.java.LogicParent_LogicParentLocalName_LogicInstanceName", + assertEquals("somewhere.over.the.rainbow.java.LogicParentLogicParentLocalNameLogicInstanceName", logic.getLogic()); } catch (final Exception e) { fail("test should not throw an exception"); @@ -106,7 +106,7 @@ public class TestPolicyLogicReader { logicKey.setParentLocalName(AxKey.NULL_KEY_NAME); try { final AxLogic logic = new AxLogic(logicKey, "JAVA", plReader); - assertEquals("somewhere.over.the.rainbow.java.LogicParent_LogicInstanceName", logic.getLogic()); + assertEquals("somewhere.over.the.rainbow.java.LogicParentLogicInstanceName", logic.getLogic()); } catch (final Exception e) { fail("test should not throw an exception"); } diff --git a/model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParentLogicParentLocalNameLogicInstanceName.funkylogic b/model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParentLogicParentLocalNameLogicInstanceName.funkylogic new file mode 100644 index 000000000..7ccf3da88 --- /dev/null +++ b/model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParentLogicParentLocalNameLogicInstanceName.funkylogic @@ -0,0 +1,21 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +Way out man, this is funky logic! \ No newline at end of file diff --git a/model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParent_LogicParentLocalName_LogicInstanceName.funkylogic b/model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParent_LogicParentLocalName_LogicInstanceName.funkylogic deleted file mode 100644 index 7ccf3da88..000000000 --- a/model/policy-model/src/test/resources/path/to/apex/logic/funkylogic/LogicParent_LogicParentLocalName_LogicInstanceName.funkylogic +++ /dev/null @@ -1,21 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -Way out man, this is funky logic! \ No newline at end of file diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerEndpoint.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerEndpoint.java index f8524fcfd..ca2d797b9 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerEndpoint.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerEndpoint.java @@ -43,8 +43,10 @@ import org.slf4j.LoggerFactory; * @author Liam Fallon (liam.fallon@ericsson.com) */ @Path("/{eventInput}") -@Produces({ MediaType.APPLICATION_JSON }) -@Consumes({ MediaType.APPLICATION_JSON }) +@Produces( + { MediaType.APPLICATION_JSON }) +@Consumes( + { MediaType.APPLICATION_JSON }) public class RestServerEndpoint { // Get a reference to the logger private static final Logger LOGGER = LoggerFactory.getLogger(RestServerEndpoint.class); @@ -56,8 +58,7 @@ public class RestServerEndpoint { // This map is used to hold all the REST server event inputs. This is used to determine which consumer to send input // events to - private static Map consumerMap = - new LinkedHashMap<>(); + private static Map consumerMap = new LinkedHashMap<>(); // The ID of this event input. This gets injected from the URL. @PathParam("eventInput") @@ -70,7 +71,7 @@ public class RestServerEndpoint { * @param consumer The consumer to register */ public static void registerApexRestServerConsumer(final String consumerEventInputId, - final ApexRestServerConsumer consumer) { + final ApexRestServerConsumer consumer) { consumerMap.put(consumerEventInputId, consumer); } @@ -82,12 +83,12 @@ public class RestServerEndpoint { @Path("/Status") @GET public Response serviceGetStats() { - getMessagesReceived++; + incrementGetMessages(); return Response.status(Response.Status.OK.getStatusCode()) - .entity("{\n" + "\"INPUTS\": \"" + consumerMap.keySet() + "\",\n" + "\"STAT\": " + getMessagesReceived - + ",\n" + "\"POST\": " + postEventMessagesReceived + ",\n" + "\"PUT\": " - + putEventMessagesReceived + "\n}") - .build(); + .entity("{\n" + "\"INPUTS\": \"" + consumerMap.keySet() + "\",\n" + "\"STAT\": " + + getMessagesReceived + ",\n" + "\"POST\": " + postEventMessagesReceived + ",\n" + + "\"PUT\": " + putEventMessagesReceived + "\n}") + .build(); } /** @@ -99,7 +100,7 @@ public class RestServerEndpoint { @Path("/EventIn") @POST public Response servicePostRequest(final String jsonString) { - postEventMessagesReceived++; + incrementPostEventMessages(); if (LOGGER.isDebugEnabled()) { String message = "event input " + eventInputId + ", received POST of event \"" + jsonString + "\""; @@ -119,7 +120,7 @@ public class RestServerEndpoint { @Path("/EventIn") @PUT public Response servicePutRequest(final String jsonString) { - putEventMessagesReceived++; + incrementPutEventMessages(); if (LOGGER.isDebugEnabled()) { String message = "event input \"" + eventInputId + "\", received PUT of event \"" + jsonString + "\""; @@ -140,13 +141,34 @@ public class RestServerEndpoint { // Find the correct consumer for this REST message final ApexRestServerConsumer eventConsumer = consumerMap.get(eventInputId); if (eventConsumer == null) { - final String errorMessage = - "event input " + eventInputId + " is not defined in the Apex configuration file"; + final String errorMessage = "event input " + eventInputId + + " is not defined in the Apex configuration file"; LOGGER.warn(errorMessage); return Response.status(Response.Status.BAD_REQUEST.getStatusCode()) - .entity("{'errorMessage', '" + errorMessage + "'}").build(); + .entity("{'errorMessage', '" + errorMessage + "'}").build(); } return eventConsumer.receiveEvent(jsonString); } + + /** + * Increment number of get messages received. + */ + private static void incrementGetMessages() { + getMessagesReceived++; + } + + /** + * Increment number of get messages received. + */ + private static void incrementPutEventMessages() { + putEventMessagesReceived++; + } + + /** + * Increment number of get messages received. + */ + private static void incrementPostEventMessages() { + postEventMessagesReceived++; + } } diff --git a/testsuites/integration/integration-common/pom.xml b/testsuites/integration/integration-common/pom.xml index 7cb679815..8c2e39086 100644 --- a/testsuites/integration/integration-common/pom.xml +++ b/testsuites/integration/integration-common/pom.xml @@ -88,7 +88,7 @@ -classpath - org.onap.policy.apex.test.common.model.SampleDomainModelSaver + org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelSaver ${project.build.directory}/classes/examples/models/SampleDomain diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/EvalDomainModelFactory.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/EvalDomainModelFactory.java deleted file mode 100644 index a3f626f48..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/EvalDomainModelFactory.java +++ /dev/null @@ -1,501 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.test.common.model; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; -import org.onap.policy.apex.model.eventmodel.concepts.AxField; -import org.onap.policy.apex.model.policymodel.concepts.AxLogicReader; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicies; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.model.policymodel.concepts.AxState; -import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput; -import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskOutputType; -import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference; -import org.onap.policy.apex.model.policymodel.concepts.AxTask; -import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic; -import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic; -import org.onap.policy.apex.model.policymodel.concepts.AxTasks; -import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; - -/** - * This class creates sample evaluation Policy Models. - * - * @author John Keeney (john.keeney@ericsson.com) - */ -public class EvalDomainModelFactory { - private static final int THIRD_MEMBER = 3; - - private static final String PACKAGE = EvalDomainModelFactory.class.getPackage().getName(); - - private String justOneLang = null; - - private final AxContextSchema typeTimestamp; - private final AxContextSchema typeDouble; - private final AxContextSchema typeCounter; - private final AxContextSchemas schemas; - private final AxEvent event0000; - private final AxEvent event0001; - private final AxEvent event0002; - private final AxEvent event0003; - private final AxEvent event0004; - private final AxEvents events; - - /** - * The Constructor for the factory. - */ - public EvalDomainModelFactory() { - this(null); - } - - /** - * The Constructor for the factory that creates models for a single executor language flavour. - * - * @param justOneLang the just one lang - */ - public EvalDomainModelFactory(final String justOneLang) { - this.justOneLang = justOneLang; - - typeTimestamp = new AxContextSchema(new AxArtifactKey("TestTimestamp", "0.0.1"), "Java", "java.lang.Long"); - typeDouble = new AxContextSchema(new AxArtifactKey("TestTemperature", "0.0.1"), "Java", "java.lang.Double"); - typeCounter = new AxContextSchema(new AxArtifactKey("TestTimestamp", "0.0.1"), "Java", "java.lang.Long"); - - schemas = new AxContextSchemas(new AxArtifactKey("TestDatatypes", "0.0.1")); - schemas.getSchemasMap().put(typeTimestamp.getKey(), typeTimestamp); - schemas.getSchemasMap().put(typeDouble.getKey(), typeDouble); - schemas.getSchemasMap().put(typeCounter.getKey(), typeCounter); - - event0000 = new AxEvent(new AxArtifactKey("Event0000", "0.0.1"), PACKAGE + ".events"); - event0000.getParameterMap().put("SentTimestamp", new AxField(new AxReferenceKey(event0000.getKey(), "SentTimestamp"), typeTimestamp.getKey())); - event0000.getParameterMap().put("TestTemperature", new AxField(new AxReferenceKey(event0000.getKey(), "TestTemperature"), typeDouble.getKey())); - event0000.getParameterMap().put("FirstEventTimestamp", - new AxField(new AxReferenceKey(event0000.getKey(), "FirstEventTimestamp"), typeTimestamp.getKey())); - event0000.getParameterMap().put("EventNumber", new AxField(new AxReferenceKey(event0000.getKey(), "EventNumber"), typeCounter.getKey())); - - event0001 = new AxEvent(new AxArtifactKey("Event0001", "0.0.1"), PACKAGE + ".events"); - event0001.getParameterMap().put("SentTimestamp", new AxField(new AxReferenceKey(event0001.getKey(), "SentTimestamp"), typeTimestamp.getKey())); - event0001.getParameterMap().put("State1Timestamp", new AxField(new AxReferenceKey(event0001.getKey(), "State1Timestamp"), typeTimestamp.getKey())); - event0001.getParameterMap().put("TestTemperature", new AxField(new AxReferenceKey(event0001.getKey(), "TestTemperature"), typeDouble.getKey())); - event0001.getParameterMap().put("FirstEventTimestamp", - new AxField(new AxReferenceKey(event0001.getKey(), "FirstEventTimestamp"), typeTimestamp.getKey())); - event0001.getParameterMap().put("EventNumber", new AxField(new AxReferenceKey(event0001.getKey(), "EventNumber"), typeCounter.getKey())); - - event0002 = new AxEvent(new AxArtifactKey("Event0002", "0.0.1"), PACKAGE + ".events"); - event0002.getParameterMap().put("SentTimestamp", new AxField(new AxReferenceKey(event0002.getKey(), "SentTimestamp"), typeTimestamp.getKey())); - event0002.getParameterMap().put("State1Timestamp", new AxField(new AxReferenceKey(event0002.getKey(), "State1Timestamp"), typeTimestamp.getKey())); - event0002.getParameterMap().put("State2Timestamp", new AxField(new AxReferenceKey(event0002.getKey(), "State2Timestamp"), typeTimestamp.getKey())); - event0002.getParameterMap().put("TestTemperature", new AxField(new AxReferenceKey(event0002.getKey(), "TestTemperature"), typeDouble.getKey())); - event0002.getParameterMap().put("FirstEventTimestamp", - new AxField(new AxReferenceKey(event0002.getKey(), "FirstEventTimestamp"), typeTimestamp.getKey())); - event0002.getParameterMap().put("EventNumber", new AxField(new AxReferenceKey(event0002.getKey(), "EventNumber"), typeCounter.getKey())); - - event0003 = new AxEvent(new AxArtifactKey("Event0003", "0.0.1"), PACKAGE + ".events"); - event0003.getParameterMap().put("SentTimestamp", new AxField(new AxReferenceKey(event0003.getKey(), "SentTimestamp"), typeTimestamp.getKey())); - event0003.getParameterMap().put("State1Timestamp", new AxField(new AxReferenceKey(event0003.getKey(), "State1Timestamp"), typeTimestamp.getKey())); - event0003.getParameterMap().put("State2Timestamp", new AxField(new AxReferenceKey(event0003.getKey(), "State2Timestamp"), typeTimestamp.getKey())); - event0003.getParameterMap().put("State3Timestamp", new AxField(new AxReferenceKey(event0003.getKey(), "State3Timestamp"), typeTimestamp.getKey())); - event0003.getParameterMap().put("TestTemperature", new AxField(new AxReferenceKey(event0003.getKey(), "TestTemperature"), typeDouble.getKey())); - event0003.getParameterMap().put("FirstEventTimestamp", - new AxField(new AxReferenceKey(event0003.getKey(), "FirstEventTimestamp"), typeTimestamp.getKey())); - event0003.getParameterMap().put("EventNumber", new AxField(new AxReferenceKey(event0003.getKey(), "EventNumber"), typeCounter.getKey())); - - event0004 = new AxEvent(new AxArtifactKey("Event0004", "0.0.1"), PACKAGE + ".events"); - event0004.getParameterMap().put("SentTimestamp", new AxField(new AxReferenceKey(event0004.getKey(), "SentTimestamp"), typeTimestamp.getKey())); - event0004.getParameterMap().put("State1Timestamp", new AxField(new AxReferenceKey(event0004.getKey(), "State1Timestamp"), typeTimestamp.getKey())); - event0004.getParameterMap().put("State2Timestamp", new AxField(new AxReferenceKey(event0004.getKey(), "State2Timestamp"), typeTimestamp.getKey())); - event0004.getParameterMap().put("State3Timestamp", new AxField(new AxReferenceKey(event0004.getKey(), "State3Timestamp"), typeTimestamp.getKey())); - event0004.getParameterMap().put("State4Timestamp", new AxField(new AxReferenceKey(event0004.getKey(), "State4Timestamp"), typeTimestamp.getKey())); - event0004.getParameterMap().put("TestTemperature", new AxField(new AxReferenceKey(event0004.getKey(), "TestTemperature"), typeDouble.getKey())); - event0004.getParameterMap().put("FirstEventTimestamp", - new AxField(new AxReferenceKey(event0004.getKey(), "FirstEventTimestamp"), typeTimestamp.getKey())); - event0004.getParameterMap().put("EventNumber", new AxField(new AxReferenceKey(event0004.getKey(), "EventNumber"), typeCounter.getKey())); - - events = new AxEvents(new AxArtifactKey("Events", "0.0.1")); - events.getEventMap().put(event0000.getKey(), event0000); - events.getEventMap().put(event0001.getKey(), event0001); - events.getEventMap().put(event0002.getKey(), event0002); - events.getEventMap().put(event0003.getKey(), event0003); - events.getEventMap().put(event0004.getKey(), event0004); - } - - /** - * Get a sample OODA policy model. - * - * @return the sample policy model - */ - public AxPolicyModel getOODAPolicyModel() { - final AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", "0.0.1")); - - final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE).setDefaultLogic("EvalTask_Logic"); - - final AxTask obTask = new AxTask(new AxArtifactKey("Task_Observe_0", "0.0.1")); - obTask.duplicateInputFields(event0000.getParameterMap()); - obTask.duplicateOutputFields(event0001.getParameterMap()); - final AxTaskLogic obAxLogic = new AxTaskLogic(obTask.getKey(), "TaskLogic", (justOneLang == null ? "JRUBY" : justOneLang), logicReader); - obAxLogic.setLogic(obAxLogic.getLogic().replaceAll("", "Observe").replaceAll("", obTask.getKey().getName()) - .replaceAll("", "1")); - obTask.setTaskLogic(obAxLogic); - - final AxTask orTask = new AxTask(new AxArtifactKey("Task_Orient_0", "0.0.1")); - orTask.duplicateInputFields(event0001.getParameterMap()); - orTask.duplicateOutputFields(event0002.getParameterMap()); - final AxTaskLogic orAxLogic = new AxTaskLogic(orTask.getKey(), "TaskLogic", (justOneLang == null ? "JAVASCRIPT" : justOneLang), logicReader); - orAxLogic.setLogic(orAxLogic.getLogic().replaceAll("", "Orient").replaceAll("", orTask.getKey().getName()) - .replaceAll("", "2")); - orTask.setTaskLogic(orAxLogic); - - final AxTask dTask = new AxTask(new AxArtifactKey("Task_Decide_0", "0.0.1")); - dTask.duplicateInputFields(event0002.getParameterMap()); - dTask.duplicateOutputFields(event0003.getParameterMap()); - final AxTaskLogic dAxLogic = new AxTaskLogic(dTask.getKey(), "TaskLogic", (justOneLang == null ? "MVEL" : justOneLang), logicReader); - dAxLogic.setLogic( - dAxLogic.getLogic().replaceAll("", "Orient").replaceAll("", dTask.getKey().getName()).replaceAll("", "3")); - dTask.setTaskLogic(dAxLogic); - - final AxTask aTask = new AxTask(new AxArtifactKey("Task_Act_0", "0.0.1")); - aTask.duplicateInputFields(event0003.getParameterMap()); - aTask.duplicateOutputFields(event0004.getParameterMap()); - final AxTaskLogic aAxLogic = new AxTaskLogic(aTask.getKey(), "TaskLogic", (justOneLang == null ? "JAVA" : justOneLang), logicReader); - aAxLogic.setLogic( - aAxLogic.getLogic().replaceAll("", "Act").replaceAll("", aTask.getKey().getName()).replaceAll("", "4")); - aTask.setTaskLogic(aAxLogic); - - tasks.getTaskMap().put(obTask.getKey(), obTask); - tasks.getTaskMap().put(orTask.getKey(), orTask); - tasks.getTaskMap().put(dTask.getKey(), dTask); - tasks.getTaskMap().put(aTask.getKey(), aTask); - - final Set obTasks = new TreeSet<>(); - final Set orTasks = new TreeSet<>(); - final Set decTasks = new TreeSet<>(); - final Set actTasks = new TreeSet<>(); - - for (final AxTask task : tasks.getTaskMap().values()) { - if (task.getKey().getName().contains("Observe")) { - obTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Orient")) { - orTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Decide")) { - decTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Act")) { - actTasks.add(task.getKey()); - } - } - final List> taskReferenceList = new ArrayList<>(); - taskReferenceList.add(obTasks); - taskReferenceList.add(orTasks); - taskReferenceList.add(decTasks); - taskReferenceList.add(actTasks); - - final List p0InEventList = new ArrayList<>(); - p0InEventList.add(event0000.getKey()); - p0InEventList.add(event0001.getKey()); - p0InEventList.add(event0002.getKey()); - p0InEventList.add(event0003.getKey()); - - final List p0OutEventList = new ArrayList<>(); - p0OutEventList.add(event0001.getKey()); - p0OutEventList.add(event0002.getKey()); - p0OutEventList.add(event0003.getKey()); - p0OutEventList.add(event0004.getKey()); - - final List p0defaultTaskList = new ArrayList<>(); - p0defaultTaskList.add(tasks.get("Task_Observe_0").getKey()); - p0defaultTaskList.add(tasks.get("Task_Orient_0").getKey()); - p0defaultTaskList.add(tasks.get("Task_Decide_0").getKey()); - p0defaultTaskList.add(tasks.get("Task_Act_0").getKey()); - - final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("OODAPolicy_0", "0.0.1")); - final List axLogicExecutorTypeList = Arrays.asList((justOneLang == null ? "JAVASCRIPT" : justOneLang), - (justOneLang == null ? "MVEL" : justOneLang), (justOneLang == null ? "JYTHON" : justOneLang), (justOneLang == null ? "JRUBY" : justOneLang)); - policy0.setStateMap(getOODAStateMap(policy0.getKey(), p0InEventList, p0OutEventList, axLogicExecutorTypeList, p0defaultTaskList, taskReferenceList)); - policy0.setFirstState(policy0.getStateMap().get("Observe").getKey().getLocalName()); - - final AxPolicies policies = new AxPolicies(new AxArtifactKey("OODAPolicies", "0.0.1")); - policies.getPolicyMap().put(policy0.getKey(), policy0); - - final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", "0.0.1")); - final AxPolicyModel policyModel = new AxPolicyModel(new AxArtifactKey("EvaluationPolicyModel_OODA", "0.0.1")); - policyModel.setPolicies(policies); - policyModel.setEvents(events); - policyModel.setTasks(tasks); - policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", "0.0.1"))); - policyModel.setSchemas(schemas); - policyModel.setKeyInformation(keyInformation); - policyModel.getKeyInformation().generateKeyInfo(policyModel); - - final AxValidationResult result = policyModel.validate(new AxValidationResult()); - if (!result.isOk()) { - throw new ApexRuntimeException("model " + policyModel.getId() + " is not valid" + result); - } - return policyModel; - } - - /** - * Gets the OODA state map. - * - * @param policyKey the policy key - * @param inEventKeyList the in event key list - * @param outEventKeyList the out event key list - * @param axLogicExecutorTypeList the ax logic executor type list - * @param defaultTaskList the default task list - * @param taskKeySetList the task key set list - * @return the OODA state map - */ - private Map getOODAStateMap(final AxArtifactKey policyKey, final List inEventKeyList, - final List outEventKeyList, final List axLogicExecutorTypeList, final List defaultTaskList, - final List> taskKeySetList) { - final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE).setDefaultLogic("EvalState_Logic"); - - final AxState actState = new AxState(new AxReferenceKey(policyKey, "Act")); - actState.setTrigger(inEventKeyList.get(THIRD_MEMBER)); - final AxStateOutput act2Out = new AxStateOutput(new AxReferenceKey(actState.getKey(), "Act2Out"), outEventKeyList.get(THIRD_MEMBER), - AxReferenceKey.getNullKey()); - actState.getStateOutputs().put(act2Out.getKey().getLocalName(), act2Out); - actState.setTaskSelectionLogic( - new AxTaskSelectionLogic(actState.getKey(), "TaskSelectionLogic", axLogicExecutorTypeList.get(THIRD_MEMBER), logicReader)); - actState.setDefaultTask(defaultTaskList.get(THIRD_MEMBER)); - for (final AxArtifactKey taskKey : taskKeySetList.get(THIRD_MEMBER)) { - actState.getTaskReferences().put(taskKey, - new AxStateTaskReference(new AxReferenceKey(actState.getKey(), taskKey.getName()), AxStateTaskOutputType.DIRECT, act2Out.getKey())); - } - - final AxState decState = new AxState(new AxReferenceKey(policyKey, "Decide")); - decState.setTrigger(inEventKeyList.get(2)); - final AxStateOutput dec2Act = new AxStateOutput(new AxReferenceKey(decState.getKey(), "Dec2Act"), outEventKeyList.get(2), actState.getKey()); - decState.getStateOutputs().put(dec2Act.getKey().getLocalName(), dec2Act); - decState.setTaskSelectionLogic(new AxTaskSelectionLogic(decState.getKey(), "TaskSelectionLogic", axLogicExecutorTypeList.get(2), logicReader)); - decState.setDefaultTask(defaultTaskList.get(2)); - for (final AxArtifactKey taskKey : taskKeySetList.get(2)) { - decState.getTaskReferences().put(taskKey, - new AxStateTaskReference(new AxReferenceKey(decState.getKey(), taskKey.getName()), AxStateTaskOutputType.DIRECT, dec2Act.getKey())); - } - - final AxState orState = new AxState(new AxReferenceKey(policyKey, "Orient")); - orState.setTrigger(inEventKeyList.get(1)); - final AxStateOutput or2Dec = new AxStateOutput(new AxReferenceKey(orState.getKey(), "Or2Dec"), outEventKeyList.get(1), decState.getKey()); - orState.getStateOutputs().put(or2Dec.getKey().getLocalName(), or2Dec); - orState.setTaskSelectionLogic(new AxTaskSelectionLogic(orState.getKey(), "TaskSelectionLogic", axLogicExecutorTypeList.get(1), logicReader)); - orState.setDefaultTask(defaultTaskList.get(1)); - for (final AxArtifactKey taskKey : taskKeySetList.get(1)) { - orState.getTaskReferences().put(taskKey, - new AxStateTaskReference(new AxReferenceKey(orState.getKey(), taskKey.getName()), AxStateTaskOutputType.DIRECT, or2Dec.getKey())); - } - - final AxState obState = new AxState(new AxReferenceKey(policyKey, "Observe")); - obState.setTrigger(inEventKeyList.get(0)); - final AxStateOutput ob2Or = new AxStateOutput(new AxReferenceKey(obState.getKey(), "Ob2Or"), outEventKeyList.get(0), orState.getKey()); - obState.getStateOutputs().put(ob2Or.getKey().getLocalName(), ob2Or); - obState.setTaskSelectionLogic(new AxTaskSelectionLogic(obState.getKey(), "TaskSelectionLogic", axLogicExecutorTypeList.get(0), logicReader)); - obState.setDefaultTask(defaultTaskList.get(0)); - for (final AxArtifactKey taskKey : taskKeySetList.get(0)) { - obState.getTaskReferences().put(taskKey, - new AxStateTaskReference(new AxReferenceKey(obState.getKey(), taskKey.getName()), AxStateTaskOutputType.DIRECT, ob2Or.getKey())); - } - - final Map stateMap = new TreeMap<>(); - stateMap.put(obState.getKey().getLocalName(), obState); - stateMap.put(orState.getKey().getLocalName(), orState); - stateMap.put(decState.getKey().getLocalName(), decState); - stateMap.put(actState.getKey().getLocalName(), actState); - - return stateMap; - } - - /** - * Get a sample ECA policy model. - * - * @return the sample policy model - */ - public AxPolicyModel getECAPolicyModel() { - - final AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", "0.0.1")); - - final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE).setDefaultLogic("EvalTask_Logic"); - - final AxTask eTask = new AxTask(new AxArtifactKey("Task_Event_0", "0.0.1")); - eTask.duplicateInputFields(event0000.getParameterMap()); - eTask.duplicateOutputFields(event0001.getParameterMap()); - final AxTaskLogic eAxLogic = new AxTaskLogic(eTask.getKey(), "TaskLogic", (justOneLang == null ? "JYTHON" : justOneLang), logicReader); - eAxLogic.setLogic( - eAxLogic.getLogic().replaceAll("", "Event").replaceAll("", eTask.getKey().getName()).replaceAll("", "1")); - eTask.setTaskLogic(eAxLogic); - - final AxTask cTask = new AxTask(new AxArtifactKey("Task_Condition_0", "0.0.1")); - cTask.duplicateInputFields(event0001.getParameterMap()); - cTask.duplicateOutputFields(event0002.getParameterMap()); - final AxTaskLogic cAxLogic = new AxTaskLogic(cTask.getKey(), "TaskLogic", (justOneLang == null ? "JAVASCRIPT" : justOneLang), logicReader); - cAxLogic.setLogic(cAxLogic.getLogic().replaceAll("", "Condition").replaceAll("", cTask.getKey().getName()) - .replaceAll("", "2")); - cTask.setTaskLogic(cAxLogic); - - final AxTask aTask = new AxTask(new AxArtifactKey("Task_Action_0", "0.0.1")); - aTask.duplicateInputFields(event0002.getParameterMap()); - aTask.duplicateOutputFields(event0003.getParameterMap()); - final AxTaskLogic aAxLogic = new AxTaskLogic(aTask.getKey(), "TaskLogic", (justOneLang == null ? "JAVA" : justOneLang), logicReader); - aAxLogic.setLogic( - aAxLogic.getLogic().replaceAll("", "Action").replaceAll("", aTask.getKey().getName()).replaceAll("", "3")); - aTask.setTaskLogic(aAxLogic); - - tasks.getTaskMap().put(eTask.getKey(), eTask); - tasks.getTaskMap().put(cTask.getKey(), cTask); - tasks.getTaskMap().put(aTask.getKey(), aTask); - - final Set eventTasks = new TreeSet<>(); - final Set conditionTasks = new TreeSet<>(); - final Set actionTasks = new TreeSet<>(); - - for (final AxTask task : tasks.getTaskMap().values()) { - if (task.getKey().getName().contains("Event")) { - eventTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Condition")) { - conditionTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Action")) { - actionTasks.add(task.getKey()); - } - } - final List> taskReferenceList = new ArrayList<>(); - taskReferenceList.add(eventTasks); - taskReferenceList.add(conditionTasks); - taskReferenceList.add(actionTasks); - - final List p0InEventList = new ArrayList<>(); - p0InEventList.add(event0000.getKey()); - p0InEventList.add(event0001.getKey()); - p0InEventList.add(event0002.getKey()); - - final List p0OutEventList = new ArrayList<>(); - p0OutEventList.add(event0001.getKey()); - p0OutEventList.add(event0002.getKey()); - p0OutEventList.add(event0003.getKey()); - - final List p0defaultTaskList = new ArrayList<>(); - p0defaultTaskList.add(tasks.get("Task_Event_0").getKey()); - p0defaultTaskList.add(tasks.get("Task_Condition_0").getKey()); - p0defaultTaskList.add(tasks.get("Task_Action_0").getKey()); - - final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("ECAPolicy_0", "0.0.1")); - final List axLogicExecutorTypeList = Arrays.asList((justOneLang == null ? "JAVASCRIPT" : justOneLang), - (justOneLang == null ? "MVEL" : justOneLang), (justOneLang == null ? "JYTHON" : justOneLang)); - policy0.setStateMap(getECAStateMap(policy0.getKey(), p0InEventList, p0OutEventList, axLogicExecutorTypeList, p0defaultTaskList, taskReferenceList)); - policy0.setFirstState(policy0.getStateMap().get("Event").getKey().getLocalName()); - - final AxPolicies policies = new AxPolicies(new AxArtifactKey("ECAPolicies", "0.0.1")); - policies.getPolicyMap().put(policy0.getKey(), policy0); - - final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", "0.0.1")); - final AxPolicyModel policyModel = new AxPolicyModel(new AxArtifactKey("EvaluationPolicyModel_ECA", "0.0.1")); - policyModel.setPolicies(policies); - policyModel.setEvents(events); - policyModel.setTasks(tasks); - policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", "0.0.1"))); - policyModel.setSchemas(schemas); - policyModel.setKeyInformation(keyInformation); - policyModel.getKeyInformation().generateKeyInfo(policyModel); - - final AxValidationResult result = policyModel.validate(new AxValidationResult()); - if (!result.isOk()) { - throw new ApexRuntimeException("model " + policyModel.getId() + " is not valid" + result); - } - return policyModel; - } - - /** - * Gets the ECA state map. - * - * @param policyKey the policy key - * @param inEventKeyList the in event key list - * @param outEventKeyList the out event key list - * @param axLogicExecutorTypeList the ax logic executor type list - * @param defaultTaskList the default task list - * @param taskKeySetList the task key set list - * @return the ECA state map - */ - private Map getECAStateMap(final AxArtifactKey policyKey, final List inEventKeyList, - final List outEventKeyList, final List axLogicExecutorTypeList, final List defaultTaskList, - final List> taskKeySetList) { - final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE).setDefaultLogic("EvalState_Logic"); - - final AxState actionState = new AxState(new AxReferenceKey(policyKey, "Action")); - actionState.setTrigger(inEventKeyList.get(2)); - final AxStateOutput action2Out = new AxStateOutput(actionState.getKey(), AxReferenceKey.getNullKey(), outEventKeyList.get(2)); - actionState.getStateOutputs().put(action2Out.getKey().getLocalName(), action2Out); - actionState.setTaskSelectionLogic(new AxTaskSelectionLogic(actionState.getKey(), "TaskSelectionLogic", axLogicExecutorTypeList.get(2), logicReader)); - actionState.setDefaultTask(defaultTaskList.get(2)); - for (final AxArtifactKey taskKey : taskKeySetList.get(2)) { - actionState.getTaskReferences().put(taskKey, - new AxStateTaskReference(new AxReferenceKey(actionState.getKey(), taskKey.getName()), AxStateTaskOutputType.DIRECT, action2Out.getKey())); - } - - final AxState conditionState = new AxState(new AxReferenceKey(policyKey, "Condition")); - conditionState.setTrigger(inEventKeyList.get(1)); - final AxStateOutput condition2Action = new AxStateOutput(conditionState.getKey(), actionState.getKey(), outEventKeyList.get(1)); - conditionState.getStateOutputs().put(condition2Action.getKey().getLocalName(), condition2Action); - conditionState - .setTaskSelectionLogic(new AxTaskSelectionLogic(conditionState.getKey(), "TaskSelectionLogic", axLogicExecutorTypeList.get(1), logicReader)); - conditionState.setDefaultTask(defaultTaskList.get(1)); - for (final AxArtifactKey taskKey : taskKeySetList.get(1)) { - conditionState.getTaskReferences().put(taskKey, new AxStateTaskReference(new AxReferenceKey(conditionState.getKey(), taskKey.getName()), - AxStateTaskOutputType.DIRECT, condition2Action.getKey())); - } - - final AxState eventState = new AxState(new AxReferenceKey(policyKey, "Event")); - eventState.setTrigger(inEventKeyList.get(0)); - final AxStateOutput event2Condition = new AxStateOutput(eventState.getKey(), conditionState.getKey(), outEventKeyList.get(0)); - eventState.getStateOutputs().put(event2Condition.getKey().getLocalName(), event2Condition); - eventState.setTaskSelectionLogic(new AxTaskSelectionLogic(eventState.getKey(), "TaskSelectionLogic", axLogicExecutorTypeList.get(0), logicReader)); - eventState.setDefaultTask(defaultTaskList.get(0)); - for (final AxArtifactKey taskKey : taskKeySetList.get(0)) { - eventState.getTaskReferences().put(taskKey, new AxStateTaskReference(new AxReferenceKey(eventState.getKey(), taskKey.getName()), - AxStateTaskOutputType.DIRECT, event2Condition.getKey())); - } - - final Map stateMap = new TreeMap<>(); - stateMap.put(eventState.getKey().getLocalName(), eventState); - stateMap.put(conditionState.getKey().getLocalName(), conditionState); - stateMap.put(actionState.getKey().getLocalName(), actionState); - - return stateMap; - } - -} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelFactory.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelFactory.java deleted file mode 100644 index 184529fa9..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelFactory.java +++ /dev/null @@ -1,717 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.test.common.model; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; -import org.onap.policy.apex.model.eventmodel.concepts.AxField; -import org.onap.policy.apex.model.policymodel.concepts.AxLogicReader; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicies; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.model.policymodel.concepts.AxState; -import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput; -import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskOutputType; -import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference; -import org.onap.policy.apex.model.policymodel.concepts.AxTask; -import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic; -import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter; -import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic; -import org.onap.policy.apex.model.policymodel.concepts.AxTasks; -import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; - -/** - * This class creates sample Policy Models. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class SampleDomainModelFactory { - private static final int THIRD_ENTRY = 3; - - /** - * Get a sample policy model. - * - * @param axLogicExecutorType The type of logic executor, the scripting language being used - * @return the sample policy model - */ - // CHECKSTYLE:OFF: checkstyle:maximumMethodLength - public AxPolicyModel getSamplePolicyModel(final String axLogicExecutorType) { - AxContextSchema testSlogan = - new AxContextSchema(new AxArtifactKey("TestSlogan", "0.0.1"), "Java", "java.lang.String"); - AxContextSchema testCase = - new AxContextSchema(new AxArtifactKey("TestCase", "0.0.1"), "Java", "java.lang.Byte"); - AxContextSchema testTimestamp = - new AxContextSchema(new AxArtifactKey("TestTimestamp", "0.0.1"), "Java", "java.lang.Long"); - AxContextSchema testTemperature = - new AxContextSchema(new AxArtifactKey("TestTemperature", "0.0.1"), "Java", "java.lang.Double"); - - AxContextSchema testContextItem000 = new AxContextSchema(new AxArtifactKey("TestContextItem000", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem000"); - AxContextSchema testContextItem001 = new AxContextSchema(new AxArtifactKey("TestContextItem001", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem001"); - AxContextSchema testContextItem002 = new AxContextSchema(new AxArtifactKey("TestContextItem002", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem002"); - AxContextSchema testContextItem003 = new AxContextSchema(new AxArtifactKey("TestContextItem003", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem003"); - AxContextSchema testContextItem004 = new AxContextSchema(new AxArtifactKey("TestContextItem004", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem004"); - AxContextSchema testContextItem005 = new AxContextSchema(new AxArtifactKey("TestContextItem005", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem005"); - AxContextSchema testContextItem006 = new AxContextSchema(new AxArtifactKey("TestContextItem006", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem006"); - AxContextSchema testContextItem007 = new AxContextSchema(new AxArtifactKey("TestContextItem007", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem007"); - AxContextSchema testContextItem008 = new AxContextSchema(new AxArtifactKey("TestContextItem008", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem008"); - AxContextSchema testContextItem009 = new AxContextSchema(new AxArtifactKey("TestContextItem009", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem009"); - AxContextSchema testContextItem00A = new AxContextSchema(new AxArtifactKey("TestContextItem00A", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem00A"); - AxContextSchema testContextItem00B = new AxContextSchema(new AxArtifactKey("TestContextItem00B", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem00B"); - AxContextSchema testContextItem00C = new AxContextSchema(new AxArtifactKey("TestContextItem00C", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestContextItem00C"); - - AxContextSchema testPolicyContextItem = new AxContextSchema(new AxArtifactKey("TestPolicyContextItem", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestPolicyContextItem"); - AxContextSchema testGlobalContextItem = new AxContextSchema(new AxArtifactKey("TestGlobalContextItem", "0.0.1"), - "Java", "org.onap.policy.apex.context.test.concepts.TestGlobalContextItem"); - AxContextSchema testExternalContextItem = - new AxContextSchema(new AxArtifactKey("TestExternalContextItem", "0.0.1"), "Java", - "org.onap.policy.apex.context.test.concepts.TestExternalContextItem"); - - AxContextSchemas axContextSchemas = new AxContextSchemas(new AxArtifactKey("TestDatatypes", "0.0.1")); - axContextSchemas.getSchemasMap().put(testSlogan.getKey(), testSlogan); - axContextSchemas.getSchemasMap().put(testCase.getKey(), testCase); - axContextSchemas.getSchemasMap().put(testTimestamp.getKey(), testTimestamp); - axContextSchemas.getSchemasMap().put(testTemperature.getKey(), testTemperature); - - axContextSchemas.getSchemasMap().put(testContextItem000.getKey(), testContextItem000); - axContextSchemas.getSchemasMap().put(testContextItem001.getKey(), testContextItem001); - axContextSchemas.getSchemasMap().put(testContextItem002.getKey(), testContextItem002); - axContextSchemas.getSchemasMap().put(testContextItem003.getKey(), testContextItem003); - axContextSchemas.getSchemasMap().put(testContextItem004.getKey(), testContextItem004); - axContextSchemas.getSchemasMap().put(testContextItem005.getKey(), testContextItem005); - axContextSchemas.getSchemasMap().put(testContextItem006.getKey(), testContextItem006); - axContextSchemas.getSchemasMap().put(testContextItem007.getKey(), testContextItem007); - axContextSchemas.getSchemasMap().put(testContextItem008.getKey(), testContextItem008); - axContextSchemas.getSchemasMap().put(testContextItem009.getKey(), testContextItem009); - axContextSchemas.getSchemasMap().put(testContextItem00A.getKey(), testContextItem00A); - axContextSchemas.getSchemasMap().put(testContextItem00B.getKey(), testContextItem00B); - axContextSchemas.getSchemasMap().put(testContextItem00C.getKey(), testContextItem00C); - - axContextSchemas.getSchemasMap().put(testPolicyContextItem.getKey(), testPolicyContextItem); - axContextSchemas.getSchemasMap().put(testGlobalContextItem.getKey(), testGlobalContextItem); - axContextSchemas.getSchemasMap().put(testExternalContextItem.getKey(), testExternalContextItem); - - AxEvent event0000 = new AxEvent(new AxArtifactKey("Event0000", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0000.setSource("Outside"); - event0000.setTarget("Match"); - event0000.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0000.getKey(), "TestSlogan"), testSlogan.getKey())); - event0000.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0000.getKey(), "TestMatchCase"), testCase.getKey())); - event0000.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0000.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0000.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0000.getKey(), "TestTemperature"), testTemperature.getKey())); - - AxEvent event0001 = new AxEvent(new AxArtifactKey("Event0001", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0001.setSource("Match"); - event0001.setTarget("Establish"); - event0001.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0001.getKey(), "TestSlogan"), testSlogan.getKey())); - event0001.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0001.getKey(), "TestMatchCase"), testCase.getKey())); - event0001.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0001.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0001.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0001.getKey(), "TestTemperature"), testTemperature.getKey())); - event0001.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0001.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0001.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0001.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - - AxEvent event0002 = new AxEvent(new AxArtifactKey("Event0002", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0002.setSource("Establish"); - event0002.setTarget("Decide"); - event0002.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0002.getKey(), "TestSlogan"), testSlogan.getKey())); - event0002.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0002.getKey(), "TestMatchCase"), testCase.getKey())); - event0002.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0002.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0002.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0002.getKey(), "TestTemperature"), testTemperature.getKey())); - event0002.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0002.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0002.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0002.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - event0002.getParameterMap().put("TestEstablishCaseSelected", - new AxField(new AxReferenceKey(event0002.getKey(), "TestEstablishCaseSelected"), testCase.getKey())); - event0002.getParameterMap().put("TestEstablishStateTime", - new AxField(new AxReferenceKey(event0002.getKey(), "TestEstablishStateTime"), testTimestamp.getKey())); - - AxEvent event0003 = new AxEvent(new AxArtifactKey("Event0003", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0003.setSource("Decide"); - event0003.setTarget("Act"); - event0003.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0003.getKey(), "TestSlogan"), testSlogan.getKey())); - event0003.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0003.getKey(), "TestMatchCase"), testCase.getKey())); - event0003.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0003.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0003.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0003.getKey(), "TestTemperature"), testTemperature.getKey())); - event0003.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0003.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0003.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0003.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - event0003.getParameterMap().put("TestEstablishCaseSelected", - new AxField(new AxReferenceKey(event0003.getKey(), "TestEstablishCaseSelected"), testCase.getKey())); - event0003.getParameterMap().put("TestEstablishStateTime", - new AxField(new AxReferenceKey(event0003.getKey(), "TestEstablishStateTime"), testTimestamp.getKey())); - event0003.getParameterMap().put("TestDecideCaseSelected", - new AxField(new AxReferenceKey(event0003.getKey(), "TestDecideCaseSelected"), testCase.getKey())); - event0003.getParameterMap().put("TestDecideStateTime", - new AxField(new AxReferenceKey(event0003.getKey(), "TestDecideStateTime"), testTimestamp.getKey())); - - AxEvent event0004 = new AxEvent(new AxArtifactKey("Event0004", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0004.setSource("Act"); - event0004.setTarget("Outside"); - event0004.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0004.getKey(), "TestSlogan"), testSlogan.getKey())); - event0004.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0004.getKey(), "TestMatchCase"), testCase.getKey())); - event0004.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0004.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0004.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0004.getKey(), "TestTemperature"), testTemperature.getKey())); - event0004.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0004.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0004.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0004.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - event0004.getParameterMap().put("TestEstablishCaseSelected", - new AxField(new AxReferenceKey(event0004.getKey(), "TestEstablishCaseSelected"), testCase.getKey())); - event0004.getParameterMap().put("TestEstablishStateTime", - new AxField(new AxReferenceKey(event0004.getKey(), "TestEstablishStateTime"), testTimestamp.getKey())); - event0004.getParameterMap().put("TestDecideCaseSelected", - new AxField(new AxReferenceKey(event0004.getKey(), "TestDecideCaseSelected"), testCase.getKey())); - event0004.getParameterMap().put("TestDecideStateTime", - new AxField(new AxReferenceKey(event0004.getKey(), "TestDecideStateTime"), testTimestamp.getKey())); - event0004.getParameterMap().put("TestActCaseSelected", - new AxField(new AxReferenceKey(event0004.getKey(), "TestActCaseSelected"), testCase.getKey())); - event0004.getParameterMap().put("TestActStateTime", - new AxField(new AxReferenceKey(event0004.getKey(), "TestActStateTime"), testTimestamp.getKey())); - - AxEvent event0100 = new AxEvent(new AxArtifactKey("Event0100", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0100.setSource("Outside"); - event0100.setTarget("Match"); - event0100.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0100.getKey(), "TestSlogan"), testSlogan.getKey())); - event0100.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0100.getKey(), "TestMatchCase"), testCase.getKey())); - event0100.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0100.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0100.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0100.getKey(), "TestTemperature"), testTemperature.getKey())); - - AxEvent event0101 = new AxEvent(new AxArtifactKey("Event0101", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0101.setSource("Match"); - event0101.setTarget("Establish"); - event0101.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0101.getKey(), "TestSlogan"), testSlogan.getKey())); - event0101.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0101.getKey(), "TestMatchCase"), testCase.getKey())); - event0101.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0101.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0101.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0101.getKey(), "TestTemperature"), testTemperature.getKey())); - event0101.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0101.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0101.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0101.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - - AxEvent event0102 = new AxEvent(new AxArtifactKey("Event0102", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0102.setSource("Establish"); - event0102.setTarget("Decide"); - event0102.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0102.getKey(), "TestSlogan"), testSlogan.getKey())); - event0102.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0102.getKey(), "TestMatchCase"), testCase.getKey())); - event0102.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0102.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0102.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0102.getKey(), "TestTemperature"), testTemperature.getKey())); - event0102.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0102.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0102.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0102.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - event0102.getParameterMap().put("TestEstablishCaseSelected", - new AxField(new AxReferenceKey(event0102.getKey(), "TestEstablishCaseSelected"), testCase.getKey())); - event0102.getParameterMap().put("TestEstablishStateTime", - new AxField(new AxReferenceKey(event0102.getKey(), "TestEstablishStateTime"), testTimestamp.getKey())); - - AxEvent event0103 = new AxEvent(new AxArtifactKey("Event0103", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0103.setSource("Decide"); - event0103.setTarget("Act"); - event0103.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0103.getKey(), "TestSlogan"), testSlogan.getKey())); - event0103.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0103.getKey(), "TestMatchCase"), testCase.getKey())); - event0103.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0103.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0103.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0103.getKey(), "TestTemperature"), testTemperature.getKey())); - event0103.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0103.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0103.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0103.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - event0103.getParameterMap().put("TestEstablishCaseSelected", - new AxField(new AxReferenceKey(event0103.getKey(), "TestEstablishCaseSelected"), testCase.getKey())); - event0103.getParameterMap().put("TestEstablishStateTime", - new AxField(new AxReferenceKey(event0103.getKey(), "TestEstablishStateTime"), testTimestamp.getKey())); - event0103.getParameterMap().put("TestDecideCaseSelected", - new AxField(new AxReferenceKey(event0103.getKey(), "TestDecideCaseSelected"), testCase.getKey())); - event0103.getParameterMap().put("TestDecideStateTime", - new AxField(new AxReferenceKey(event0103.getKey(), "TestDecideStateTime"), testTimestamp.getKey())); - - AxEvent event0104 = new AxEvent(new AxArtifactKey("Event0104", "0.0.1"), "org.onap.policy.apex.sample.events"); - event0104.setSource("Act"); - event0104.setTarget("Outside"); - event0104.getParameterMap().put("TestSlogan", - new AxField(new AxReferenceKey(event0104.getKey(), "TestSlogan"), testSlogan.getKey())); - event0104.getParameterMap().put("TestMatchCase", - new AxField(new AxReferenceKey(event0104.getKey(), "TestMatchCase"), testCase.getKey())); - event0104.getParameterMap().put("TestTimestamp", - new AxField(new AxReferenceKey(event0104.getKey(), "TestTimestamp"), testTimestamp.getKey())); - event0104.getParameterMap().put("TestTemperature", - new AxField(new AxReferenceKey(event0104.getKey(), "TestTemperature"), testTemperature.getKey())); - event0104.getParameterMap().put("TestMatchCaseSelected", - new AxField(new AxReferenceKey(event0104.getKey(), "TestMatchCaseSelected"), testCase.getKey())); - event0104.getParameterMap().put("TestMatchStateTime", - new AxField(new AxReferenceKey(event0104.getKey(), "TestMatchStateTime"), testTimestamp.getKey())); - event0104.getParameterMap().put("TestEstablishCaseSelected", - new AxField(new AxReferenceKey(event0104.getKey(), "TestEstablishCaseSelected"), testCase.getKey())); - event0104.getParameterMap().put("TestEstablishStateTime", - new AxField(new AxReferenceKey(event0104.getKey(), "TestEstablishStateTime"), testTimestamp.getKey())); - event0104.getParameterMap().put("TestDecideCaseSelected", - new AxField(new AxReferenceKey(event0104.getKey(), "TestDecideCaseSelected"), testCase.getKey())); - event0104.getParameterMap().put("TestDecideStateTime", - new AxField(new AxReferenceKey(event0104.getKey(), "TestDecideStateTime"), testTimestamp.getKey())); - event0104.getParameterMap().put("TestActCaseSelected", - new AxField(new AxReferenceKey(event0104.getKey(), "TestActCaseSelected"), testCase.getKey())); - event0104.getParameterMap().put("TestActStateTime", - new AxField(new AxReferenceKey(event0104.getKey(), "TestActStateTime"), testTimestamp.getKey())); - - AxEvents events = new AxEvents(new AxArtifactKey("Events", "0.0.1")); - events.getEventMap().put(event0000.getKey(), event0000); - events.getEventMap().put(event0001.getKey(), event0001); - events.getEventMap().put(event0002.getKey(), event0002); - events.getEventMap().put(event0003.getKey(), event0003); - events.getEventMap().put(event0004.getKey(), event0004); - events.getEventMap().put(event0100.getKey(), event0100); - events.getEventMap().put(event0101.getKey(), event0101); - events.getEventMap().put(event0102.getKey(), event0102); - events.getEventMap().put(event0103.getKey(), event0103); - events.getEventMap().put(event0104.getKey(), event0104); - - AxContextAlbum externalContextAlbum = new AxContextAlbum(new AxArtifactKey("ExternalContextAlbum", "0.0.1"), - "EXTERNAL", false, testExternalContextItem.getKey()); - AxContextAlbum globalContextAlbum = new AxContextAlbum(new AxArtifactKey("GlobalContextAlbum", "0.0.1"), - "GLOBAL", true, testGlobalContextItem.getKey()); - AxContextAlbum policy0ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy0ContextAlbum", "0.0.1"), - "APPLICATION", true, testPolicyContextItem.getKey()); - AxContextAlbum policy1ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy1ContextAlbum", "0.0.1"), - "APPLICATION", true, testPolicyContextItem.getKey()); - - AxContextAlbums albums = new AxContextAlbums(new AxArtifactKey("Context", "0.0.1")); - albums.getAlbumsMap().put(externalContextAlbum.getKey(), externalContextAlbum); - albums.getAlbumsMap().put(globalContextAlbum.getKey(), globalContextAlbum); - albums.getAlbumsMap().put(policy0ContextAlbum.getKey(), policy0ContextAlbum); - albums.getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); - - Set referenceKeySet0 = new TreeSet(); - referenceKeySet0.add(policy0ContextAlbum.getKey()); - referenceKeySet0.add(policy1ContextAlbum.getKey()); - referenceKeySet0.add(globalContextAlbum.getKey()); - referenceKeySet0.add(externalContextAlbum.getKey()); - - Set referenceKeySet1 = new TreeSet(); - referenceKeySet1.add(policy0ContextAlbum.getKey()); - referenceKeySet1.add(globalContextAlbum.getKey()); - - Set referenceKeySet2 = new TreeSet(); - referenceKeySet2.add(policy1ContextAlbum.getKey()); - referenceKeySet2.add(globalContextAlbum.getKey()); - - Set referenceKeySet3 = new TreeSet(); - referenceKeySet3.add(globalContextAlbum.getKey()); - referenceKeySet3.add(externalContextAlbum.getKey()); - - List> referenceKeySetList = new ArrayList>(); - referenceKeySetList.add(referenceKeySet0); - referenceKeySetList.add(referenceKeySet1); - referenceKeySetList.add(referenceKeySet2); - referenceKeySetList.add(referenceKeySet3); - - AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", "0.0.1")); - tasks.getTaskMap().putAll(getTaskMap("Match", event0000.getParameterMap(), event0001.getParameterMap(), - referenceKeySetList, axLogicExecutorType)); - tasks.getTaskMap().putAll(getTaskMap("Establish", event0001.getParameterMap(), event0002.getParameterMap(), - referenceKeySetList, axLogicExecutorType)); - tasks.getTaskMap().putAll(getTaskMap("Decide", event0002.getParameterMap(), event0003.getParameterMap(), - referenceKeySetList, axLogicExecutorType)); - tasks.getTaskMap().putAll(getTaskMap("Act", event0003.getParameterMap(), event0004.getParameterMap(), - referenceKeySetList, axLogicExecutorType)); - - Set matchTasks = new TreeSet(); - Set establishTasks = new TreeSet(); - Set decideTasks = new TreeSet(); - Set actTasks = new TreeSet(); - for (AxTask task : tasks.getTaskMap().values()) { - if (task.getKey().getName().contains("Match")) { - matchTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Establish")) { - establishTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Decide")) { - decideTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Act")) { - actTasks.add(task.getKey()); - } - } - List> taskReferenceList = new ArrayList>(); - taskReferenceList.add(matchTasks); - taskReferenceList.add(establishTasks); - taskReferenceList.add(decideTasks); - taskReferenceList.add(actTasks); - - List p0InEventList = new ArrayList(); - p0InEventList.add(event0000.getKey()); - p0InEventList.add(event0001.getKey()); - p0InEventList.add(event0002.getKey()); - p0InEventList.add(event0003.getKey()); - - List p0OutEventList = new ArrayList(); - p0OutEventList.add(event0001.getKey()); - p0OutEventList.add(event0002.getKey()); - p0OutEventList.add(event0003.getKey()); - p0OutEventList.add(event0004.getKey()); - - List p0defaultTaskList = new ArrayList(); - p0defaultTaskList.add(tasks.get("Task_Match0").getKey()); - p0defaultTaskList.add(tasks.get("Task_Establish2").getKey()); - p0defaultTaskList.add(tasks.get("Task_Decide3").getKey()); - p0defaultTaskList.add(tasks.get("Task_Act1").getKey()); - - List p1InEventList = new ArrayList(); - p1InEventList.add(event0100.getKey()); - p1InEventList.add(event0101.getKey()); - p1InEventList.add(event0102.getKey()); - p1InEventList.add(event0103.getKey()); - - List p1OutEventList = new ArrayList(); - p1OutEventList.add(event0101.getKey()); - p1OutEventList.add(event0102.getKey()); - p1OutEventList.add(event0103.getKey()); - p1OutEventList.add(event0104.getKey()); - - List p1defaultTaskList = new ArrayList(); - p1defaultTaskList.add(tasks.get("Task_Match3").getKey()); - p1defaultTaskList.add(tasks.get("Task_Establish1").getKey()); - p1defaultTaskList.add(tasks.get("Task_Decide3").getKey()); - p1defaultTaskList.add(tasks.get("Task_Act0").getKey()); - - Set p0ReferenceKeySet0 = new TreeSet(); - p0ReferenceKeySet0.add(policy0ContextAlbum.getKey()); - p0ReferenceKeySet0.add(globalContextAlbum.getKey()); - - Set p0ReferenceKeySet1 = new TreeSet(); - p0ReferenceKeySet1.add(policy1ContextAlbum.getKey()); - p0ReferenceKeySet1.add(globalContextAlbum.getKey()); - p0ReferenceKeySet1.add(externalContextAlbum.getKey()); - - Set p0ReferenceKeySet2 = new TreeSet(); - p0ReferenceKeySet2.add(policy0ContextAlbum.getKey()); - p0ReferenceKeySet2.add(globalContextAlbum.getKey()); - p0ReferenceKeySet2.add(externalContextAlbum.getKey()); - - Set p0ReferenceKeySet3 = new TreeSet(); - p0ReferenceKeySet3.add(globalContextAlbum.getKey()); - - List> p0ReferenceKeySetList = new ArrayList>(); - p0ReferenceKeySetList.add(p0ReferenceKeySet0); - p0ReferenceKeySetList.add(p0ReferenceKeySet1); - p0ReferenceKeySetList.add(p0ReferenceKeySet2); - p0ReferenceKeySetList.add(p0ReferenceKeySet3); - - AxPolicy policy0 = new AxPolicy(new AxArtifactKey("Policy0", "0.0.1")); - policy0.setTemplate("MEDA"); - policy0.setStateMap(getStateMap(policy0.getKey(), p0InEventList, p0OutEventList, p0ReferenceKeySetList, - axLogicExecutorType, p0defaultTaskList, taskReferenceList)); - policy0.setFirstState(policy0.getStateMap().get("Match").getKey().getLocalName()); - - Set p1ReferenceKeySet0 = new TreeSet(); - p1ReferenceKeySet0.add(policy1ContextAlbum.getKey()); - p1ReferenceKeySet0.add(globalContextAlbum.getKey()); - p1ReferenceKeySet0.add(externalContextAlbum.getKey()); - - Set p1ReferenceKeySet1 = new TreeSet(); - p1ReferenceKeySet1.add(policy1ContextAlbum.getKey()); - p1ReferenceKeySet1.add(globalContextAlbum.getKey()); - p1ReferenceKeySet1.add(externalContextAlbum.getKey()); - - Set p1ReferenceKeySet2 = new TreeSet(); - p1ReferenceKeySet2.add(policy1ContextAlbum.getKey()); - p1ReferenceKeySet2.add(globalContextAlbum.getKey()); - p1ReferenceKeySet2.add(externalContextAlbum.getKey()); - - Set p1ReferenceKeySet3 = new TreeSet(); - p1ReferenceKeySet3.add(globalContextAlbum.getKey()); - - List> p1ReferenceKeySetList = new ArrayList>(); - p1ReferenceKeySetList.add(p1ReferenceKeySet0); - p1ReferenceKeySetList.add(p1ReferenceKeySet1); - p1ReferenceKeySetList.add(p1ReferenceKeySet2); - p1ReferenceKeySetList.add(p1ReferenceKeySet3); - - AxPolicy policy1 = new AxPolicy(new AxArtifactKey("Policy1", "0.0.1")); - policy1.setTemplate("MEDA"); - policy1.setStateMap(getStateMap(policy1.getKey(), p1InEventList, p1OutEventList, p1ReferenceKeySetList, - axLogicExecutorType, p1defaultTaskList, taskReferenceList)); - policy1.setFirstState(policy1.getStateMap().get("Match").getKey().getLocalName()); - - AxPolicies policies = new AxPolicies(new AxArtifactKey("Policies", "0.0.1")); - policies.getPolicyMap().put(policy0.getKey(), policy0); - policies.getPolicyMap().put(policy1.getKey(), policy1); - - AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", "0.0.1")); - AxPolicyModel policyModel = - new AxPolicyModel(new AxArtifactKey("SamplePolicyModel" + axLogicExecutorType, "0.0.1")); - policyModel.setKeyInformation(keyInformation); - policyModel.setPolicies(policies); - policyModel.setEvents(events); - policyModel.setTasks(tasks); - policyModel.setAlbums(albums); - policyModel.setSchemas(axContextSchemas); - policyModel.getKeyInformation().generateKeyInfo(policyModel); - - AxValidationResult result = policyModel.validate(new AxValidationResult()); - if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.VALID)) { - throw new ApexRuntimeException("model " + policyModel.getId() + " is not valid" + result); - } - return policyModel; - } - - /** - * Gets the state map. - * - * @param policyKey the policy key - * @param inEventKeyList the in event key list - * @param outEventKeyList the out event key list - * @param referenceKeySetList the reference key set list - * @param axLogicExecutorType the ax logic executor type - * @param defaultTaskList the default task list - * @param taskKeySetList the task key set list - * @return the state map - */ - private Map getStateMap(final AxArtifactKey policyKey, final List inEventKeyList, - final List outEventKeyList, final List> referenceKeySetList, - final String axLogicExecutorType, final List defaultTaskList, - final List> taskKeySetList) { - AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(this.getClass().getPackage().getName()) - .setDefaultLogic("DefaultState_Logic"); - - AxState actState = new AxState(new AxReferenceKey(policyKey, "Act")); - actState.setTrigger(inEventKeyList.get(3)); - AxStateOutput act2Out = - new AxStateOutput(actState.getKey(), AxReferenceKey.getNullKey(), outEventKeyList.get(3)); - actState.getStateOutputs().put(act2Out.getKey().getLocalName(), act2Out); - actState.setContextAlbumReferences(referenceKeySetList.get(3)); - actState.setTaskSelectionLogic( - new AxTaskSelectionLogic(actState.getKey(), "TaskSelectionLigic", axLogicExecutorType, logicReader)); - actState.setDefaultTask(defaultTaskList.get(3)); - for (AxArtifactKey taskKey : taskKeySetList.get(3)) { - actState.getTaskReferences().put(taskKey, new AxStateTaskReference(actState.getKey(), taskKey, - AxStateTaskOutputType.DIRECT, act2Out.getKey())); - } - - AxState decideState = new AxState(new AxReferenceKey(policyKey, "Decide")); - decideState.setTrigger(inEventKeyList.get(2)); - AxStateOutput decide2Act = new AxStateOutput(decideState.getKey(), actState.getKey(), outEventKeyList.get(2)); - decideState.getStateOutputs().put(decide2Act.getKey().getLocalName(), decide2Act); - decideState.setContextAlbumReferences(referenceKeySetList.get(2)); - decideState.setTaskSelectionLogic( - new AxTaskSelectionLogic(decideState.getKey(), "TaskSelectionLigic", axLogicExecutorType, logicReader)); - decideState.setDefaultTask(defaultTaskList.get(2)); - for (AxArtifactKey taskKey : taskKeySetList.get(2)) { - decideState.getTaskReferences().put(taskKey, new AxStateTaskReference(decideState.getKey(), taskKey, - AxStateTaskOutputType.DIRECT, decide2Act.getKey())); - } - - AxState establishState = new AxState(new AxReferenceKey(policyKey, "Establish")); - establishState.setTrigger(inEventKeyList.get(1)); - AxStateOutput establish2Decide = - new AxStateOutput(establishState.getKey(), decideState.getKey(), outEventKeyList.get(1)); - establishState.getStateOutputs().put(establish2Decide.getKey().getLocalName(), establish2Decide); - establishState.setContextAlbumReferences(referenceKeySetList.get(1)); - establishState.setTaskSelectionLogic(new AxTaskSelectionLogic(establishState.getKey(), "TaskSelectionLigic", - axLogicExecutorType, logicReader)); - establishState.setDefaultTask(defaultTaskList.get(1)); - for (AxArtifactKey taskKey : taskKeySetList.get(1)) { - establishState.getTaskReferences().put(taskKey, new AxStateTaskReference(establishState.getKey(), taskKey, - AxStateTaskOutputType.DIRECT, establish2Decide.getKey())); - } - - AxState matchState = new AxState(new AxReferenceKey(policyKey, "Match")); - matchState.setTrigger(inEventKeyList.get(0)); - AxStateOutput match2Establish = - new AxStateOutput(matchState.getKey(), establishState.getKey(), outEventKeyList.get(0)); - matchState.getStateOutputs().put(match2Establish.getKey().getLocalName(), match2Establish); - matchState.setContextAlbumReferences(referenceKeySetList.get(0)); - matchState.setTaskSelectionLogic( - new AxTaskSelectionLogic(matchState.getKey(), "TaskSelectionLigic", axLogicExecutorType, logicReader)); - matchState.setDefaultTask(defaultTaskList.get(0)); - for (AxArtifactKey taskKey : taskKeySetList.get(0)) { - matchState.getTaskReferences().put(taskKey, new AxStateTaskReference(matchState.getKey(), taskKey, - AxStateTaskOutputType.DIRECT, match2Establish.getKey())); - } - - Map stateMap = new TreeMap(); - stateMap.put(matchState.getKey().getLocalName(), matchState); - stateMap.put(establishState.getKey().getLocalName(), establishState); - stateMap.put(decideState.getKey().getLocalName(), decideState); - stateMap.put(actState.getKey().getLocalName(), actState); - - return stateMap; - } - // CHECKSTYLE:ON: checkstyle:maximumMethodLength - - /** - * Gets the task map. - * - * @param state the state - * @param inputFields the input fields - * @param outputFields the output fields - * @param referenceKeySetList the reference key set list - * @param axLogicExecutorType the ax logic executor type - * @return the task map - */ - private Map getTaskMap(final String state, final Map inputFields, - final Map outputFields, final List> referenceKeySetList, - final String axLogicExecutorType) { - AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(this.getClass().getPackage().getName()) - .setDefaultLogic("DefaultTask_Logic"); - - AxTask testTask0 = new AxTask(new AxArtifactKey("Task_" + state + "0", "0.0.1")); - testTask0.duplicateInputFields(inputFields); - testTask0.duplicateOutputFields(outputFields); - AxTaskParameter parameter00 = - new AxTaskParameter(new AxReferenceKey(testTask0.getKey(), "Parameter0"), "DefaultValue0"); - AxTaskParameter parameter01 = - new AxTaskParameter(new AxReferenceKey(testTask0.getKey(), "Parameter1"), "DefaultValue1"); - AxTaskParameter parameter02 = - new AxTaskParameter(new AxReferenceKey(testTask0.getKey(), "Parameter2"), "DefaultValue2"); - testTask0.getTaskParameters().put(parameter00.getKey().getLocalName(), parameter00); - testTask0.getTaskParameters().put(parameter01.getKey().getLocalName(), parameter01); - testTask0.getTaskParameters().put(parameter02.getKey().getLocalName(), parameter02); - testTask0.setContextAlbumReferences(referenceKeySetList.get(0)); - testTask0.setTaskLogic(getTaskLogic(testTask0, logicReader, axLogicExecutorType, state, "2")); - - AxTask testTask1 = new AxTask(new AxArtifactKey("Task_" + state + "1", "0.0.1")); - testTask1.duplicateInputFields(inputFields); - testTask1.duplicateOutputFields(outputFields); - AxTaskParameter parameter10 = - new AxTaskParameter(new AxReferenceKey(testTask1.getKey(), "Parameter0"), "DefaultValue0"); - AxTaskParameter parameter11 = - new AxTaskParameter(new AxReferenceKey(testTask1.getKey(), "Parameter1"), "DefaultValue1"); - testTask1.getTaskParameters().put(parameter10.getKey().getLocalName(), parameter10); - testTask1.getTaskParameters().put(parameter11.getKey().getLocalName(), parameter11); - testTask1.setContextAlbumReferences(referenceKeySetList.get(1)); - testTask1.setTaskLogic(getTaskLogic(testTask1, logicReader, axLogicExecutorType, state, "3")); - - AxTask testTask2 = new AxTask(new AxArtifactKey("Task_" + state + "2", "0.0.1")); - testTask2.duplicateInputFields(inputFields); - testTask2.duplicateOutputFields(outputFields); - AxTaskParameter parameter20 = - new AxTaskParameter(new AxReferenceKey(testTask2.getKey(), "Parameter0"), "DefaultValue0"); - testTask2.getTaskParameters().put(parameter20.getKey().getLocalName(), parameter20); - testTask2.setContextAlbumReferences(referenceKeySetList.get(2)); - testTask2.setTaskLogic(getTaskLogic(testTask2, logicReader, axLogicExecutorType, state, "0")); - - AxTask testTask3 = new AxTask(new AxArtifactKey("Task_" + state + "3", "0.0.1")); - testTask3.duplicateInputFields(inputFields); - testTask3.duplicateOutputFields(outputFields); - AxTaskParameter parameter30 = - new AxTaskParameter(new AxReferenceKey(testTask3.getKey(), "Parameter0"), "DefaultValue0"); - testTask3.getTaskParameters().put(parameter30.getKey().getLocalName(), parameter30); - testTask3.setContextAlbumReferences(referenceKeySetList.get(THIRD_ENTRY)); - testTask3.setTaskLogic(getTaskLogic(testTask3, logicReader, axLogicExecutorType, state, "1")); - - Map taskMap = new TreeMap(); - taskMap.put(testTask0.getKey(), testTask0); - taskMap.put(testTask1.getKey(), testTask1); - taskMap.put(testTask2.getKey(), testTask2); - taskMap.put(testTask3.getKey(), testTask3); - - return taskMap; - } - - /** - * Gets the task logic. - * - * @param task the task - * @param logicReader the logic reader - * @param logicFlavour the logic flavour - * @param stateName the state name - * @param caseToUse the case to use - * @return the task logic - */ - private AxTaskLogic getTaskLogic(final AxTask task, final AxLogicReader logicReader, final String logicFlavour, - final String stateName, final String caseToUse) { - AxTaskLogic axLogic = - new AxTaskLogic(new AxReferenceKey(task.getKey(), "_TaskLogic"), logicFlavour, logicReader); - - axLogic.setLogic(axLogic.getLogic().replaceAll("", stateName) - .replaceAll("", task.getKey().getName()).replaceAll("", caseToUse)); - - return axLogic; - } -} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelSaver.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelSaver.java deleted file mode 100644 index 6ca644ff4..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/SampleDomainModelSaver.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.test.common.model; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelSaver; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -/** - * This class saves sample domain models to disk in XML and JSON format. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public final class SampleDomainModelSaver { - /** - * Private default constructor to prevent subclassing. - */ - private SampleDomainModelSaver() { - } - - /** - * Write the sample Models to args[0]. - * - * @param args Not used - * @throws ApexException the apex exception - */ - public static void main(final String[] args) throws ApexException { - if (args.length != 1) { - System.err.println("usage: " + SampleDomainModelSaver.class.getCanonicalName() + " modelDirectory"); - return; - } - - // Save Java model - final AxPolicyModel javaPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVA"); - final ApexModelSaver javaModelSaver = new ApexModelSaver(AxPolicyModel.class, javaPolicyModel, args[0]); - javaModelSaver.apexModelWriteJson(); - javaModelSaver.apexModelWriteXml(); - - // Save Javascript model - final AxPolicyModel javascriptPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVASCRIPT"); - final ApexModelSaver javascriptModelSaver = new ApexModelSaver(AxPolicyModel.class, javascriptPolicyModel, args[0]); - javascriptModelSaver.apexModelWriteJson(); - javascriptModelSaver.apexModelWriteXml(); - - // Save JRuby model - final AxPolicyModel jRubyPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JRUBY"); - final ApexModelSaver jRubyModelSaver = new ApexModelSaver(AxPolicyModel.class, jRubyPolicyModel, args[0]); - jRubyModelSaver.apexModelWriteJson(); - jRubyModelSaver.apexModelWriteXml(); - - // Save Jython model - final AxPolicyModel jythonPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JYTHON"); - final ApexModelSaver jythonModelSaver = new ApexModelSaver(AxPolicyModel.class, jythonPolicyModel, args[0]); - jythonModelSaver.apexModelWriteJson(); - jythonModelSaver.apexModelWriteXml(); - - // Save MVEL model - final AxPolicyModel mvelPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - final ApexModelSaver mvelModelSaver = new ApexModelSaver(AxPolicyModel.class, mvelPolicyModel, args[0]); - mvelModelSaver.apexModelWriteJson(); - mvelModelSaver.apexModelWriteXml(); - } - -} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultState_Logic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultState_Logic.java deleted file mode 100644 index d970835d0..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultState_Logic.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.test.common.model.java; - -import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; - -/** - * The Class DefaultState_Logic is default task selection logic in Java. - */ -// CHECKSTYLE:OFF: checkstyle:typeNames -public class DefaultState_Logic { - // CHECKSTYLE:ON: checkstyle:typeNames - /** - * Gets the task. - * - * @param executor the executor - * @return the task - */ - public boolean getTask(final TaskSelectionExecutionContext executor) { - executor.logger.debug(executor.subject.getId()); - executor.logger.debug(executor.getContextAlbum("GlobalContextAlbum").getName()); - executor.subject.getDefaultTaskKey().copyTo(executor.selectedTask); - return true; - } -} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultTask_Logic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultTask_Logic.java deleted file mode 100644 index b22f15d90..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/DefaultTask_Logic.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.test.common.model.java; - -import java.util.Date; -import java.util.Random; - -import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; - -/** - * The Class DefaultTask_Logic is default task logic in Java. - */ -//CHECKSTYLE:OFF: checkstyle:typeNames -public class DefaultTask_Logic { -// CHECKSTYLE:ON: checkstyle:typeNames - private static final int BOUND_FOR_RANDOM_INT = 4; - - /** - * Gets the event. - * - * @param executor the executor - * @return the event - * @throws ApexException the apex exception - */ - public boolean getEvent(final TaskExecutionContext executor) throws ApexException { - executor.logger.debug(executor.subject.getId()); - executor.logger.debug(executor.getContextAlbum("GlobalContextAlbum").getName()); - executor.logger.debug(executor.inFields.toString()); - - final Date timeNow = new Date(); - final Random rand = new Random(); - - if (executor.inFields.containsKey("TestDecideCaseSelected")) { - executor.outFields.put("TestActCaseSelected", new Byte((byte) rand.nextInt(BOUND_FOR_RANDOM_INT))); - executor.outFields.put("TestActStateTime", timeNow.getTime()); - } - else if (executor.inFields.containsKey("TestEstablishCaseSelected")) { - executor.outFields.put("TestDecideCaseSelected", new Byte((byte) rand.nextInt(BOUND_FOR_RANDOM_INT))); - executor.outFields.put("TestDecideStateTime", timeNow.getTime()); - } - else if (executor.inFields.containsKey("TestMatchCaseSelected")) { - executor.outFields.put("TestEstablishCaseSelected", new Byte((byte) rand.nextInt(BOUND_FOR_RANDOM_INT))); - executor.outFields.put("TestEstablishStateTime", timeNow.getTime()); - } - else { - executor.outFields.put("TestMatchCaseSelected", new Byte((byte) rand.nextInt(BOUND_FOR_RANDOM_INT))); - executor.outFields.put("TestMatchStateTime", timeNow.getTime()); - } - - return true; - } -} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalState_Logic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalState_Logic.java deleted file mode 100644 index 2180936ed..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalState_Logic.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.test.common.model.java; - -import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; - -/** - * The Class EvalState_Logic is default evaluation task selection logic in Java. - */ -//CHECKSTYLE:OFF: checkstyle:typeNames -public class EvalState_Logic { - // CHECKSTYLE:ON: checkstyle:typeNames - /** - * Gets the task. - * - * @param executor the executor - * @return the task - */ - public boolean getTask(final TaskSelectionExecutionContext executor) { - executor.logger.debug(executor.subject.getId()); - executor.subject.getDefaultTaskKey().copyTo(executor.selectedTask); - return true; - } -} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalTask_Logic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalTask_Logic.java deleted file mode 100644 index f4fa533f8..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/EvalTask_Logic.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.test.common.model.java; - -import java.util.Date; - -import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; - -/** - * The Class EvalTask_Logic is default evaluation task logic in Java. - */ -public class EvalTask_Logic { - - /** - * Gets the event. - * - * @param executor the executor - * @return the event - * @throws ApexException the apex exception - */ - public boolean getEvent(final TaskExecutionContext executor) throws ApexException { - executor.logger.debug(executor.subject.getId()); - executor.logger.debug(executor.inFields.toString()); - executor.outFields.putAll(executor.inFields); - - final Date timeNow = new Date(); - executor.outFields.put("State3Timestamp", timeNow.getTime()); - executor.logger.debug(executor.outFields.toString()); - return true; - } -} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/package-info.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/package-info.java deleted file mode 100644 index 70c8452b5..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/java/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Contains the Javadomain specific logic for the test domain. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.policy.apex.test.common.model.java; diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/package-info.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/package-info.java deleted file mode 100644 index 9277bd43c..000000000 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/test/common/model/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Executes tests using all the APEX executors on a test domain model. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.policy.apex.test.common.model; diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java new file mode 100644 index 000000000..a36aa1030 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java @@ -0,0 +1,585 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.model; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; +import org.onap.policy.apex.model.policymodel.concepts.AxLogicReader; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicies; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.policymodel.concepts.AxState; +import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput; +import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskOutputType; +import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference; +import org.onap.policy.apex.model.policymodel.concepts.AxTask; +import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic; +import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic; +import org.onap.policy.apex.model.policymodel.concepts.AxTasks; +import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; + +/** + * This class creates sample evaluation Policy Models. + * + * @author John Keeney (john.keeney@ericsson.com) + */ +public class EvalDomainModelFactory { + // Recurring string constants + private static final String ACTION = "Action"; + private static final String CONDITION = "Condition"; + private static final String EVENT = "Event"; + private static final String TASK_SELECTION_LOGIC = "TaskSelectionLogic"; + private static final String JYTHON = "JYTHON"; + private static final String ORIENT = "Orient"; + private static final String STATE_NAME = ""; + private static final String OBSERVE = "Observe"; + private static final String JAVASCRIPT = "JAVASCRIPT"; + private static final String TASK_NAME = ""; + private static final String TASK_LOGIC = "TaskLogic"; + private static final String STATE_NUMBER = ""; + private static final String STATE3_TIMESTAMP = "State3Timestamp"; + private static final String EVENT_NUMBER = "EventNumber"; + private static final String FIRST_EVENT_TIMESTAMP = "FirstEventTimestamp"; + private static final String STATE2_TIMESTAMP = "State2Timestamp"; + private static final String STATE1_TIMESTAMP = "State1Timestamp"; + private static final String TEST_TEMPERATURE = "TestTemperature"; + private static final String SENT_TIMESTAMP = "SentTimestamp"; + private static final String EVENT_TAG = ".events"; + private static final String DEFAULT_VERSION = "0.0.1"; + + private static final int THIRD_MEMBER = 3; + + private static final String PACKAGE = EvalDomainModelFactory.class.getPackage().getName(); + + private String justOneLang = null; + + private final AxContextSchema typeTimestamp; + private final AxContextSchema typeDouble; + private final AxContextSchema typeCounter; + private final AxContextSchemas schemas; + private final AxEvent event0000; + private final AxEvent event0001; + private final AxEvent event0002; + private final AxEvent event0003; + private final AxEvent event0004; + private final AxEvents events; + + /** + * The Constructor for the factory. + */ + public EvalDomainModelFactory() { + this(null); + } + + /** + * The Constructor for the factory that creates models for a single executor language flavour. + * + * @param justOneLang the just one lang + */ + public EvalDomainModelFactory(final String justOneLang) { + this.justOneLang = justOneLang; + + typeTimestamp = new AxContextSchema(new AxArtifactKey("TestTimestamp", DEFAULT_VERSION), "Java", + "java.lang.Long"); + typeDouble = new AxContextSchema(new AxArtifactKey(TEST_TEMPERATURE, DEFAULT_VERSION), "Java", + "java.lang.Double"); + typeCounter = new AxContextSchema(new AxArtifactKey("TestTimestamp", DEFAULT_VERSION), "Java", + "java.lang.Long"); + + schemas = new AxContextSchemas(new AxArtifactKey("TestDatatypes", DEFAULT_VERSION)); + schemas.getSchemasMap().put(typeTimestamp.getKey(), typeTimestamp); + schemas.getSchemasMap().put(typeDouble.getKey(), typeDouble); + schemas.getSchemasMap().put(typeCounter.getKey(), typeCounter); + + event0000 = new AxEvent(new AxArtifactKey("Event0000", DEFAULT_VERSION), PACKAGE + EVENT_TAG); + event0000.getParameterMap().put(SENT_TIMESTAMP, + new AxField(new AxReferenceKey(event0000.getKey(), SENT_TIMESTAMP), typeTimestamp.getKey())); + event0000.getParameterMap().put(TEST_TEMPERATURE, + new AxField(new AxReferenceKey(event0000.getKey(), TEST_TEMPERATURE), typeDouble.getKey())); + event0000.getParameterMap().put(FIRST_EVENT_TIMESTAMP, new AxField( + new AxReferenceKey(event0000.getKey(), FIRST_EVENT_TIMESTAMP), typeTimestamp.getKey())); + event0000.getParameterMap().put(EVENT_NUMBER, + new AxField(new AxReferenceKey(event0000.getKey(), EVENT_NUMBER), typeCounter.getKey())); + + event0001 = new AxEvent(new AxArtifactKey("Event0001", DEFAULT_VERSION), PACKAGE + EVENT_TAG); + event0001.getParameterMap().put(SENT_TIMESTAMP, + new AxField(new AxReferenceKey(event0001.getKey(), SENT_TIMESTAMP), typeTimestamp.getKey())); + event0001.getParameterMap().put(STATE1_TIMESTAMP, + new AxField(new AxReferenceKey(event0001.getKey(), STATE1_TIMESTAMP), typeTimestamp.getKey())); + event0001.getParameterMap().put(TEST_TEMPERATURE, + new AxField(new AxReferenceKey(event0001.getKey(), TEST_TEMPERATURE), typeDouble.getKey())); + event0001.getParameterMap().put(FIRST_EVENT_TIMESTAMP, new AxField( + new AxReferenceKey(event0001.getKey(), FIRST_EVENT_TIMESTAMP), typeTimestamp.getKey())); + event0001.getParameterMap().put(EVENT_NUMBER, + new AxField(new AxReferenceKey(event0001.getKey(), EVENT_NUMBER), typeCounter.getKey())); + + event0002 = new AxEvent(new AxArtifactKey("Event0002", DEFAULT_VERSION), PACKAGE + EVENT_TAG); + event0002.getParameterMap().put(SENT_TIMESTAMP, + new AxField(new AxReferenceKey(event0002.getKey(), SENT_TIMESTAMP), typeTimestamp.getKey())); + event0002.getParameterMap().put(STATE1_TIMESTAMP, + new AxField(new AxReferenceKey(event0002.getKey(), STATE1_TIMESTAMP), typeTimestamp.getKey())); + event0002.getParameterMap().put(STATE2_TIMESTAMP, + new AxField(new AxReferenceKey(event0002.getKey(), STATE2_TIMESTAMP), typeTimestamp.getKey())); + event0002.getParameterMap().put(TEST_TEMPERATURE, + new AxField(new AxReferenceKey(event0002.getKey(), TEST_TEMPERATURE), typeDouble.getKey())); + event0002.getParameterMap().put(FIRST_EVENT_TIMESTAMP, new AxField( + new AxReferenceKey(event0002.getKey(), FIRST_EVENT_TIMESTAMP), typeTimestamp.getKey())); + event0002.getParameterMap().put(EVENT_NUMBER, + new AxField(new AxReferenceKey(event0002.getKey(), EVENT_NUMBER), typeCounter.getKey())); + + event0003 = new AxEvent(new AxArtifactKey("Event0003", DEFAULT_VERSION), PACKAGE + EVENT_TAG); + event0003.getParameterMap().put(SENT_TIMESTAMP, + new AxField(new AxReferenceKey(event0003.getKey(), SENT_TIMESTAMP), typeTimestamp.getKey())); + event0003.getParameterMap().put(STATE1_TIMESTAMP, + new AxField(new AxReferenceKey(event0003.getKey(), STATE1_TIMESTAMP), typeTimestamp.getKey())); + event0003.getParameterMap().put(STATE2_TIMESTAMP, + new AxField(new AxReferenceKey(event0003.getKey(), STATE2_TIMESTAMP), typeTimestamp.getKey())); + event0003.getParameterMap().put(STATE3_TIMESTAMP, + new AxField(new AxReferenceKey(event0003.getKey(), STATE3_TIMESTAMP), typeTimestamp.getKey())); + event0003.getParameterMap().put(TEST_TEMPERATURE, + new AxField(new AxReferenceKey(event0003.getKey(), TEST_TEMPERATURE), typeDouble.getKey())); + event0003.getParameterMap().put(FIRST_EVENT_TIMESTAMP, new AxField( + new AxReferenceKey(event0003.getKey(), FIRST_EVENT_TIMESTAMP), typeTimestamp.getKey())); + event0003.getParameterMap().put(EVENT_NUMBER, + new AxField(new AxReferenceKey(event0003.getKey(), EVENT_NUMBER), typeCounter.getKey())); + + event0004 = new AxEvent(new AxArtifactKey("Event0004", DEFAULT_VERSION), PACKAGE + EVENT_TAG); + event0004.getParameterMap().put(SENT_TIMESTAMP, + new AxField(new AxReferenceKey(event0004.getKey(), SENT_TIMESTAMP), typeTimestamp.getKey())); + event0004.getParameterMap().put(STATE1_TIMESTAMP, + new AxField(new AxReferenceKey(event0004.getKey(), STATE1_TIMESTAMP), typeTimestamp.getKey())); + event0004.getParameterMap().put(STATE2_TIMESTAMP, + new AxField(new AxReferenceKey(event0004.getKey(), STATE2_TIMESTAMP), typeTimestamp.getKey())); + event0004.getParameterMap().put(STATE3_TIMESTAMP, + new AxField(new AxReferenceKey(event0004.getKey(), STATE3_TIMESTAMP), typeTimestamp.getKey())); + event0004.getParameterMap().put("State4Timestamp", + new AxField(new AxReferenceKey(event0004.getKey(), "State4Timestamp"), typeTimestamp.getKey())); + event0004.getParameterMap().put(TEST_TEMPERATURE, + new AxField(new AxReferenceKey(event0004.getKey(), TEST_TEMPERATURE), typeDouble.getKey())); + event0004.getParameterMap().put(FIRST_EVENT_TIMESTAMP, new AxField( + new AxReferenceKey(event0004.getKey(), FIRST_EVENT_TIMESTAMP), typeTimestamp.getKey())); + event0004.getParameterMap().put(EVENT_NUMBER, + new AxField(new AxReferenceKey(event0004.getKey(), EVENT_NUMBER), typeCounter.getKey())); + + events = new AxEvents(new AxArtifactKey("Events", DEFAULT_VERSION)); + events.getEventMap().put(event0000.getKey(), event0000); + events.getEventMap().put(event0001.getKey(), event0001); + events.getEventMap().put(event0002.getKey(), event0002); + events.getEventMap().put(event0003.getKey(), event0003); + events.getEventMap().put(event0004.getKey(), event0004); + } + + /** + * Get a sample OODA policy model. + * + * @return the sample policy model + */ + public AxPolicyModel getOodaPolicyModel() { + final AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", "0.0.1")); + + final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE) + .setDefaultLogic("EvalTask_Logic"); + + final AxTask obTask = new AxTask(new AxArtifactKey("Task_Observe_0", "0.0.1")); + obTask.duplicateInputFields(event0000.getParameterMap()); + obTask.duplicateOutputFields(event0001.getParameterMap()); + final AxTaskLogic obAxLogic = new AxTaskLogic(obTask.getKey(), TASK_LOGIC, + (justOneLang == null ? "JRUBY" : justOneLang), logicReader); + obAxLogic.setLogic(obAxLogic.getLogic().replaceAll(STATE_NAME, OBSERVE) + .replaceAll(TASK_NAME, obTask.getKey().getName()).replaceAll(STATE_NUMBER, "1")); + obTask.setTaskLogic(obAxLogic); + + final AxTask orTask = new AxTask(new AxArtifactKey("Task_Orient_0", "0.0.1")); + orTask.duplicateInputFields(event0001.getParameterMap()); + orTask.duplicateOutputFields(event0002.getParameterMap()); + final AxTaskLogic orAxLogic = new AxTaskLogic(orTask.getKey(), TASK_LOGIC, + (justOneLang == null ? JAVASCRIPT : justOneLang), logicReader); + orAxLogic.setLogic(orAxLogic.getLogic().replaceAll(STATE_NAME, ORIENT) + .replaceAll(TASK_NAME, orTask.getKey().getName()).replaceAll(STATE_NUMBER, "2")); + orTask.setTaskLogic(orAxLogic); + + final AxTask dTask = new AxTask(new AxArtifactKey("Task_Decide_0", "0.0.1")); + dTask.duplicateInputFields(event0002.getParameterMap()); + dTask.duplicateOutputFields(event0003.getParameterMap()); + final AxTaskLogic dAxLogic = new AxTaskLogic(dTask.getKey(), TASK_LOGIC, + (justOneLang == null ? "MVEL" : justOneLang), logicReader); + dAxLogic.setLogic(dAxLogic.getLogic().replaceAll(STATE_NAME, ORIENT) + .replaceAll(TASK_NAME, dTask.getKey().getName()).replaceAll(STATE_NUMBER, "3")); + dTask.setTaskLogic(dAxLogic); + + final AxTask aTask = new AxTask(new AxArtifactKey("Task_Act_0", "0.0.1")); + aTask.duplicateInputFields(event0003.getParameterMap()); + aTask.duplicateOutputFields(event0004.getParameterMap()); + final AxTaskLogic aAxLogic = new AxTaskLogic(aTask.getKey(), TASK_LOGIC, + (justOneLang == null ? "JAVA" : justOneLang), logicReader); + aAxLogic.setLogic(aAxLogic.getLogic().replaceAll(STATE_NAME, "Act") + .replaceAll(TASK_NAME, aTask.getKey().getName()).replaceAll(STATE_NUMBER, "4")); + aTask.setTaskLogic(aAxLogic); + + tasks.getTaskMap().put(obTask.getKey(), obTask); + tasks.getTaskMap().put(orTask.getKey(), orTask); + tasks.getTaskMap().put(dTask.getKey(), dTask); + tasks.getTaskMap().put(aTask.getKey(), aTask); + + final Set obTasks = new TreeSet<>(); + final Set orTasks = new TreeSet<>(); + final Set decTasks = new TreeSet<>(); + final Set actTasks = new TreeSet<>(); + + for (final AxTask task : tasks.getTaskMap().values()) { + if (task.getKey().getName().contains(OBSERVE)) { + obTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(ORIENT)) { + orTasks.add(task.getKey()); + } + if (task.getKey().getName().contains("Decide")) { + decTasks.add(task.getKey()); + } + if (task.getKey().getName().contains("Act")) { + actTasks.add(task.getKey()); + } + } + final List> taskReferenceList = new ArrayList<>(); + taskReferenceList.add(obTasks); + taskReferenceList.add(orTasks); + taskReferenceList.add(decTasks); + taskReferenceList.add(actTasks); + + final List p0InEventList = new ArrayList<>(); + p0InEventList.add(event0000.getKey()); + p0InEventList.add(event0001.getKey()); + p0InEventList.add(event0002.getKey()); + p0InEventList.add(event0003.getKey()); + + final List p0OutEventList = new ArrayList<>(); + p0OutEventList.add(event0001.getKey()); + p0OutEventList.add(event0002.getKey()); + p0OutEventList.add(event0003.getKey()); + p0OutEventList.add(event0004.getKey()); + + final List p0defaultTaskList = new ArrayList<>(); + p0defaultTaskList.add(tasks.get("Task_Observe_0").getKey()); + p0defaultTaskList.add(tasks.get("Task_Orient_0").getKey()); + p0defaultTaskList.add(tasks.get("Task_Decide_0").getKey()); + p0defaultTaskList.add(tasks.get("Task_Act_0").getKey()); + + final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("OODAPolicy_0", "0.0.1")); + final List axLogicExecutorTypeList = Arrays.asList((justOneLang == null ? JAVASCRIPT : justOneLang), + (justOneLang == null ? "MVEL" : justOneLang), (justOneLang == null ? JYTHON : justOneLang), + (justOneLang == null ? "JRUBY" : justOneLang)); + policy0.setStateMap(getOodaStateMap(policy0.getKey(), p0InEventList, p0OutEventList, axLogicExecutorTypeList, + p0defaultTaskList, taskReferenceList)); + policy0.setFirstState(policy0.getStateMap().get(OBSERVE).getKey().getLocalName()); + + final AxPolicies policies = new AxPolicies(new AxArtifactKey("OODAPolicies", "0.0.1")); + policies.getPolicyMap().put(policy0.getKey(), policy0); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", "0.0.1")); + final AxPolicyModel policyModel = new AxPolicyModel(new AxArtifactKey("EvaluationPolicyModel_OODA", "0.0.1")); + policyModel.setPolicies(policies); + policyModel.setEvents(events); + policyModel.setTasks(tasks); + policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", "0.0.1"))); + policyModel.setSchemas(schemas); + policyModel.setKeyInformation(keyInformation); + policyModel.getKeyInformation().generateKeyInfo(policyModel); + + final AxValidationResult result = policyModel.validate(new AxValidationResult()); + if (!result.isOk()) { + throw new ApexRuntimeException("model " + policyModel.getId() + " is not valid" + result); + } + return policyModel; + } + + /** + * Gets the OODA state map. + * + * @param policyKey the policy key + * @param inEventKeyList the in event key list + * @param outEventKeyList the out event key list + * @param axLogicExecutorTypeList the ax logic executor type list + * @param defaultTaskList the default task list + * @param taskKeySetList the task key set list + * @return the OODA state map + */ + private Map getOodaStateMap(final AxArtifactKey policyKey, + final List inEventKeyList, final List outEventKeyList, + final List axLogicExecutorTypeList, final List defaultTaskList, + final List> taskKeySetList) { + final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE) + .setDefaultLogic("EvalState_Logic"); + + final AxState actState = new AxState(new AxReferenceKey(policyKey, "Act")); + actState.setTrigger(inEventKeyList.get(THIRD_MEMBER)); + final AxStateOutput act2Out = new AxStateOutput(new AxReferenceKey(actState.getKey(), "Act2Out"), + outEventKeyList.get(THIRD_MEMBER), AxReferenceKey.getNullKey()); + actState.getStateOutputs().put(act2Out.getKey().getLocalName(), act2Out); + actState.setTaskSelectionLogic(new AxTaskSelectionLogic(actState.getKey(), TASK_SELECTION_LOGIC, + axLogicExecutorTypeList.get(THIRD_MEMBER), logicReader)); + actState.setDefaultTask(defaultTaskList.get(THIRD_MEMBER)); + for (final AxArtifactKey taskKey : taskKeySetList.get(THIRD_MEMBER)) { + actState.getTaskReferences().put(taskKey, + new AxStateTaskReference(new AxReferenceKey(actState.getKey(), taskKey.getName()), + AxStateTaskOutputType.DIRECT, act2Out.getKey())); + } + + final AxState decState = new AxState(new AxReferenceKey(policyKey, "Decide")); + decState.setTrigger(inEventKeyList.get(2)); + final AxStateOutput dec2Act = new AxStateOutput(new AxReferenceKey(decState.getKey(), "Dec2Act"), + outEventKeyList.get(2), actState.getKey()); + decState.getStateOutputs().put(dec2Act.getKey().getLocalName(), dec2Act); + decState.setTaskSelectionLogic(new AxTaskSelectionLogic(decState.getKey(), TASK_SELECTION_LOGIC, + axLogicExecutorTypeList.get(2), logicReader)); + decState.setDefaultTask(defaultTaskList.get(2)); + for (final AxArtifactKey taskKey : taskKeySetList.get(2)) { + decState.getTaskReferences().put(taskKey, + new AxStateTaskReference(new AxReferenceKey(decState.getKey(), taskKey.getName()), + AxStateTaskOutputType.DIRECT, dec2Act.getKey())); + } + + final AxState orState = new AxState(new AxReferenceKey(policyKey, ORIENT)); + orState.setTrigger(inEventKeyList.get(1)); + final AxStateOutput or2Dec = new AxStateOutput(new AxReferenceKey(orState.getKey(), "Or2Dec"), + outEventKeyList.get(1), decState.getKey()); + orState.getStateOutputs().put(or2Dec.getKey().getLocalName(), or2Dec); + orState.setTaskSelectionLogic(new AxTaskSelectionLogic(orState.getKey(), TASK_SELECTION_LOGIC, + axLogicExecutorTypeList.get(1), logicReader)); + orState.setDefaultTask(defaultTaskList.get(1)); + for (final AxArtifactKey taskKey : taskKeySetList.get(1)) { + orState.getTaskReferences().put(taskKey, + new AxStateTaskReference(new AxReferenceKey(orState.getKey(), taskKey.getName()), + AxStateTaskOutputType.DIRECT, or2Dec.getKey())); + } + + final AxState obState = new AxState(new AxReferenceKey(policyKey, OBSERVE)); + obState.setTrigger(inEventKeyList.get(0)); + final AxStateOutput ob2Or = new AxStateOutput(new AxReferenceKey(obState.getKey(), "Ob2Or"), + outEventKeyList.get(0), orState.getKey()); + obState.getStateOutputs().put(ob2Or.getKey().getLocalName(), ob2Or); + obState.setTaskSelectionLogic(new AxTaskSelectionLogic(obState.getKey(), TASK_SELECTION_LOGIC, + axLogicExecutorTypeList.get(0), logicReader)); + obState.setDefaultTask(defaultTaskList.get(0)); + for (final AxArtifactKey taskKey : taskKeySetList.get(0)) { + obState.getTaskReferences().put(taskKey, + new AxStateTaskReference(new AxReferenceKey(obState.getKey(), taskKey.getName()), + AxStateTaskOutputType.DIRECT, ob2Or.getKey())); + } + + final Map stateMap = new TreeMap<>(); + stateMap.put(obState.getKey().getLocalName(), obState); + stateMap.put(orState.getKey().getLocalName(), orState); + stateMap.put(decState.getKey().getLocalName(), decState); + stateMap.put(actState.getKey().getLocalName(), actState); + + return stateMap; + } + + /** + * Get a sample ECA policy model. + * + * @return the sample policy model + */ + public AxPolicyModel getEcaPolicyModel() { + + final AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", "0.0.1")); + + final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE) + .setDefaultLogic("EvalTask_Logic"); + + final AxTask eTask = new AxTask(new AxArtifactKey("Task_Event_0", "0.0.1")); + eTask.duplicateInputFields(event0000.getParameterMap()); + eTask.duplicateOutputFields(event0001.getParameterMap()); + final AxTaskLogic eAxLogic = new AxTaskLogic(eTask.getKey(), TASK_LOGIC, + (justOneLang == null ? JYTHON : justOneLang), logicReader); + eAxLogic.setLogic(eAxLogic.getLogic().replaceAll(STATE_NAME, EVENT) + .replaceAll(TASK_NAME, eTask.getKey().getName()).replaceAll(STATE_NUMBER, "1")); + eTask.setTaskLogic(eAxLogic); + + final AxTask cTask = new AxTask(new AxArtifactKey("Task_Condition_0", "0.0.1")); + cTask.duplicateInputFields(event0001.getParameterMap()); + cTask.duplicateOutputFields(event0002.getParameterMap()); + final AxTaskLogic cAxLogic = new AxTaskLogic(cTask.getKey(), TASK_LOGIC, + (justOneLang == null ? JAVASCRIPT : justOneLang), logicReader); + cAxLogic.setLogic(cAxLogic.getLogic().replaceAll(STATE_NAME, CONDITION) + .replaceAll(TASK_NAME, cTask.getKey().getName()).replaceAll(STATE_NUMBER, "2")); + cTask.setTaskLogic(cAxLogic); + + final AxTask aTask = new AxTask(new AxArtifactKey("Task_Action_0", "0.0.1")); + aTask.duplicateInputFields(event0002.getParameterMap()); + aTask.duplicateOutputFields(event0003.getParameterMap()); + final AxTaskLogic aAxLogic = new AxTaskLogic(aTask.getKey(), TASK_LOGIC, + (justOneLang == null ? "JAVA" : justOneLang), logicReader); + aAxLogic.setLogic(aAxLogic.getLogic().replaceAll(STATE_NAME, ACTION) + .replaceAll(TASK_NAME, aTask.getKey().getName()).replaceAll(STATE_NUMBER, "3")); + aTask.setTaskLogic(aAxLogic); + + tasks.getTaskMap().put(eTask.getKey(), eTask); + tasks.getTaskMap().put(cTask.getKey(), cTask); + tasks.getTaskMap().put(aTask.getKey(), aTask); + + final Set eventTasks = new TreeSet<>(); + final Set conditionTasks = new TreeSet<>(); + final Set actionTasks = new TreeSet<>(); + + for (final AxTask task : tasks.getTaskMap().values()) { + if (task.getKey().getName().contains(EVENT)) { + eventTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(CONDITION)) { + conditionTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(ACTION)) { + actionTasks.add(task.getKey()); + } + } + final List> taskReferenceList = new ArrayList<>(); + taskReferenceList.add(eventTasks); + taskReferenceList.add(conditionTasks); + taskReferenceList.add(actionTasks); + + final List p0InEventList = new ArrayList<>(); + p0InEventList.add(event0000.getKey()); + p0InEventList.add(event0001.getKey()); + p0InEventList.add(event0002.getKey()); + + final List p0OutEventList = new ArrayList<>(); + p0OutEventList.add(event0001.getKey()); + p0OutEventList.add(event0002.getKey()); + p0OutEventList.add(event0003.getKey()); + + final List p0defaultTaskList = new ArrayList<>(); + p0defaultTaskList.add(tasks.get("Task_Event_0").getKey()); + p0defaultTaskList.add(tasks.get("Task_Condition_0").getKey()); + p0defaultTaskList.add(tasks.get("Task_Action_0").getKey()); + + final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("ECAPolicy_0", "0.0.1")); + final List axLogicExecutorTypeList = Arrays.asList((justOneLang == null ? JAVASCRIPT : justOneLang), + (justOneLang == null ? "MVEL" : justOneLang), (justOneLang == null ? JYTHON : justOneLang)); + policy0.setStateMap(getEcaStateMap(policy0.getKey(), p0InEventList, p0OutEventList, axLogicExecutorTypeList, + p0defaultTaskList, taskReferenceList)); + policy0.setFirstState(policy0.getStateMap().get(EVENT).getKey().getLocalName()); + + final AxPolicies policies = new AxPolicies(new AxArtifactKey("ECAPolicies", "0.0.1")); + policies.getPolicyMap().put(policy0.getKey(), policy0); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", "0.0.1")); + final AxPolicyModel policyModel = new AxPolicyModel(new AxArtifactKey("EvaluationPolicyModel_ECA", "0.0.1")); + policyModel.setPolicies(policies); + policyModel.setEvents(events); + policyModel.setTasks(tasks); + policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", "0.0.1"))); + policyModel.setSchemas(schemas); + policyModel.setKeyInformation(keyInformation); + policyModel.getKeyInformation().generateKeyInfo(policyModel); + + final AxValidationResult result = policyModel.validate(new AxValidationResult()); + if (!result.isOk()) { + throw new ApexRuntimeException("model " + policyModel.getId() + " is not valid" + result); + } + return policyModel; + } + + /** + * Gets the ECA state map. + * + * @param policyKey the policy key + * @param inEventKeyList the in event key list + * @param outEventKeyList the out event key list + * @param axLogicExecutorTypeList the ax logic executor type list + * @param defaultTaskList the default task list + * @param taskKeySetList the task key set list + * @return the ECA state map + */ + private Map getEcaStateMap(final AxArtifactKey policyKey, final List inEventKeyList, + final List outEventKeyList, final List axLogicExecutorTypeList, + final List defaultTaskList, final List> taskKeySetList) { + final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE) + .setDefaultLogic("EvalState_Logic"); + + final AxState actionState = new AxState(new AxReferenceKey(policyKey, ACTION)); + actionState.setTrigger(inEventKeyList.get(2)); + final AxStateOutput action2Out = new AxStateOutput(actionState.getKey(), AxReferenceKey.getNullKey(), + outEventKeyList.get(2)); + actionState.getStateOutputs().put(action2Out.getKey().getLocalName(), action2Out); + actionState.setTaskSelectionLogic(new AxTaskSelectionLogic(actionState.getKey(), TASK_SELECTION_LOGIC, + axLogicExecutorTypeList.get(2), logicReader)); + actionState.setDefaultTask(defaultTaskList.get(2)); + for (final AxArtifactKey taskKey : taskKeySetList.get(2)) { + actionState.getTaskReferences().put(taskKey, + new AxStateTaskReference(new AxReferenceKey(actionState.getKey(), taskKey.getName()), + AxStateTaskOutputType.DIRECT, action2Out.getKey())); + } + + final AxState conditionState = new AxState(new AxReferenceKey(policyKey, CONDITION)); + conditionState.setTrigger(inEventKeyList.get(1)); + final AxStateOutput condition2Action = new AxStateOutput(conditionState.getKey(), actionState.getKey(), + outEventKeyList.get(1)); + conditionState.getStateOutputs().put(condition2Action.getKey().getLocalName(), condition2Action); + conditionState.setTaskSelectionLogic(new AxTaskSelectionLogic(conditionState.getKey(), TASK_SELECTION_LOGIC, + axLogicExecutorTypeList.get(1), logicReader)); + conditionState.setDefaultTask(defaultTaskList.get(1)); + for (final AxArtifactKey taskKey : taskKeySetList.get(1)) { + conditionState.getTaskReferences().put(taskKey, + new AxStateTaskReference(new AxReferenceKey(conditionState.getKey(), taskKey.getName()), + AxStateTaskOutputType.DIRECT, condition2Action.getKey())); + } + + final AxState eventState = new AxState(new AxReferenceKey(policyKey, EVENT)); + eventState.setTrigger(inEventKeyList.get(0)); + final AxStateOutput event2Condition = new AxStateOutput(eventState.getKey(), conditionState.getKey(), + outEventKeyList.get(0)); + eventState.getStateOutputs().put(event2Condition.getKey().getLocalName(), event2Condition); + eventState.setTaskSelectionLogic(new AxTaskSelectionLogic(eventState.getKey(), TASK_SELECTION_LOGIC, + axLogicExecutorTypeList.get(0), logicReader)); + eventState.setDefaultTask(defaultTaskList.get(0)); + for (final AxArtifactKey taskKey : taskKeySetList.get(0)) { + eventState.getTaskReferences().put(taskKey, + new AxStateTaskReference(new AxReferenceKey(eventState.getKey(), taskKey.getName()), + AxStateTaskOutputType.DIRECT, event2Condition.getKey())); + } + + final Map stateMap = new TreeMap<>(); + stateMap.put(eventState.getKey().getLocalName(), eventState); + stateMap.put(conditionState.getKey().getLocalName(), conditionState); + stateMap.put(actionState.getKey().getLocalName(), actionState); + + return stateMap; + } + +} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelFactory.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelFactory.java new file mode 100644 index 000000000..5e9958ff0 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelFactory.java @@ -0,0 +1,776 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; +import org.onap.policy.apex.model.policymodel.concepts.AxLogicReader; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicies; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.policymodel.concepts.AxState; +import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput; +import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskOutputType; +import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference; +import org.onap.policy.apex.model.policymodel.concepts.AxTask; +import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic; +import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter; +import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic; +import org.onap.policy.apex.model.policymodel.concepts.AxTasks; +import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; + +/** + * This class creates sample Policy Models. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class SampleDomainModelFactory { + // Recurring string constants + private static final String TASK = "Task_"; + private static final String PARAMETER2 = "Parameter2"; + private static final String PARAMETER1 = "Parameter1"; + private static final String DEFAULT_VALUE2 = "DefaultValue2"; + private static final String DEFAULT_VALUE1 = "DefaultValue1"; + private static final String PARAMETER0 = "Parameter0"; + private static final String DEFAULT_VALUE0 = "DefaultValue0"; + private static final String TASK_SELECTION_LIGIC = "TaskSelectionLigic"; + private static final String TEST_ACT_STATE_TIME = "TestActStateTime"; + private static final String TEST_ACT_CASE_SELECTED = "TestActCaseSelected"; + private static final String TEST_DECIDE_STATE_TIME = "TestDecideStateTime"; + private static final String TEST_DECIDE_CASE_SELECTED = "TestDecideCaseSelected"; + private static final String TEST_ESTABLISH_STATE_TIME = "TestEstablishStateTime"; + private static final String TEST_ESTABLISH_CASE_SELECTED = "TestEstablishCaseSelected"; + private static final String DECIDE = "Decide"; + private static final String TEST_MATCH_STATE_TIME = "TestMatchStateTime"; + private static final String TEST_MATCH_CASE_SELECTED = "TestMatchCaseSelected"; + private static final String ESTABLISH = "Establish"; + private static final String TEST_MATCH_CASE = "TestMatchCase"; + private static final String MATCH = "Match"; + private static final String DEFAULT_SOURCE = "Outside"; + private static final String DEFAULT_NAMESPACE = "org.onap.policy.apex.sample.events"; + private static final String TEST_TEMPERATURE = "TestTemperature"; + private static final String TEST_TIMESTAMP = "TestTimestamp"; + private static final String TEST_SLOGAN = "TestSlogan"; + private static final String DEFAULT_VERSION = "0.0.1"; + + private static final int THIRD_ENTRY = 3; + + /** + * Get a sample policy model. + * + * @param axLogicExecutorType The type of logic executor, the scripting language being used + * @return the sample policy model + */ + // CHECKSTYLE:OFF: checkstyle:maximumMethodLength + public AxPolicyModel getSamplePolicyModel(final String axLogicExecutorType) { + AxContextSchema testSlogan = new AxContextSchema(new AxArtifactKey(TEST_SLOGAN, DEFAULT_VERSION), "Java", + "java.lang.String"); + AxContextSchema testCase = new AxContextSchema(new AxArtifactKey("TestCase", DEFAULT_VERSION), "Java", + "java.lang.Byte"); + AxContextSchema testTimestamp = new AxContextSchema(new AxArtifactKey(TEST_TIMESTAMP, DEFAULT_VERSION), "Java", + "java.lang.Long"); + AxContextSchema testTemperature = new AxContextSchema(new AxArtifactKey(TEST_TEMPERATURE, DEFAULT_VERSION), + "Java", "java.lang.Double"); + + AxContextSchema testContextItem000 = new AxContextSchema( + new AxArtifactKey("TestContextItem000", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem000"); + AxContextSchema testContextItem001 = new AxContextSchema( + new AxArtifactKey("TestContextItem001", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem001"); + AxContextSchema testContextItem002 = new AxContextSchema( + new AxArtifactKey("TestContextItem002", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem002"); + AxContextSchema testContextItem003 = new AxContextSchema( + new AxArtifactKey("TestContextItem003", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem003"); + AxContextSchema testContextItem004 = new AxContextSchema( + new AxArtifactKey("TestContextItem004", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem004"); + AxContextSchema testContextItem005 = new AxContextSchema( + new AxArtifactKey("TestContextItem005", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem005"); + AxContextSchema testContextItem006 = new AxContextSchema( + new AxArtifactKey("TestContextItem006", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem006"); + AxContextSchema testContextItem007 = new AxContextSchema( + new AxArtifactKey("TestContextItem007", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem007"); + AxContextSchema testContextItem008 = new AxContextSchema( + new AxArtifactKey("TestContextItem008", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem008"); + AxContextSchema testContextItem009 = new AxContextSchema( + new AxArtifactKey("TestContextItem009", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem009"); + AxContextSchema testContextItem00A = new AxContextSchema( + new AxArtifactKey("TestContextItem00A", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem00A"); + AxContextSchema testContextItem00B = new AxContextSchema( + new AxArtifactKey("TestContextItem00B", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem00B"); + AxContextSchema testContextItem00C = new AxContextSchema( + new AxArtifactKey("TestContextItem00C", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestContextItem00C"); + + AxContextSchema testPolicyContextItem = new AxContextSchema( + new AxArtifactKey("TestPolicyContextItem", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestPolicyContextItem"); + AxContextSchema testGlobalContextItem = new AxContextSchema( + new AxArtifactKey("TestGlobalContextItem", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestGlobalContextItem"); + AxContextSchema testExternalContextItem = new AxContextSchema( + new AxArtifactKey("TestExternalContextItem", DEFAULT_VERSION), "Java", + "org.onap.policy.apex.context.test.concepts.TestExternalContextItem"); + + AxContextSchemas axContextSchemas = new AxContextSchemas(new AxArtifactKey("TestDatatypes", DEFAULT_VERSION)); + axContextSchemas.getSchemasMap().put(testSlogan.getKey(), testSlogan); + axContextSchemas.getSchemasMap().put(testCase.getKey(), testCase); + axContextSchemas.getSchemasMap().put(testTimestamp.getKey(), testTimestamp); + axContextSchemas.getSchemasMap().put(testTemperature.getKey(), testTemperature); + + axContextSchemas.getSchemasMap().put(testContextItem000.getKey(), testContextItem000); + axContextSchemas.getSchemasMap().put(testContextItem001.getKey(), testContextItem001); + axContextSchemas.getSchemasMap().put(testContextItem002.getKey(), testContextItem002); + axContextSchemas.getSchemasMap().put(testContextItem003.getKey(), testContextItem003); + axContextSchemas.getSchemasMap().put(testContextItem004.getKey(), testContextItem004); + axContextSchemas.getSchemasMap().put(testContextItem005.getKey(), testContextItem005); + axContextSchemas.getSchemasMap().put(testContextItem006.getKey(), testContextItem006); + axContextSchemas.getSchemasMap().put(testContextItem007.getKey(), testContextItem007); + axContextSchemas.getSchemasMap().put(testContextItem008.getKey(), testContextItem008); + axContextSchemas.getSchemasMap().put(testContextItem009.getKey(), testContextItem009); + axContextSchemas.getSchemasMap().put(testContextItem00A.getKey(), testContextItem00A); + axContextSchemas.getSchemasMap().put(testContextItem00B.getKey(), testContextItem00B); + axContextSchemas.getSchemasMap().put(testContextItem00C.getKey(), testContextItem00C); + + axContextSchemas.getSchemasMap().put(testPolicyContextItem.getKey(), testPolicyContextItem); + axContextSchemas.getSchemasMap().put(testGlobalContextItem.getKey(), testGlobalContextItem); + axContextSchemas.getSchemasMap().put(testExternalContextItem.getKey(), testExternalContextItem); + + AxEvent event0000 = new AxEvent(new AxArtifactKey("Event0000", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0000.setSource(DEFAULT_SOURCE); + event0000.setTarget(MATCH); + event0000.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0000.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0000.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0000.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0000.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0000.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0000.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0000.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + + AxEvent event0001 = new AxEvent(new AxArtifactKey("Event0001", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0001.setSource(MATCH); + event0001.setTarget(ESTABLISH); + event0001.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0001.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0001.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0001.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0001.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0001.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0001.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0001.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0001.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0001.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0001.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0001.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + + AxEvent event0002 = new AxEvent(new AxArtifactKey("Event0002", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0002.setSource(ESTABLISH); + event0002.setTarget(DECIDE); + event0002.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0002.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0002.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0002.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0002.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0002.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0002.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0002.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0002.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0002.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0002.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0002.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + event0002.getParameterMap().put(TEST_ESTABLISH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0002.getKey(), TEST_ESTABLISH_CASE_SELECTED), testCase.getKey())); + event0002.getParameterMap().put(TEST_ESTABLISH_STATE_TIME, new AxField( + new AxReferenceKey(event0002.getKey(), TEST_ESTABLISH_STATE_TIME), testTimestamp.getKey())); + + AxEvent event0003 = new AxEvent(new AxArtifactKey("Event0003", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0003.setSource(DECIDE); + event0003.setTarget("Act"); + event0003.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0003.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0003.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0003.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0003.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0003.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0003.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0003.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0003.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0003.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0003.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0003.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + event0003.getParameterMap().put(TEST_ESTABLISH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0003.getKey(), TEST_ESTABLISH_CASE_SELECTED), testCase.getKey())); + event0003.getParameterMap().put(TEST_ESTABLISH_STATE_TIME, new AxField( + new AxReferenceKey(event0003.getKey(), TEST_ESTABLISH_STATE_TIME), testTimestamp.getKey())); + event0003.getParameterMap().put(TEST_DECIDE_CASE_SELECTED, new AxField( + new AxReferenceKey(event0003.getKey(), TEST_DECIDE_CASE_SELECTED), testCase.getKey())); + event0003.getParameterMap().put(TEST_DECIDE_STATE_TIME, new AxField( + new AxReferenceKey(event0003.getKey(), TEST_DECIDE_STATE_TIME), testTimestamp.getKey())); + + AxEvent event0004 = new AxEvent(new AxArtifactKey("Event0004", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0004.setSource("Act"); + event0004.setTarget(DEFAULT_SOURCE); + event0004.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0004.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0004.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0004.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0004.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0004.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0004.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0004.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0004.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + event0004.getParameterMap().put(TEST_ESTABLISH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_ESTABLISH_CASE_SELECTED), testCase.getKey())); + event0004.getParameterMap().put(TEST_ESTABLISH_STATE_TIME, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_ESTABLISH_STATE_TIME), testTimestamp.getKey())); + event0004.getParameterMap().put(TEST_DECIDE_CASE_SELECTED, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_DECIDE_CASE_SELECTED), testCase.getKey())); + event0004.getParameterMap().put(TEST_DECIDE_STATE_TIME, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_DECIDE_STATE_TIME), testTimestamp.getKey())); + event0004.getParameterMap().put(TEST_ACT_CASE_SELECTED, + new AxField(new AxReferenceKey(event0004.getKey(), TEST_ACT_CASE_SELECTED), testCase.getKey())); + event0004.getParameterMap().put(TEST_ACT_STATE_TIME, new AxField( + new AxReferenceKey(event0004.getKey(), TEST_ACT_STATE_TIME), testTimestamp.getKey())); + + AxEvent event0100 = new AxEvent(new AxArtifactKey("Event0100", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0100.setSource(DEFAULT_SOURCE); + event0100.setTarget(MATCH); + event0100.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0100.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0100.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0100.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0100.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0100.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0100.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0100.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + + AxEvent event0101 = new AxEvent(new AxArtifactKey("Event0101", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0101.setSource(MATCH); + event0101.setTarget(ESTABLISH); + event0101.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0101.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0101.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0101.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0101.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0101.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0101.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0101.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0101.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0101.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0101.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0101.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + + AxEvent event0102 = new AxEvent(new AxArtifactKey("Event0102", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0102.setSource(ESTABLISH); + event0102.setTarget(DECIDE); + event0102.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0102.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0102.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0102.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0102.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0102.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0102.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0102.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0102.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0102.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0102.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0102.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + event0102.getParameterMap().put(TEST_ESTABLISH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0102.getKey(), TEST_ESTABLISH_CASE_SELECTED), testCase.getKey())); + event0102.getParameterMap().put(TEST_ESTABLISH_STATE_TIME, new AxField( + new AxReferenceKey(event0102.getKey(), TEST_ESTABLISH_STATE_TIME), testTimestamp.getKey())); + + AxEvent event0103 = new AxEvent(new AxArtifactKey("Event0103", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0103.setSource(DECIDE); + event0103.setTarget("Act"); + event0103.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0103.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0103.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0103.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0103.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0103.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0103.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0103.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0103.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0103.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0103.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0103.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + event0103.getParameterMap().put(TEST_ESTABLISH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0103.getKey(), TEST_ESTABLISH_CASE_SELECTED), testCase.getKey())); + event0103.getParameterMap().put(TEST_ESTABLISH_STATE_TIME, new AxField( + new AxReferenceKey(event0103.getKey(), TEST_ESTABLISH_STATE_TIME), testTimestamp.getKey())); + event0103.getParameterMap().put(TEST_DECIDE_CASE_SELECTED, new AxField( + new AxReferenceKey(event0103.getKey(), TEST_DECIDE_CASE_SELECTED), testCase.getKey())); + event0103.getParameterMap().put(TEST_DECIDE_STATE_TIME, new AxField( + new AxReferenceKey(event0103.getKey(), TEST_DECIDE_STATE_TIME), testTimestamp.getKey())); + + AxEvent event0104 = new AxEvent(new AxArtifactKey("Event0104", DEFAULT_VERSION), + DEFAULT_NAMESPACE); + event0104.setSource("Act"); + event0104.setTarget(DEFAULT_SOURCE); + event0104.getParameterMap().put(TEST_SLOGAN, + new AxField(new AxReferenceKey(event0104.getKey(), TEST_SLOGAN), testSlogan.getKey())); + event0104.getParameterMap().put(TEST_MATCH_CASE, + new AxField(new AxReferenceKey(event0104.getKey(), TEST_MATCH_CASE), testCase.getKey())); + event0104.getParameterMap().put(TEST_TIMESTAMP, + new AxField(new AxReferenceKey(event0104.getKey(), TEST_TIMESTAMP), testTimestamp.getKey())); + event0104.getParameterMap().put(TEST_TEMPERATURE, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_TEMPERATURE), testTemperature.getKey())); + event0104.getParameterMap().put(TEST_MATCH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_MATCH_CASE_SELECTED), testCase.getKey())); + event0104.getParameterMap().put(TEST_MATCH_STATE_TIME, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_MATCH_STATE_TIME), testTimestamp.getKey())); + event0104.getParameterMap().put(TEST_ESTABLISH_CASE_SELECTED, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_ESTABLISH_CASE_SELECTED), testCase.getKey())); + event0104.getParameterMap().put(TEST_ESTABLISH_STATE_TIME, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_ESTABLISH_STATE_TIME), testTimestamp.getKey())); + event0104.getParameterMap().put(TEST_DECIDE_CASE_SELECTED, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_DECIDE_CASE_SELECTED), testCase.getKey())); + event0104.getParameterMap().put(TEST_DECIDE_STATE_TIME, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_DECIDE_STATE_TIME), testTimestamp.getKey())); + event0104.getParameterMap().put(TEST_ACT_CASE_SELECTED, + new AxField(new AxReferenceKey(event0104.getKey(), TEST_ACT_CASE_SELECTED), testCase.getKey())); + event0104.getParameterMap().put(TEST_ACT_STATE_TIME, new AxField( + new AxReferenceKey(event0104.getKey(), TEST_ACT_STATE_TIME), testTimestamp.getKey())); + + AxEvents events = new AxEvents(new AxArtifactKey("Events", DEFAULT_VERSION)); + events.getEventMap().put(event0000.getKey(), event0000); + events.getEventMap().put(event0001.getKey(), event0001); + events.getEventMap().put(event0002.getKey(), event0002); + events.getEventMap().put(event0003.getKey(), event0003); + events.getEventMap().put(event0004.getKey(), event0004); + events.getEventMap().put(event0100.getKey(), event0100); + events.getEventMap().put(event0101.getKey(), event0101); + events.getEventMap().put(event0102.getKey(), event0102); + events.getEventMap().put(event0103.getKey(), event0103); + events.getEventMap().put(event0104.getKey(), event0104); + + AxContextAlbum externalContextAlbum = new AxContextAlbum( + new AxArtifactKey("ExternalContextAlbum", DEFAULT_VERSION), "EXTERNAL", false, + testExternalContextItem.getKey()); + AxContextAlbum globalContextAlbum = new AxContextAlbum(new AxArtifactKey("GlobalContextAlbum", DEFAULT_VERSION), + "GLOBAL", true, testGlobalContextItem.getKey()); + AxContextAlbum policy0ContextAlbum = new AxContextAlbum( + new AxArtifactKey("Policy0ContextAlbum", DEFAULT_VERSION), "APPLICATION", true, + testPolicyContextItem.getKey()); + AxContextAlbum policy1ContextAlbum = new AxContextAlbum( + new AxArtifactKey("Policy1ContextAlbum", DEFAULT_VERSION), "APPLICATION", true, + testPolicyContextItem.getKey()); + + AxContextAlbums albums = new AxContextAlbums(new AxArtifactKey("Context", DEFAULT_VERSION)); + albums.getAlbumsMap().put(externalContextAlbum.getKey(), externalContextAlbum); + albums.getAlbumsMap().put(globalContextAlbum.getKey(), globalContextAlbum); + albums.getAlbumsMap().put(policy0ContextAlbum.getKey(), policy0ContextAlbum); + albums.getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); + + Set referenceKeySet0 = new TreeSet<>(); + referenceKeySet0.add(policy0ContextAlbum.getKey()); + referenceKeySet0.add(policy1ContextAlbum.getKey()); + referenceKeySet0.add(globalContextAlbum.getKey()); + referenceKeySet0.add(externalContextAlbum.getKey()); + + Set referenceKeySet1 = new TreeSet<>(); + referenceKeySet1.add(policy0ContextAlbum.getKey()); + referenceKeySet1.add(globalContextAlbum.getKey()); + + Set referenceKeySet2 = new TreeSet<>(); + referenceKeySet2.add(policy1ContextAlbum.getKey()); + referenceKeySet2.add(globalContextAlbum.getKey()); + + Set referenceKeySet3 = new TreeSet<>(); + referenceKeySet3.add(globalContextAlbum.getKey()); + referenceKeySet3.add(externalContextAlbum.getKey()); + + List> referenceKeySetList = new ArrayList<>(); + referenceKeySetList.add(referenceKeySet0); + referenceKeySetList.add(referenceKeySet1); + referenceKeySetList.add(referenceKeySet2); + referenceKeySetList.add(referenceKeySet3); + + AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", DEFAULT_VERSION)); + tasks.getTaskMap().putAll(getTaskMap(MATCH, event0000.getParameterMap(), event0001.getParameterMap(), + referenceKeySetList, axLogicExecutorType)); + tasks.getTaskMap().putAll(getTaskMap(ESTABLISH, event0001.getParameterMap(), event0002.getParameterMap(), + referenceKeySetList, axLogicExecutorType)); + tasks.getTaskMap().putAll(getTaskMap(DECIDE, event0002.getParameterMap(), event0003.getParameterMap(), + referenceKeySetList, axLogicExecutorType)); + tasks.getTaskMap().putAll(getTaskMap("Act", event0003.getParameterMap(), event0004.getParameterMap(), + referenceKeySetList, axLogicExecutorType)); + + Set matchTasks = new TreeSet<>(); + Set establishTasks = new TreeSet<>(); + Set decideTasks = new TreeSet<>(); + Set actTasks = new TreeSet<>(); + for (AxTask task : tasks.getTaskMap().values()) { + if (task.getKey().getName().contains(MATCH)) { + matchTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(ESTABLISH)) { + establishTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(DECIDE)) { + decideTasks.add(task.getKey()); + } + if (task.getKey().getName().contains("Act")) { + actTasks.add(task.getKey()); + } + } + List> taskReferenceList = new ArrayList<>(); + taskReferenceList.add(matchTasks); + taskReferenceList.add(establishTasks); + taskReferenceList.add(decideTasks); + taskReferenceList.add(actTasks); + + List p0InEventList = new ArrayList<>(); + p0InEventList.add(event0000.getKey()); + p0InEventList.add(event0001.getKey()); + p0InEventList.add(event0002.getKey()); + p0InEventList.add(event0003.getKey()); + + List p0OutEventList = new ArrayList<>(); + p0OutEventList.add(event0001.getKey()); + p0OutEventList.add(event0002.getKey()); + p0OutEventList.add(event0003.getKey()); + p0OutEventList.add(event0004.getKey()); + + List p0defaultTaskList = new ArrayList<>(); + p0defaultTaskList.add(tasks.get("Task_Match0").getKey()); + p0defaultTaskList.add(tasks.get("Task_Establish2").getKey()); + p0defaultTaskList.add(tasks.get("Task_Decide3").getKey()); + p0defaultTaskList.add(tasks.get("Task_Act1").getKey()); + + List p1InEventList = new ArrayList<>(); + p1InEventList.add(event0100.getKey()); + p1InEventList.add(event0101.getKey()); + p1InEventList.add(event0102.getKey()); + p1InEventList.add(event0103.getKey()); + + List p1OutEventList = new ArrayList<>(); + p1OutEventList.add(event0101.getKey()); + p1OutEventList.add(event0102.getKey()); + p1OutEventList.add(event0103.getKey()); + p1OutEventList.add(event0104.getKey()); + + List p1defaultTaskList = new ArrayList<>(); + p1defaultTaskList.add(tasks.get("Task_Match3").getKey()); + p1defaultTaskList.add(tasks.get("Task_Establish1").getKey()); + p1defaultTaskList.add(tasks.get("Task_Decide3").getKey()); + p1defaultTaskList.add(tasks.get("Task_Act0").getKey()); + + Set p0ReferenceKeySet0 = new TreeSet<>(); + p0ReferenceKeySet0.add(policy0ContextAlbum.getKey()); + p0ReferenceKeySet0.add(globalContextAlbum.getKey()); + + Set p0ReferenceKeySet1 = new TreeSet<>(); + p0ReferenceKeySet1.add(policy1ContextAlbum.getKey()); + p0ReferenceKeySet1.add(globalContextAlbum.getKey()); + p0ReferenceKeySet1.add(externalContextAlbum.getKey()); + + Set p0ReferenceKeySet2 = new TreeSet<>(); + p0ReferenceKeySet2.add(policy0ContextAlbum.getKey()); + p0ReferenceKeySet2.add(globalContextAlbum.getKey()); + p0ReferenceKeySet2.add(externalContextAlbum.getKey()); + + Set p0ReferenceKeySet3 = new TreeSet<>(); + p0ReferenceKeySet3.add(globalContextAlbum.getKey()); + + List> p0ReferenceKeySetList = new ArrayList<>(); + p0ReferenceKeySetList.add(p0ReferenceKeySet0); + p0ReferenceKeySetList.add(p0ReferenceKeySet1); + p0ReferenceKeySetList.add(p0ReferenceKeySet2); + p0ReferenceKeySetList.add(p0ReferenceKeySet3); + + AxPolicy policy0 = new AxPolicy(new AxArtifactKey("Policy0", DEFAULT_VERSION)); + policy0.setTemplate("MEDA"); + policy0.setStateMap(getStateMap(policy0.getKey(), p0InEventList, p0OutEventList, p0ReferenceKeySetList, + axLogicExecutorType, p0defaultTaskList, taskReferenceList)); + policy0.setFirstState(policy0.getStateMap().get(MATCH).getKey().getLocalName()); + + Set p1ReferenceKeySet0 = new TreeSet<>(); + p1ReferenceKeySet0.add(policy1ContextAlbum.getKey()); + p1ReferenceKeySet0.add(globalContextAlbum.getKey()); + p1ReferenceKeySet0.add(externalContextAlbum.getKey()); + + Set p1ReferenceKeySet1 = new TreeSet<>(); + p1ReferenceKeySet1.add(policy1ContextAlbum.getKey()); + p1ReferenceKeySet1.add(globalContextAlbum.getKey()); + p1ReferenceKeySet1.add(externalContextAlbum.getKey()); + + Set p1ReferenceKeySet2 = new TreeSet<>(); + p1ReferenceKeySet2.add(policy1ContextAlbum.getKey()); + p1ReferenceKeySet2.add(globalContextAlbum.getKey()); + p1ReferenceKeySet2.add(externalContextAlbum.getKey()); + + Set p1ReferenceKeySet3 = new TreeSet<>(); + p1ReferenceKeySet3.add(globalContextAlbum.getKey()); + + List> p1ReferenceKeySetList = new ArrayList<>(); + p1ReferenceKeySetList.add(p1ReferenceKeySet0); + p1ReferenceKeySetList.add(p1ReferenceKeySet1); + p1ReferenceKeySetList.add(p1ReferenceKeySet2); + p1ReferenceKeySetList.add(p1ReferenceKeySet3); + + AxPolicy policy1 = new AxPolicy(new AxArtifactKey("Policy1", DEFAULT_VERSION)); + policy1.setTemplate("MEDA"); + policy1.setStateMap(getStateMap(policy1.getKey(), p1InEventList, p1OutEventList, p1ReferenceKeySetList, + axLogicExecutorType, p1defaultTaskList, taskReferenceList)); + policy1.setFirstState(policy1.getStateMap().get(MATCH).getKey().getLocalName()); + + AxPolicies policies = new AxPolicies(new AxArtifactKey("Policies", DEFAULT_VERSION)); + policies.getPolicyMap().put(policy0.getKey(), policy0); + policies.getPolicyMap().put(policy1.getKey(), policy1); + + AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", DEFAULT_VERSION)); + AxPolicyModel policyModel = new AxPolicyModel( + new AxArtifactKey("SamplePolicyModel" + axLogicExecutorType, DEFAULT_VERSION)); + policyModel.setKeyInformation(keyInformation); + policyModel.setPolicies(policies); + policyModel.setEvents(events); + policyModel.setTasks(tasks); + policyModel.setAlbums(albums); + policyModel.setSchemas(axContextSchemas); + policyModel.getKeyInformation().generateKeyInfo(policyModel); + + AxValidationResult result = policyModel.validate(new AxValidationResult()); + if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.VALID)) { + throw new ApexRuntimeException("model " + policyModel.getId() + " is not valid" + result); + } + return policyModel; + } + + /** + * Gets the state map. + * + * @param policyKey the policy key + * @param inEventKeyList the in event key list + * @param outEventKeyList the out event key list + * @param referenceKeySetList the reference key set list + * @param axLogicExecutorType the ax logic executor type + * @param defaultTaskList the default task list + * @param taskKeySetList the task key set list + * @return the state map + */ + private Map getStateMap(final AxArtifactKey policyKey, final List inEventKeyList, + final List outEventKeyList, final List> referenceKeySetList, + final String axLogicExecutorType, final List defaultTaskList, + final List> taskKeySetList) { + + AxState actState = new AxState(new AxReferenceKey(policyKey, "Act")); + actState.setTrigger(inEventKeyList.get(3)); + AxStateOutput act2Out = new AxStateOutput(actState.getKey(), AxReferenceKey.getNullKey(), + outEventKeyList.get(3)); + actState.getStateOutputs().put(act2Out.getKey().getLocalName(), act2Out); + actState.setContextAlbumReferences(referenceKeySetList.get(3)); + + AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(this.getClass().getPackage().getName()) + .setDefaultLogic("DefaultStateLogic"); + actState.setTaskSelectionLogic(new AxTaskSelectionLogic(actState.getKey(), TASK_SELECTION_LIGIC, + axLogicExecutorType, logicReader)); + actState.setDefaultTask(defaultTaskList.get(3)); + for (AxArtifactKey taskKey : taskKeySetList.get(3)) { + actState.getTaskReferences().put(taskKey, new AxStateTaskReference(actState.getKey(), taskKey, + AxStateTaskOutputType.DIRECT, act2Out.getKey())); + } + + AxState decideState = new AxState(new AxReferenceKey(policyKey, DECIDE)); + decideState.setTrigger(inEventKeyList.get(2)); + AxStateOutput decide2Act = new AxStateOutput(decideState.getKey(), actState.getKey(), outEventKeyList.get(2)); + decideState.getStateOutputs().put(decide2Act.getKey().getLocalName(), decide2Act); + decideState.setContextAlbumReferences(referenceKeySetList.get(2)); + decideState.setTaskSelectionLogic(new AxTaskSelectionLogic(decideState.getKey(), TASK_SELECTION_LIGIC, + axLogicExecutorType, logicReader)); + decideState.setDefaultTask(defaultTaskList.get(2)); + for (AxArtifactKey taskKey : taskKeySetList.get(2)) { + decideState.getTaskReferences().put(taskKey, new AxStateTaskReference(decideState.getKey(), taskKey, + AxStateTaskOutputType.DIRECT, decide2Act.getKey())); + } + + AxState establishState = new AxState(new AxReferenceKey(policyKey, ESTABLISH)); + establishState.setTrigger(inEventKeyList.get(1)); + AxStateOutput establish2Decide = new AxStateOutput(establishState.getKey(), decideState.getKey(), + outEventKeyList.get(1)); + establishState.getStateOutputs().put(establish2Decide.getKey().getLocalName(), establish2Decide); + establishState.setContextAlbumReferences(referenceKeySetList.get(1)); + establishState.setTaskSelectionLogic(new AxTaskSelectionLogic(establishState.getKey(), TASK_SELECTION_LIGIC, + axLogicExecutorType, logicReader)); + establishState.setDefaultTask(defaultTaskList.get(1)); + for (AxArtifactKey taskKey : taskKeySetList.get(1)) { + establishState.getTaskReferences().put(taskKey, new AxStateTaskReference(establishState.getKey(), taskKey, + AxStateTaskOutputType.DIRECT, establish2Decide.getKey())); + } + + AxState matchState = new AxState(new AxReferenceKey(policyKey, MATCH)); + matchState.setTrigger(inEventKeyList.get(0)); + AxStateOutput match2Establish = new AxStateOutput(matchState.getKey(), establishState.getKey(), + outEventKeyList.get(0)); + matchState.getStateOutputs().put(match2Establish.getKey().getLocalName(), match2Establish); + matchState.setContextAlbumReferences(referenceKeySetList.get(0)); + matchState.setTaskSelectionLogic(new AxTaskSelectionLogic(matchState.getKey(), TASK_SELECTION_LIGIC, + axLogicExecutorType, logicReader)); + matchState.setDefaultTask(defaultTaskList.get(0)); + for (AxArtifactKey taskKey : taskKeySetList.get(0)) { + matchState.getTaskReferences().put(taskKey, new AxStateTaskReference(matchState.getKey(), taskKey, + AxStateTaskOutputType.DIRECT, match2Establish.getKey())); + } + + Map stateMap = new TreeMap<>(); + stateMap.put(matchState.getKey().getLocalName(), matchState); + stateMap.put(establishState.getKey().getLocalName(), establishState); + stateMap.put(decideState.getKey().getLocalName(), decideState); + stateMap.put(actState.getKey().getLocalName(), actState); + + return stateMap; + } + // CHECKSTYLE:ON: checkstyle:maximumMethodLength + + /** + * Gets the task map. + * + * @param state the state + * @param inputFields the input fields + * @param outputFields the output fields + * @param referenceKeySetList the reference key set list + * @param axLogicExecutorType the ax logic executor type + * @return the task map + */ + private Map getTaskMap(final String state, final Map inputFields, + final Map outputFields, final List> referenceKeySetList, + final String axLogicExecutorType) { + + AxTask testTask0 = new AxTask(new AxArtifactKey(TASK + state + "0", DEFAULT_VERSION)); + testTask0.duplicateInputFields(inputFields); + testTask0.duplicateOutputFields(outputFields); + AxTaskParameter parameter00 = new AxTaskParameter(new AxReferenceKey(testTask0.getKey(), PARAMETER0), + DEFAULT_VALUE0); + AxTaskParameter parameter01 = new AxTaskParameter(new AxReferenceKey(testTask0.getKey(), PARAMETER1), + DEFAULT_VALUE1); + AxTaskParameter parameter02 = new AxTaskParameter(new AxReferenceKey(testTask0.getKey(), PARAMETER2), + DEFAULT_VALUE2); + testTask0.getTaskParameters().put(parameter00.getKey().getLocalName(), parameter00); + testTask0.getTaskParameters().put(parameter01.getKey().getLocalName(), parameter01); + testTask0.getTaskParameters().put(parameter02.getKey().getLocalName(), parameter02); + testTask0.setContextAlbumReferences(referenceKeySetList.get(0)); + + AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(this.getClass().getPackage().getName()) + .setDefaultLogic("DefaultTaskLogic"); + testTask0.setTaskLogic(getTaskLogic(testTask0, logicReader, axLogicExecutorType, state, "2")); + + AxTask testTask1 = new AxTask(new AxArtifactKey(TASK + state + "1", DEFAULT_VERSION)); + testTask1.duplicateInputFields(inputFields); + testTask1.duplicateOutputFields(outputFields); + AxTaskParameter parameter10 = new AxTaskParameter(new AxReferenceKey(testTask1.getKey(), PARAMETER0), + DEFAULT_VALUE0); + AxTaskParameter parameter11 = new AxTaskParameter(new AxReferenceKey(testTask1.getKey(), PARAMETER1), + DEFAULT_VALUE1); + testTask1.getTaskParameters().put(parameter10.getKey().getLocalName(), parameter10); + testTask1.getTaskParameters().put(parameter11.getKey().getLocalName(), parameter11); + testTask1.setContextAlbumReferences(referenceKeySetList.get(1)); + testTask1.setTaskLogic(getTaskLogic(testTask1, logicReader, axLogicExecutorType, state, "3")); + + AxTask testTask2 = new AxTask(new AxArtifactKey(TASK + state + "2", DEFAULT_VERSION)); + testTask2.duplicateInputFields(inputFields); + testTask2.duplicateOutputFields(outputFields); + AxTaskParameter parameter20 = new AxTaskParameter(new AxReferenceKey(testTask2.getKey(), PARAMETER0), + DEFAULT_VALUE0); + testTask2.getTaskParameters().put(parameter20.getKey().getLocalName(), parameter20); + testTask2.setContextAlbumReferences(referenceKeySetList.get(2)); + testTask2.setTaskLogic(getTaskLogic(testTask2, logicReader, axLogicExecutorType, state, "0")); + + AxTask testTask3 = new AxTask(new AxArtifactKey(TASK + state + "3", DEFAULT_VERSION)); + testTask3.duplicateInputFields(inputFields); + testTask3.duplicateOutputFields(outputFields); + AxTaskParameter parameter30 = new AxTaskParameter(new AxReferenceKey(testTask3.getKey(), PARAMETER0), + DEFAULT_VALUE0); + testTask3.getTaskParameters().put(parameter30.getKey().getLocalName(), parameter30); + testTask3.setContextAlbumReferences(referenceKeySetList.get(THIRD_ENTRY)); + testTask3.setTaskLogic(getTaskLogic(testTask3, logicReader, axLogicExecutorType, state, "1")); + + Map taskMap = new TreeMap<>(); + taskMap.put(testTask0.getKey(), testTask0); + taskMap.put(testTask1.getKey(), testTask1); + taskMap.put(testTask2.getKey(), testTask2); + taskMap.put(testTask3.getKey(), testTask3); + + return taskMap; + } + + /** + * Gets the task logic. + * + * @param task the task + * @param logicReader the logic reader + * @param logicFlavour the logic flavour + * @param stateName the state name + * @param caseToUse the case to use + * @return the task logic + */ + private AxTaskLogic getTaskLogic(final AxTask task, final AxLogicReader logicReader, final String logicFlavour, + final String stateName, final String caseToUse) { + AxTaskLogic axLogic = new AxTaskLogic(new AxReferenceKey(task.getKey(), "_TaskLogic"), logicFlavour, + logicReader); + + axLogic.setLogic(axLogic.getLogic().replaceAll("", stateName) + .replaceAll("", task.getKey().getName()) + .replaceAll("", caseToUse)); + + return axLogic; + } +} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelSaver.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelSaver.java new file mode 100644 index 000000000..8eb885759 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/SampleDomainModelSaver.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.model; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelSaver; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class saves sample domain models to disk in XML and JSON format. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public final class SampleDomainModelSaver { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(SampleDomainModelSaver.class); + + /** + * Private default constructor to prevent subclassing. + */ + private SampleDomainModelSaver() { + } + + /** + * Write the sample Models to args[0]. + * + * @param args Not used + * @throws ApexException the apex exception + */ + public static void main(final String[] args) throws ApexException { + if (args.length != 1) { + LOGGER.error("usage: " + SampleDomainModelSaver.class.getCanonicalName() + " modelDirectory"); + return; + } + + // Save Java model + final AxPolicyModel javaPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVA"); + final ApexModelSaver javaModelSaver = new ApexModelSaver<>(AxPolicyModel.class, + javaPolicyModel, args[0]); + javaModelSaver.apexModelWriteJson(); + javaModelSaver.apexModelWriteXml(); + + // Save Javascript model + final AxPolicyModel javascriptPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVASCRIPT"); + final ApexModelSaver javascriptModelSaver = new ApexModelSaver<>( + AxPolicyModel.class, javascriptPolicyModel, args[0]); + javascriptModelSaver.apexModelWriteJson(); + javascriptModelSaver.apexModelWriteXml(); + + // Save JRuby model + final AxPolicyModel jRubyPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JRUBY"); + final ApexModelSaver jRubyModelSaver = new ApexModelSaver<>(AxPolicyModel.class, + jRubyPolicyModel, args[0]); + jRubyModelSaver.apexModelWriteJson(); + jRubyModelSaver.apexModelWriteXml(); + + // Save Jython model + final AxPolicyModel jythonPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JYTHON"); + final ApexModelSaver jythonModelSaver = new ApexModelSaver<>(AxPolicyModel.class, + jythonPolicyModel, args[0]); + jythonModelSaver.apexModelWriteJson(); + jythonModelSaver.apexModelWriteXml(); + + // Save MVEL model + final AxPolicyModel mvelPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + final ApexModelSaver mvelModelSaver = new ApexModelSaver<>(AxPolicyModel.class, + mvelPolicyModel, args[0]); + mvelModelSaver.apexModelWriteJson(); + mvelModelSaver.apexModelWriteXml(); + } + +} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultStateLogic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultStateLogic.java new file mode 100644 index 000000000..2669e70d7 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultStateLogic.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.model.java; + +import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; + +/** + * The Class DefaultState_Logic is default task selection logic in Java. + */ +public class DefaultStateLogic { + /** + * Gets the task. + * + * @param executor the executor + * @return the task + */ + public boolean getTask(final TaskSelectionExecutionContext executor) { + executor.logger.debug(executor.subject.getId()); + executor.logger.debug(executor.getContextAlbum("GlobalContextAlbum").getName()); + executor.subject.getDefaultTaskKey().copyTo(executor.selectedTask); + return true; + } +} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java new file mode 100644 index 000000000..86dac6638 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.model.java; + +import java.util.Date; +import java.util.Random; + +import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; + +/** + * The Class DefaultTask_Logic is default task logic in Java. + */ +public class DefaultTaskLogic { + private static final int BOUND_FOR_RANDOM_INT = 4; + + /** + * Gets the event. + * + * @param executor the executor + * @return the event + * @throws ApexException the apex exception + */ + public boolean getEvent(final TaskExecutionContext executor) throws ApexException { + String idString = executor.subject.getId(); + executor.logger.debug(idString); + + String albumNameString = executor.getContextAlbum("GlobalContextAlbum").getName(); + executor.logger.debug(albumNameString); + + String inFieldsString = executor.inFields.toString(); + executor.logger.debug(inFieldsString); + + final Date timeNow = new Date(); + final Random rand = new Random(); + + if (executor.inFields.containsKey("TestDecideCaseSelected")) { + executor.outFields.put("TestActCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT)); + executor.outFields.put("TestActStateTime", timeNow.getTime()); + } + else if (executor.inFields.containsKey("TestEstablishCaseSelected")) { + executor.outFields.put("TestDecideCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT)); + executor.outFields.put("TestDecideStateTime", timeNow.getTime()); + } + else if (executor.inFields.containsKey("TestMatchCaseSelected")) { + executor.outFields.put("TestEstablishCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT)); + executor.outFields.put("TestEstablishStateTime", timeNow.getTime()); + } + else { + executor.outFields.put("TestMatchCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT)); + executor.outFields.put("TestMatchStateTime", timeNow.getTime()); + } + + return true; + } +} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalStateLogic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalStateLogic.java new file mode 100644 index 000000000..49fccd75d --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalStateLogic.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.model.java; + +import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; + +/** + * The Class EvalState_Logic is default evaluation task selection logic in Java. + */ +public class EvalStateLogic { + /** + * Gets the task. + * + * @param executor the executor + * @return the task + */ + public boolean getTask(final TaskSelectionExecutionContext executor) { + executor.logger.debug(executor.subject.getId()); + executor.subject.getDefaultTaskKey().copyTo(executor.selectedTask); + return true; + } +} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java new file mode 100644 index 000000000..4c37e4d89 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.model.java; + +import java.util.Date; + +import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; + +/** + * The Class EvalTask_Logic is default evaluation task logic in Java. + */ +public class EvalTaskLogic { + + /** + * Gets the event. + * + * @param executor the executor + * @return the event + * @throws ApexException the apex exception + */ + public boolean getEvent(final TaskExecutionContext executor) throws ApexException { + String idString = executor.subject.getId(); + executor.logger.debug(idString); + + String inFieldString = executor.inFields.toString(); + executor.logger.debug(inFieldString); + + executor.outFields.putAll(executor.inFields); + + final Date timeNow = new Date(); + executor.outFields.put("State3Timestamp", timeNow.getTime()); + + String outFieldString = executor.outFields.toString(); + executor.logger.debug(outFieldString); + return true; + } +} diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/package-info.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/package-info.java new file mode 100644 index 000000000..fb5f414d8 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/package-info.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains the Javadomain specific logic for the test domain. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +package org.onap.policy.apex.testsuites.integration.common.model.java; diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/package-info.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/package-info.java new file mode 100644 index 000000000..e508444c9 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/package-info.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Executes tests using all the APEX executors on a test domain model. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +package org.onap.policy.apex.testsuites.integration.common.model; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultState_Logic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultState_Logic.javascript deleted file mode 100644 index e25cb9c6e..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultState_Logic.javascript +++ /dev/null @@ -1,27 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -executor.logger.debug(executor.subject.id); -var gc = executor.getContextAlbum("GlobalContextAlbum"); -executor.logger.debug(gc.name); -executor.subject.defaultTaskKey.copyTo(executor.selectedTask) - -var returnValue = executor.isTrue; - diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultTask_Logic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultTask_Logic.javascript deleted file mode 100644 index f98e16555..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/DefaultTask_Logic.javascript +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -executor.logger.debug(executor.subject.id); -var gc = executor.getContextAlbum("GlobalContextAlbum"); -executor.logger.debug(gc.name); -executor.logger.debug(executor.inFields); - -var caseSelectedType = Java.type("java.lang.Byte"); -executor.outFields.put("TestCaseSelected", new caseSelectedType()); - -var JavaDate = Java.type("java.util.Date"); -timeNow = new JavaDate(); -executor.outFields.put("TestStateTime", timeNow.getTime()); -executor.logger.debug(executor.eo); - -var returnValue = executor.isTrue; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalState_Logic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalState_Logic.javascript deleted file mode 100644 index 535cad595..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalState_Logic.javascript +++ /dev/null @@ -1,25 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -executor.logger.debug(executor.subject.id); -executor.subject.defaultTaskKey.copyTo(executor.selectedTask); - -var returnValue = executor.isTrue; - diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalTask_Logic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalTask_Logic.javascript deleted file mode 100644 index b0756504c..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/javascript/EvalTask_Logic.javascript +++ /dev/null @@ -1,29 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -executor.logger.debug(executor.subject.id); -executor.logger.debug(executor.inFields); - -var JavaDate = Java.type("java.util.Date"); -timeNow = new JavaDate(); -executor.outFields.put("StateTimestamp", timeNow.getTime()); -executor.logger.debug(executor.outFields); - -var returnValue = executor.isTrue; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultState_Logic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultState_Logic.jruby deleted file mode 100644 index 2965476a8..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultState_Logic.jruby +++ /dev/null @@ -1,24 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -executor.logger.debug("id: " + executor.subject.id) -executor.logger.debug("ctxt name: " + executor.getContextAlbum("GlobalContextAlbum").name) -executor.subject.defaultTaskKey.copyTo(executor.selectedTask) -return true diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultTask_Logic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultTask_Logic.jruby deleted file mode 100644 index 4ad39f57e..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/DefaultTask_Logic.jruby +++ /dev/null @@ -1,33 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -require 'java' - -executor.logger.debug("id: " + executor.subject.id) -executor.logger.debug("ctxt name: " + executor.getContextAlbum("GlobalContextAlbum").name) -executor.logger.debug("inFields: " + executor.inFields.toString()) - -executor.outFields.put("TestCaseSelected", .to_java(:byte)) - -timeNow = java.util.Date.new() -executor.outFields.put("TestStateTime", timeNow.getTime()) -executor.logger.debug("outFields: " + executor.outFields.toString()) - -return true diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalState_Logic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalState_Logic.jruby deleted file mode 100644 index e57a62c8b..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalState_Logic.jruby +++ /dev/null @@ -1,23 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -executor.logger.debug("id: " + executor.subject.id); -executor.subject.defaultTaskKey.copyTo(executor.selectedTask); -return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalTask_Logic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalTask_Logic.jruby deleted file mode 100644 index 72a4ee607..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jruby/EvalTask_Logic.jruby +++ /dev/null @@ -1,32 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -require 'java'; - -executor.logger.debug("id: " + executor.subject.id); -executor.logger.debug("inFields: " + executor.inFields.toString()); - -executor.outFields.putAll(executor.inFields); - -timeNow = java.util.Date.new(); -executor.outFields.put("StateTimestamp", timeNow.getTime()); -executor.logger.debug("outFields: " + executor.outFields.toString()); - -return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultState_Logic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultState_Logic.jython deleted file mode 100644 index 9752f057d..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultState_Logic.jython +++ /dev/null @@ -1,27 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -from java.lang import Boolean -executor.logger.debug('id: ' + executor.subject.id) - -executor.logger.debug('ctxt name: ' + executor.getContextAlbum("GlobalContextAlbum").name) -executor.subject.defaultTaskKey.copyTo(executor.selectedTask) - -returnValue = executor.isTrue diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultTask_Logic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultTask_Logic.jython deleted file mode 100644 index f57ce3f0a..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/DefaultTask_Logic.jython +++ /dev/null @@ -1,35 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -from java.lang import Byte -from java.lang import Long -from java.util import Date - -executor.logger.debug('id: ' + executor.subject.id) - -executor.logger.debug('ctxt name: ' + executor.getContextAlbum("GlobalContextAlbum").name) -executor.logger.debug('inFields: ' + executor.inFields.toString()) - -executor.outFields["TestCaseSelected"] = Byte("") - -timeValue = Long(Date().getTime()); -executor.outFields["TestStateTime"] = timeValue -executor.logger.debug('outFields: ' + executor.outFields.toString()) -returnValue = executor.isTrue diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalState_Logic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalState_Logic.jython deleted file mode 100644 index 94f90b258..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalState_Logic.jython +++ /dev/null @@ -1,25 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -executor.logger.debug('id: ' + executor.subject.id); - -executor.subject.defaultTaskKey.copyTo(executor.selectedTask); - -returnValue = executor.isTrue; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalTask_Logic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalTask_Logic.jython deleted file mode 100644 index aa6525673..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/jython/EvalTask_Logic.jython +++ /dev/null @@ -1,32 +0,0 @@ -#------------------------------------------------------------------------------- -# ============LICENSE_START======================================================= -# Copyright (C) 2016-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. -# -# SPDX-License-Identifier: Apache-2.0 -# ============LICENSE_END========================================================= -#------------------------------------------------------------------------------- - -from java.lang import Boolean -from java.lang import Long -from java.util import Date - -executor.logger.debug('id: ' + executor.subject.id) - -executor.logger.debug('inFields: ' + executor.inFields.toString()) -executor.outFields.putAll(executor.inFields) - -executor.outFields["StateTimestamp"] = Long(Date().getTime()) -executor.logger.debug('outFields: ' + executor.outFields.toString()) -returnValue = Boolean.TRUE diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultState_Logic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultState_Logic.mvel deleted file mode 100644 index 1620c6cd5..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultState_Logic.mvel +++ /dev/null @@ -1,23 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -logger.debug(subject.id + ":" + subject.stateName); -subject.defaultTaskKey.copyTo(selectedTask); -return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultTask_Logic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultTask_Logic.mvel deleted file mode 100644 index 9a1a4bad1..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/DefaultTask_Logic.mvel +++ /dev/null @@ -1,30 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -import java.util.Date; -logger.debug(subject.id); -gc = getContextAlbum("GlobalContextAlbum"); -logger.debug(gc); -logger.debug(inFields); -outFields["TestCaseSelected"] = (byte); -timeNow = new Date(); -outFields["TestStateTime"] = timeNow.getTime(); -logger.debug(outFields); -return true; \ No newline at end of file diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalState_Logic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalState_Logic.mvel deleted file mode 100644 index 1620c6cd5..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalState_Logic.mvel +++ /dev/null @@ -1,23 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -logger.debug(subject.id + ":" + subject.stateName); -subject.defaultTaskKey.copyTo(selectedTask); -return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalTask_Logic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalTask_Logic.mvel deleted file mode 100644 index e15a4beec..000000000 --- a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/test/common/model/mvel/EvalTask_Logic.mvel +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -import java.util.Date; -logger.debug(subject.id); -logger.debug(inFields); -timeNow = new Date(); -outFields["StateTimestamp"] = timeNow.getTime(); -return true; \ No newline at end of file diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultStateLogic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultStateLogic.javascript new file mode 100644 index 000000000..e25cb9c6e --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultStateLogic.javascript @@ -0,0 +1,27 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +executor.logger.debug(executor.subject.id); +var gc = executor.getContextAlbum("GlobalContextAlbum"); +executor.logger.debug(gc.name); +executor.subject.defaultTaskKey.copyTo(executor.selectedTask) + +var returnValue = executor.isTrue; + diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultTaskLogic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultTaskLogic.javascript new file mode 100644 index 000000000..f98e16555 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/DefaultTaskLogic.javascript @@ -0,0 +1,34 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +executor.logger.debug(executor.subject.id); +var gc = executor.getContextAlbum("GlobalContextAlbum"); +executor.logger.debug(gc.name); +executor.logger.debug(executor.inFields); + +var caseSelectedType = Java.type("java.lang.Byte"); +executor.outFields.put("TestCaseSelected", new caseSelectedType()); + +var JavaDate = Java.type("java.util.Date"); +timeNow = new JavaDate(); +executor.outFields.put("TestStateTime", timeNow.getTime()); +executor.logger.debug(executor.eo); + +var returnValue = executor.isTrue; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalStateLogic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalStateLogic.javascript new file mode 100644 index 000000000..535cad595 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalStateLogic.javascript @@ -0,0 +1,25 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +executor.logger.debug(executor.subject.id); +executor.subject.defaultTaskKey.copyTo(executor.selectedTask); + +var returnValue = executor.isTrue; + diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalTaskLogic.javascript b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalTaskLogic.javascript new file mode 100644 index 000000000..b0756504c --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/javascript/EvalTaskLogic.javascript @@ -0,0 +1,29 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +executor.logger.debug(executor.subject.id); +executor.logger.debug(executor.inFields); + +var JavaDate = Java.type("java.util.Date"); +timeNow = new JavaDate(); +executor.outFields.put("StateTimestamp", timeNow.getTime()); +executor.logger.debug(executor.outFields); + +var returnValue = executor.isTrue; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultStateLogic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultStateLogic.jruby new file mode 100644 index 000000000..2965476a8 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultStateLogic.jruby @@ -0,0 +1,24 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +executor.logger.debug("id: " + executor.subject.id) +executor.logger.debug("ctxt name: " + executor.getContextAlbum("GlobalContextAlbum").name) +executor.subject.defaultTaskKey.copyTo(executor.selectedTask) +return true diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultTaskLogic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultTaskLogic.jruby new file mode 100644 index 000000000..4ad39f57e --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/DefaultTaskLogic.jruby @@ -0,0 +1,33 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +require 'java' + +executor.logger.debug("id: " + executor.subject.id) +executor.logger.debug("ctxt name: " + executor.getContextAlbum("GlobalContextAlbum").name) +executor.logger.debug("inFields: " + executor.inFields.toString()) + +executor.outFields.put("TestCaseSelected", .to_java(:byte)) + +timeNow = java.util.Date.new() +executor.outFields.put("TestStateTime", timeNow.getTime()) +executor.logger.debug("outFields: " + executor.outFields.toString()) + +return true diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalStateLogic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalStateLogic.jruby new file mode 100644 index 000000000..e57a62c8b --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalStateLogic.jruby @@ -0,0 +1,23 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +executor.logger.debug("id: " + executor.subject.id); +executor.subject.defaultTaskKey.copyTo(executor.selectedTask); +return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalTaskLogic.jruby b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalTaskLogic.jruby new file mode 100644 index 000000000..72a4ee607 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jruby/EvalTaskLogic.jruby @@ -0,0 +1,32 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +require 'java'; + +executor.logger.debug("id: " + executor.subject.id); +executor.logger.debug("inFields: " + executor.inFields.toString()); + +executor.outFields.putAll(executor.inFields); + +timeNow = java.util.Date.new(); +executor.outFields.put("StateTimestamp", timeNow.getTime()); +executor.logger.debug("outFields: " + executor.outFields.toString()); + +return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultStateLogic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultStateLogic.jython new file mode 100644 index 000000000..9752f057d --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultStateLogic.jython @@ -0,0 +1,27 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +from java.lang import Boolean +executor.logger.debug('id: ' + executor.subject.id) + +executor.logger.debug('ctxt name: ' + executor.getContextAlbum("GlobalContextAlbum").name) +executor.subject.defaultTaskKey.copyTo(executor.selectedTask) + +returnValue = executor.isTrue diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultTaskLogic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultTaskLogic.jython new file mode 100644 index 000000000..f57ce3f0a --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/DefaultTaskLogic.jython @@ -0,0 +1,35 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +from java.lang import Byte +from java.lang import Long +from java.util import Date + +executor.logger.debug('id: ' + executor.subject.id) + +executor.logger.debug('ctxt name: ' + executor.getContextAlbum("GlobalContextAlbum").name) +executor.logger.debug('inFields: ' + executor.inFields.toString()) + +executor.outFields["TestCaseSelected"] = Byte("") + +timeValue = Long(Date().getTime()); +executor.outFields["TestStateTime"] = timeValue +executor.logger.debug('outFields: ' + executor.outFields.toString()) +returnValue = executor.isTrue diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalStateLogic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalStateLogic.jython new file mode 100644 index 000000000..94f90b258 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalStateLogic.jython @@ -0,0 +1,25 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +executor.logger.debug('id: ' + executor.subject.id); + +executor.subject.defaultTaskKey.copyTo(executor.selectedTask); + +returnValue = executor.isTrue; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalTaskLogic.jython b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalTaskLogic.jython new file mode 100644 index 000000000..aa6525673 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/jython/EvalTaskLogic.jython @@ -0,0 +1,32 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2016-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. +# +# SPDX-License-Identifier: Apache-2.0 +# ============LICENSE_END========================================================= +#------------------------------------------------------------------------------- + +from java.lang import Boolean +from java.lang import Long +from java.util import Date + +executor.logger.debug('id: ' + executor.subject.id) + +executor.logger.debug('inFields: ' + executor.inFields.toString()) +executor.outFields.putAll(executor.inFields) + +executor.outFields["StateTimestamp"] = Long(Date().getTime()) +executor.logger.debug('outFields: ' + executor.outFields.toString()) +returnValue = Boolean.TRUE diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultStateLogic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultStateLogic.mvel new file mode 100644 index 000000000..1620c6cd5 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultStateLogic.mvel @@ -0,0 +1,23 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +logger.debug(subject.id + ":" + subject.stateName); +subject.defaultTaskKey.copyTo(selectedTask); +return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultTaskLogic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultTaskLogic.mvel new file mode 100644 index 000000000..9a1a4bad1 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/DefaultTaskLogic.mvel @@ -0,0 +1,30 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import java.util.Date; +logger.debug(subject.id); +gc = getContextAlbum("GlobalContextAlbum"); +logger.debug(gc); +logger.debug(inFields); +outFields["TestCaseSelected"] = (byte); +timeNow = new Date(); +outFields["TestStateTime"] = timeNow.getTime(); +logger.debug(outFields); +return true; \ No newline at end of file diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalStateLogic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalStateLogic.mvel new file mode 100644 index 000000000..1620c6cd5 --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalStateLogic.mvel @@ -0,0 +1,23 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +logger.debug(subject.id + ":" + subject.stateName); +subject.defaultTaskKey.copyTo(selectedTask); +return true; diff --git a/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalTaskLogic.mvel b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalTaskLogic.mvel new file mode 100644 index 000000000..e15a4beec --- /dev/null +++ b/testsuites/integration/integration-common/src/main/resources/org/onap/policy/apex/testsuites/integration/common/model/mvel/EvalTaskLogic.mvel @@ -0,0 +1,26 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import java.util.Date; +logger.debug(subject.id); +logger.debug(inFields); +timeNow = new Date(); +outFields["StateTimestamp"] = timeNow.getTime(); +return true; \ No newline at end of file diff --git a/testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/plugins/context/test/locking/TestConcurrentContext.java b/testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/plugins/context/test/locking/TestConcurrentContext.java deleted file mode 100644 index dd6c4e6f1..000000000 --- a/testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/plugins/context/test/locking/TestConcurrentContext.java +++ /dev/null @@ -1,374 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.context.test.locking; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.onap.policy.apex.context.parameters.DistributorParameters.DEFAULT_DISTRIBUTOR_PLUGIN_CLASS; -import static org.onap.policy.apex.context.test.utils.Constants.TEST_VALUE; - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.TreeSet; - -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.onap.policy.apex.context.impl.distribution.jvmlocal.JvmLocalDistributor; -import org.onap.policy.apex.context.impl.locking.jvmlocal.JvmLocalLockManager; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.DistributorParameters; -import org.onap.policy.apex.context.test.concepts.TestContextLongItem; -import org.onap.policy.apex.context.test.lock.modifier.LockType; -import org.onap.policy.apex.context.test.locking.ConcurrentContext; -import org.onap.policy.apex.context.test.utils.ConfigrationProvider; -import org.onap.policy.apex.context.test.utils.ConfigrationProviderImpl; -import org.onap.policy.apex.context.test.utils.Constants; -import org.onap.policy.apex.context.test.utils.NetworkUtils; -import org.onap.policy.apex.context.test.utils.ZooKeeperServerServiceProvider; -import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.plugins.context.distribution.hazelcast.HazelcastContextDistributor; -import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanContextDistributor; -import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanDistributorParameters; -import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManager; -import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManagerParameters; -import org.onap.policy.apex.plugins.context.locking.hazelcast.HazelcastLockManager; -import org.onap.policy.common.parameters.ParameterService; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class TestConcurrentContext tests concurrent use of context. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestConcurrentContext { - private static final String HAZELCAST_CONFIG = "hazelcast.config"; - - private static final String JAVA_NET_PREFER_IPV4_STACK = "java.net.preferIPv4Stack"; - private static final String HAZELCAST_XML_FILE = "src/test/resources/hazelcast/hazelcast.xml"; - - // Logger for this class - private static final XLogger logger = XLoggerFactory.getXLogger(TestConcurrentContext.class); - - // Test parameters - private static final String ZOOKEEPER_ADDRESS = "127.0.0.1"; - private static final int ZOOKEEPER_START_PORT = 62181; - private static final int TEST_JVM_COUNT_SINGLE_JVM = 1; - private static final int TEST_JVM_COUNT_MULTI_JVM = 3; - private static final int TEST_THREAD_COUNT_SINGLE_JVM = 64; - private static final int TEST_THREAD_COUNT_MULTI_JVM = 20; - private static final int TEST_THREAD_LOOPS = 100; - - // We need to increment the Zookeeper port because sometimes the port is not released at the end - // of the test for a few seconds. - private static int nextZookeeperPort = ZOOKEEPER_START_PORT; - private int zookeeperPort; - - @Rule - public final TemporaryFolder folder = new TemporaryFolder(); - - private ZooKeeperServerServiceProvider zooKeeperServerServiceProvider; - - @BeforeClass - public static void configure() throws Exception { - System.setProperty(JAVA_NET_PREFER_IPV4_STACK, "true"); - final String hazelCastfileLocation = ResourceUtils.getFilePath4Resource(HAZELCAST_XML_FILE); - System.setProperty(HAZELCAST_CONFIG, hazelCastfileLocation); - - final TreeSet ipAddressSet = NetworkUtils.getIPv4NonLoopAddresses(); - - if (ipAddressSet.size() == 0) { - throw new Exception("cound not find real IP address for test"); - } - logger.info("For Infinispan, setting jgroups.tcp.address to: {}", ipAddressSet.first()); - System.setProperty("jgroups.tcp.address", ipAddressSet.first()); - - } - - private void startZookeeperServer() throws Exception { - final File zookeeperDirectory = folder.newFolder("zookeeperDirectory"); - - zookeeperPort = nextZookeeperPort++; - final InetSocketAddress addr = new InetSocketAddress(MessagingUtils.findPort(zookeeperPort)); - zooKeeperServerServiceProvider = new ZooKeeperServerServiceProvider(zookeeperDirectory, addr); - zooKeeperServerServiceProvider.startZookeeperServer(); - } - - private void stopZookeeperServer() { - if (zooKeeperServerServiceProvider != null) { - zooKeeperServerServiceProvider.stopZookeeperServer(); - } - } - - @Test - public void testConcurrentContextJVMLocalVarSet() throws Exception { - logger.debug("Running testConcurrentContextJVMLocalVarSet test . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - contextParameters.getLockManagerParameters().setPluginClass(JvmLocalLockManager.class.getCanonicalName()); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("JVMLocalVarSet", - TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - assertFalse(result.isEmpty()); - - final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - - logger.debug("Ran testConcurrentContextJVMLocalVarSet test"); - } - - @Test - public void testConcurrentContextJVMLocalNoVarSet() throws Exception { - logger.debug("Running testConcurrentContextJVMLocalNoVarSet test . . ."); - - new ContextParameters(); - final ConfigrationProvider configrationProvider = getConfigrationProvider("JVMLocalNoVarSet", - TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(Constants.TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - - logger.debug("Ran testConcurrentContextJVMLocalNoVarSet test"); - } - - @Test - public void testConcurrentContextMultiJVMNoLock() throws Exception { - logger.debug("Running testConcurrentContextMultiJVMNoLock test . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - contextParameters.getDistributorParameters().setPluginClass(JvmLocalDistributor.class.getCanonicalName()); - contextParameters.getLockManagerParameters().setPluginClass(JvmLocalLockManager.class.getCanonicalName()); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("testConcurrentContextMultiJVMNoLock", - TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - // No concurrent map so result will be zero - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(0, actual.getLongValue()); - - logger.debug("Ran testConcurrentContextMultiJVMNoLock test"); - } - - @Test - public void testConcurrentContextHazelcastLock() throws Exception { - logger.debug("Running testConcurrentContextHazelcastLock test . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); - contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("HazelcastLock", - TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - - logger.debug("Ran testConcurrentContextHazelcastLock test"); - } - - @Test - public void testConcurrentContextCuratorLock() throws Exception { - logger.debug("Running testConcurrentContextCuratorLock test . . ."); - try { - startZookeeperServer(); - final ContextParameters contextParameters = new ContextParameters(); - final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); - distributorParameters.setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); - - final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); - curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); - curatorParameters.setZookeeperAddress(ZOOKEEPER_ADDRESS + ":" + zookeeperPort); - contextParameters.setLockManagerParameters(curatorParameters); - ParameterService.register(curatorParameters); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("CuratorLock", - TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - logger.debug("Ran testConcurrentContextCuratorLock test"); - } finally { - stopZookeeperServer(); - } - } - - @Test - public void testConcurrentContextHazelcastMultiJVMHazelcastLock() throws Exception { - logger.debug("Running testConcurrentContextHazelcastMultiJVMHazelcastLock test . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); - distributorParameters.setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); - contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("HazelcastMultiHazelcastlock", - TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - logger.debug("Ran testConcurrentContextHazelcastMultiJVMHazelcastLock test"); - } - - @Test - public void testConcurrentContextInfinispanMultiJVMHazelcastlock() - throws ApexModelException, IOException, ApexException { - logger.debug("Running testConcurrentContextInfinispanMultiJVMHazelcastlock test . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); - infinispanParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); - infinispanParameters.setConfigFile("infinispan/infinispan-context-test.xml"); - contextParameters.setDistributorParameters(infinispanParameters); - contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("InfinispanMultiHazelcastlock", - TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - logger.debug("Ran testConcurrentContextInfinispanMultiJVMHazelcastlock test"); - } - - @Test - public void testConcurrentContextInfinispanMultiJVMCuratorLock() throws Exception { - logger.debug("Running testConcurrentContextInfinispanMultiJVMCuratorLock test . . ."); - - try { - startZookeeperServer(); - - final ContextParameters contextParameters = new ContextParameters(); - final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); - infinispanParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); - infinispanParameters.setConfigFile("infinispan/infinispan-context-test.xml"); - contextParameters.setDistributorParameters(infinispanParameters); - - final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); - curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); - curatorParameters.setZookeeperAddress(ZOOKEEPER_ADDRESS + ":" + zookeeperPort); - contextParameters.setLockManagerParameters(curatorParameters); - ParameterService.register(curatorParameters); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("InfinispanMultiCuratorLock", - TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); - - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - final Map result = concurrentContext.testConcurrentContext(); - - final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - } finally { - stopZookeeperServer(); - } - - logger.debug("Ran testConcurrentContextInfinispanMultiJVMCuratorLock test"); - } - - @Test - public void testConcurrentContextHazelcastMultiJVMCuratorLock() throws Exception { - logger.debug("Running testConcurrentContextHazelcastMultiJVMCuratorLock test . . ."); - - try { - startZookeeperServer(); - - final ContextParameters contextParameters = new ContextParameters(); - contextParameters.getDistributorParameters() - .setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); - - final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); - curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); - curatorParameters.setZookeeperAddress(ZOOKEEPER_ADDRESS + ":" + zookeeperPort); - contextParameters.setLockManagerParameters(curatorParameters); - ParameterService.register(curatorParameters); - - final ConfigrationProvider configrationProvider = getConfigrationProvider("HazelcastMultiCuratorLock", - TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); - final Map result = - new ConcurrentContext(configrationProvider).testConcurrentContext(); - - final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; - final TestContextLongItem actual = result.get(TEST_VALUE); - assertNotNull(actual); - assertEquals(expected, actual.getLongValue()); - } finally { - stopZookeeperServer(); - } - logger.debug("Ran testConcurrentContextHazelcastMultiJVMCuratorLock test"); - } - - ConfigrationProvider getConfigrationProvider(final String testType, final int jvmCount, final int threadCount, - final int threadLoops) { - return new ConfigrationProviderImpl(testType, jvmCount, threadCount, threadLoops, 16, - LockType.WRITE_LOCK_SINGLE_VALUE_UPDATE.getValue()) { - @Override - public Map getContextAlbumInitValues() { - final Map initValues = super.getContextAlbumInitValues(); - initValues.put(TEST_VALUE, new TestContextLongItem(0l)); - return initValues; - } - - }; - } -} diff --git a/testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/testsuites/integration/context/TestConcurrentContext.java b/testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/testsuites/integration/context/TestConcurrentContext.java new file mode 100644 index 000000000..5fadb2279 --- /dev/null +++ b/testsuites/integration/integration-context-test/src/test/java/org/onap/policy/apex/testsuites/integration/context/TestConcurrentContext.java @@ -0,0 +1,443 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.context; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.onap.policy.apex.context.parameters.DistributorParameters.DEFAULT_DISTRIBUTOR_PLUGIN_CLASS; +import static org.onap.policy.apex.context.test.utils.Constants.TEST_VALUE; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.Map; +import java.util.TreeSet; + +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.onap.policy.apex.context.impl.distribution.jvmlocal.JvmLocalDistributor; +import org.onap.policy.apex.context.impl.locking.jvmlocal.JvmLocalLockManager; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.DistributorParameters; +import org.onap.policy.apex.context.test.concepts.TestContextLongItem; +import org.onap.policy.apex.context.test.lock.modifier.LockType; +import org.onap.policy.apex.context.test.locking.ConcurrentContext; +import org.onap.policy.apex.context.test.utils.ConfigrationProvider; +import org.onap.policy.apex.context.test.utils.ConfigrationProviderImpl; +import org.onap.policy.apex.context.test.utils.Constants; +import org.onap.policy.apex.context.test.utils.NetworkUtils; +import org.onap.policy.apex.context.test.utils.ZooKeeperServerServiceProvider; +import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.plugins.context.distribution.hazelcast.HazelcastContextDistributor; +import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanContextDistributor; +import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanDistributorParameters; +import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManager; +import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManagerParameters; +import org.onap.policy.apex.plugins.context.locking.hazelcast.HazelcastLockManager; +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestConcurrentContext tests concurrent use of context. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestConcurrentContext { + private static final String HAZELCAST_CONFIG = "hazelcast.config"; + + private static final String JAVA_NET_PREFER_IPV4_STACK = "java.net.preferIPv4Stack"; + private static final String HAZELCAST_XML_FILE = "src/test/resources/hazelcast/hazelcast.xml"; + + // Logger for this class + private static final XLogger logger = XLoggerFactory.getXLogger(TestConcurrentContext.class); + + // Test parameters + private static final String ZOOKEEPER_ADDRESS = "127.0.0.1"; + private static final int ZOOKEEPER_START_PORT = 62181; + private static final int TEST_JVM_COUNT_SINGLE_JVM = 1; + private static final int TEST_JVM_COUNT_MULTI_JVM = 3; + private static final int TEST_THREAD_COUNT_SINGLE_JVM = 64; + private static final int TEST_THREAD_COUNT_MULTI_JVM = 20; + private static final int TEST_THREAD_LOOPS = 100; + + // We need to increment the Zookeeper port because sometimes the port is not released at the end + // of the test for a few seconds. + private static int nextZookeeperPort = ZOOKEEPER_START_PORT; + private int zookeeperPort; + + @Rule + public final TemporaryFolder folder = new TemporaryFolder(); + + private ZooKeeperServerServiceProvider zooKeeperServerServiceProvider; + + /** + * Configure. + * + * @throws Exception the exception + */ + @BeforeClass + public static void configure() throws Exception { + System.setProperty(JAVA_NET_PREFER_IPV4_STACK, "true"); + final String hazelCastfileLocation = ResourceUtils.getFilePath4Resource(HAZELCAST_XML_FILE); + System.setProperty(HAZELCAST_CONFIG, hazelCastfileLocation); + + final TreeSet ipAddressSet = NetworkUtils.getIPv4NonLoopAddresses(); + + if (ipAddressSet.size() == 0) { + throw new Exception("cound not find real IP address for test"); + } + logger.info("For Infinispan, setting jgroups.tcp.address to: {}", ipAddressSet.first()); + System.setProperty("jgroups.tcp.address", ipAddressSet.first()); + + } + + /** + * Start zookeeper server. + * + * @throws Exception the exception + */ + private void startZookeeperServer() throws Exception { + final File zookeeperDirectory = folder.newFolder("zookeeperDirectory"); + + zookeeperPort = nextZookeeperPort++; + final InetSocketAddress addr = new InetSocketAddress(MessagingUtils.findPort(zookeeperPort)); + zooKeeperServerServiceProvider = new ZooKeeperServerServiceProvider(zookeeperDirectory, addr); + zooKeeperServerServiceProvider.startZookeeperServer(); + } + + /** + * Stop zookeeper server. + */ + private void stopZookeeperServer() { + if (zooKeeperServerServiceProvider != null) { + zooKeeperServerServiceProvider.stopZookeeperServer(); + } + } + + /** + * Test concurrent context jvm local var set. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextJvmLocalVarSet() throws Exception { + logger.debug("Running testConcurrentContextJVMLocalVarSet test . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + contextParameters.getLockManagerParameters().setPluginClass(JvmLocalLockManager.class.getCanonicalName()); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("JVMLocalVarSet", + TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + assertFalse(result.isEmpty()); + + final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + + logger.debug("Ran testConcurrentContextJVMLocalVarSet test"); + } + + /** + * Test concurrent context jvm local no var set. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextJvmLocalNoVarSet() throws Exception { + logger.debug("Running testConcurrentContextJVMLocalNoVarSet test . . ."); + + new ContextParameters(); + final ConfigrationProvider configrationProvider = getConfigrationProvider("JVMLocalNoVarSet", + TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(Constants.TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + + logger.debug("Ran testConcurrentContextJVMLocalNoVarSet test"); + } + + /** + * Test concurrent context multi jvm no lock. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextMultiJvmNoLock() throws Exception { + logger.debug("Running testConcurrentContextMultiJVMNoLock test . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + contextParameters.getDistributorParameters().setPluginClass(JvmLocalDistributor.class.getCanonicalName()); + contextParameters.getLockManagerParameters().setPluginClass(JvmLocalLockManager.class.getCanonicalName()); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("testConcurrentContextMultiJVMNoLock", + TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + // No concurrent map so result will be zero + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(0, actual.getLongValue()); + + logger.debug("Ran testConcurrentContextMultiJVMNoLock test"); + } + + /** + * Test concurrent context hazelcast lock. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextHazelcastLock() throws Exception { + logger.debug("Running testConcurrentContextHazelcastLock test . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); + contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("HazelcastLock", + TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + + logger.debug("Ran testConcurrentContextHazelcastLock test"); + } + + /** + * Test concurrent context curator lock. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextCuratorLock() throws Exception { + logger.debug("Running testConcurrentContextCuratorLock test . . ."); + try { + startZookeeperServer(); + final ContextParameters contextParameters = new ContextParameters(); + final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); + distributorParameters.setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); + + final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); + curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); + curatorParameters.setZookeeperAddress(ZOOKEEPER_ADDRESS + ":" + zookeeperPort); + contextParameters.setLockManagerParameters(curatorParameters); + ParameterService.register(curatorParameters); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("CuratorLock", + TEST_JVM_COUNT_SINGLE_JVM, TEST_THREAD_COUNT_SINGLE_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + final int expected = TEST_JVM_COUNT_SINGLE_JVM * TEST_THREAD_COUNT_SINGLE_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + logger.debug("Ran testConcurrentContextCuratorLock test"); + } finally { + stopZookeeperServer(); + } + } + + /** + * Test concurrent context hazelcast multi jvm hazelcast lock. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextHazelcastMultiJvmHazelcastLock() throws Exception { + logger.debug("Running testConcurrentContextHazelcastMultiJVMHazelcastLock test . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); + distributorParameters.setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); + contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("HazelcastMultiHazelcastlock", + TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + logger.debug("Ran testConcurrentContextHazelcastMultiJVMHazelcastLock test"); + } + + /** + * Test concurrent context infinispan multi jvm hazelcastlock. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ + @Test + public void testConcurrentContextInfinispanMultiJvmHazelcastlock() + throws ApexModelException, IOException, ApexException { + logger.debug("Running testConcurrentContextInfinispanMultiJVMHazelcastlock test . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); + infinispanParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); + infinispanParameters.setConfigFile("infinispan/infinispan-context-test.xml"); + contextParameters.setDistributorParameters(infinispanParameters); + contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("InfinispanMultiHazelcastlock", + TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + logger.debug("Ran testConcurrentContextInfinispanMultiJVMHazelcastlock test"); + } + + /** + * Test concurrent context infinispan multi jvm curator lock. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextInfinispanMultiJvmCuratorLock() throws Exception { + logger.debug("Running testConcurrentContextInfinispanMultiJVMCuratorLock test . . ."); + + try { + startZookeeperServer(); + + final ContextParameters contextParameters = new ContextParameters(); + final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); + infinispanParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); + infinispanParameters.setConfigFile("infinispan/infinispan-context-test.xml"); + contextParameters.setDistributorParameters(infinispanParameters); + + final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); + curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); + curatorParameters.setZookeeperAddress(ZOOKEEPER_ADDRESS + ":" + zookeeperPort); + contextParameters.setLockManagerParameters(curatorParameters); + ParameterService.register(curatorParameters); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("InfinispanMultiCuratorLock", + TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); + + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + final Map result = concurrentContext.testConcurrentContext(); + + final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + } finally { + stopZookeeperServer(); + } + + logger.debug("Ran testConcurrentContextInfinispanMultiJVMCuratorLock test"); + } + + /** + * Test concurrent context hazelcast multi jvm curator lock. + * + * @throws Exception the exception + */ + @Test + public void testConcurrentContextHazelcastMultiJvmCuratorLock() throws Exception { + logger.debug("Running testConcurrentContextHazelcastMultiJVMCuratorLock test . . ."); + + try { + startZookeeperServer(); + + final ContextParameters contextParameters = new ContextParameters(); + contextParameters.getDistributorParameters() + .setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); + + final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); + curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); + curatorParameters.setZookeeperAddress(ZOOKEEPER_ADDRESS + ":" + zookeeperPort); + contextParameters.setLockManagerParameters(curatorParameters); + ParameterService.register(curatorParameters); + + final ConfigrationProvider configrationProvider = getConfigrationProvider("HazelcastMultiCuratorLock", + TEST_JVM_COUNT_MULTI_JVM, TEST_THREAD_COUNT_MULTI_JVM, TEST_THREAD_LOOPS); + final Map result = + new ConcurrentContext(configrationProvider).testConcurrentContext(); + + final int expected = TEST_JVM_COUNT_MULTI_JVM * TEST_THREAD_COUNT_MULTI_JVM * TEST_THREAD_LOOPS; + final TestContextLongItem actual = result.get(TEST_VALUE); + assertNotNull(actual); + assertEquals(expected, actual.getLongValue()); + } finally { + stopZookeeperServer(); + } + logger.debug("Ran testConcurrentContextHazelcastMultiJVMCuratorLock test"); + } + + /** + * Gets the configration provider. + * + * @param testType the test type + * @param jvmCount the jvm count + * @param threadCount the thread count + * @param threadLoops the thread loops + * @return the configration provider + */ + ConfigrationProvider getConfigrationProvider(final String testType, final int jvmCount, final int threadCount, + final int threadLoops) { + return new ConfigrationProviderImpl(testType, jvmCount, threadCount, threadLoops, 16, + LockType.WRITE_LOCK_SINGLE_VALUE_UPDATE.getValue()) { + @Override + public Map getContextAlbumInitValues() { + final Map initValues = super.getContextAlbumInitValues(); + initValues.put(TEST_VALUE, new TestContextLongItem(0L)); + return initValues; + } + + }; + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexActionListener.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexActionListener.java deleted file mode 100644 index fa79843e9..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexActionListener.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.engine; - -import java.util.ArrayList; -import java.util.List; - -import org.onap.policy.apex.core.engine.engine.EnEventListener; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The listener interface for receiving testApexAction events. The class that is interested in - * processing a testApexAction event implements this interface, and the object created with that - * class is registered with a component using the component's addTestApexActionListener - * method. When the testApexAction event occurs, that object's appropriate method is invoked. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestApexActionListener implements EnEventListener { - private static final XLogger logger = XLoggerFactory.getXLogger(TestApexActionListener.class); - - private List resultEvents = new ArrayList<>(); - - private final String id; - - /** - * Instantiates a new test apex action listener. - * - * @param id the id - */ - public TestApexActionListener(final String id) { - this.id = id; - } - - /** - * Gets the result. - * - * @param allowNulls if true and the returned event is null, then return, otherwise wait until - * an event is returned. - * @return the result - */ - public EnEvent getResult(final boolean allowNulls) { - EnEvent result = null; - while (true) { - while (resultEvents.isEmpty()) { - ThreadUtilities.sleep(100); - } - result = resultEvents.remove(0); - if (result != null || allowNulls) { - break; - } - } - return result; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.engine.engine.EnEventListener#onEnEvent(org.onap.policy.apex.core. - * engine.event.EnEvent) - */ - @Override - public void onEnEvent(final EnEvent actionEvent) { - ThreadUtilities.sleep(100); - if (actionEvent != null) { - logger.info("Action event from engine: {}", actionEvent.getName()); - } - resultEvents.add(actionEvent); - } - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - return id; - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngine.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngine.java deleted file mode 100644 index b087552eb..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngine.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.engine; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.ApexEngine; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class TestApexEngine { - // Logger for this class - private static final XLogger logger = XLoggerFactory.getXLogger(TestApexEngine.class); - - /** - * Instantiates a new test apex engine. - * - * @param axLogicExecutorType the type of logic executor to use to construct the sample policy - * model for this test - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public TestApexEngine(final String axLogicExecutorType, final EngineParameters parameters) - throws ApexException, InterruptedException, IOException { - logger.debug("Running TestApexEngine test for + " + axLogicExecutorType + "logic . . ."); - - final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel(axLogicExecutorType); - assertNotNull(apexPolicyModel); - final AxArtifactKey key = new AxArtifactKey("TestApexEngine", "0.0.1"); - - final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(key); - final TestApexActionListener listener = new TestApexActionListener("Test"); - apexEngine.addEventListener("listener", listener); - apexEngine.updateModel(apexPolicyModel); - apexEngine.start(); - - for (final AxEvent axEvent : apexPolicyModel.getEvents().getEventMap().values()) { - final EnEvent event = apexEngine.createEvent(axEvent.getKey()); - - final Date aDate = new Date(1433453067123L); - final Map eventDataMap = new HashMap(); - eventDataMap.put("TestSlogan", "This is a test slogan for event " + event.getName()); - eventDataMap.put("TestMatchCase", new Byte((byte) 123)); - eventDataMap.put("TestTimestamp", aDate.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - event.putAll(eventDataMap); - - apexEngine.handleEvent(event); - } - - EnEvent result = listener.getResult(false); - logger.debug("result 1 is:" + result); - checkResult(result); - result = listener.getResult(false); - logger.debug("result 2 is:" + result); - checkResult(result); - - final Map> apexContext = apexEngine.getEngineContext(); - assertNotNull(apexContext); - apexEngine.stop(); - } - - /** - * Check result. - * - * @param result the result - */ - private void checkResult(final EnEvent result) { - if (result.getExceptionMessage() == null) { - assertTrue(result.getName().equals("Event0004") || result.getName().equals("Event0104")); - - assertTrue(((String) result.get("TestSlogan")).startsWith("This is a test slogan for event ")); - assertTrue(((String) result.get("TestSlogan")).contains(result.getName().substring(0, 8))); - - assertEquals((byte) 123, result.get("TestMatchCase")); - assertEquals(34.5445667, result.get("TestTemperature")); - assertTrue( - (Byte) result.get("TestMatchCaseSelected") >= 0 && (Byte) result.get("TestMatchCaseSelected") <= 4); - assertTrue((Byte) result.get("TestEstablishCaseSelected") >= 0 - && (Byte) result.get("TestEstablishCaseSelected") <= 4); - assertTrue((Byte) result.get("TestDecideCaseSelected") >= 0 - && (Byte) result.get("TestDecideCaseSelected") <= 4); - assertTrue((Byte) result.get("TestActCaseSelected") >= 0 && (Byte) result.get("TestActCaseSelected") <= 4); - } else { - assertTrue(result.getName().equals("Event0001") || result.getName().equals("Event0104")); - - assertTrue(((String) result.get("TestSlogan")).startsWith("This is a test slogan for event ")); - assertTrue(((String) result.get("TestSlogan")).contains(result.getName().substring(0, 8))); - - assertEquals((byte) 123, result.get("TestMatchCase")); - assertEquals(34.5445667, result.get("TestTemperature")); - } - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJRuby.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJRuby.java deleted file mode 100644 index 916795deb..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJRuby.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.engine; - -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.plugins.executor.jruby.JrubyExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; - -public class TestApexEngineJRuby { - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("JRUBY", new JrubyExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test apex engine. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testApexEngineJRuby() throws ApexException, InterruptedException, IOException { - new TestApexEngine("JRUBY", engineParameters); - ThreadUtilities.sleep(5000); - new TestApexEngine("JRUBY", engineParameters); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJava.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJava.java deleted file mode 100644 index c1d68760d..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJava.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.engine; - -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; - -/** - * The Class TestApexEngine_Java. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestApexEngineJava { - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test apex engine. - * - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexException the apex exception - */ - @Test - public void testApexEngineJava() throws InterruptedException, IOException, ApexException { - new TestApexEngine("JAVA", engineParameters); - new TestApexEngine("JAVA", engineParameters); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJavascript.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJavascript.java deleted file mode 100644 index 1f5c1d4b8..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJavascript.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.engine; - -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; - -public class TestApexEngineJavascript { - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test apex engine. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testApexEngineJavascript() throws ApexException, InterruptedException, IOException { - - new TestApexEngine("JAVASCRIPT", engineParameters); - new TestApexEngine("JAVASCRIPT", engineParameters); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJython.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJython.java deleted file mode 100644 index b5b0f9a78..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineJython.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.engine; - -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.plugins.executor.jython.JythonExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; - -public class TestApexEngineJython { - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("JYTHON", new JythonExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test apex engine. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testApexEngineJython() throws ApexException, InterruptedException, IOException { - new TestApexEngine("JYTHON", engineParameters); - new TestApexEngine("JYTHON", engineParameters); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMvel.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMvel.java deleted file mode 100644 index 4aab859ca..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMvel.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.engine; - -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; - -public class TestApexEngineMvel { - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test apex engine. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testApexEngineMVEL() throws ApexException, InterruptedException, IOException { - new TestApexEngine("MVEL", engineParameters); - new TestApexEngine("MVEL", engineParameters); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/event/TestEventInstantiation.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/event/TestEventInstantiation.java deleted file mode 100644 index b1542def0..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/event/TestEventInstantiation.java +++ /dev/null @@ -1,234 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.event; - -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 java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.ApexEngine; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class TestEventInstantiation. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestEventInstantiation { - // Logger for this class - private static final XLogger logger = XLoggerFactory.getXLogger(TestEventInstantiation.class); - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test event instantiation. - * - * @throws ApexModelException on errors in handling Apex models - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexException the apex exception - */ - @Test - public void testEventInstantiation() throws ApexModelException, IOException, ApexException { - final String xmlFileName = "xml/ApexModel_MVEL.xml"; - - logger.debug("Running TestEventInstantiation test on file {} . . .", xmlFileName); - - final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(apexPolicyModel); - - final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(apexPolicyModel.getKey()); - apexEngine.updateModel(apexPolicyModel); - apexEngine.start(); - - final EnEvent event = apexEngine.createEvent(new AxArtifactKey("Event0000", "0.0.1")); - - Object slogan1 = event.put("TestSlogan", "This is a slogan"); - assertNull(slogan1); - slogan1 = event.get("TestSlogan"); - assertNotNull(slogan1); - assertEquals("This is a slogan", slogan1); - - Object mc1 = event.put("TestMatchCase", new Byte("4")); - assertNull(mc1); - mc1 = event.get("TestMatchCase"); - assertNotNull(mc1); - assertEquals((byte) 4, mc1); - - Object mc2 = event.put("TestMatchCase", new Byte("16")); - assertNotNull(mc2); - assertEquals((byte) 4, mc2); - mc2 = event.get("TestMatchCase"); - assertNotNull(mc2); - assertEquals((byte) 16, mc2); - - final Date timeNow = new Date(); - Object timestamp1 = event.put("TestTimestamp", timeNow.getTime()); - assertNull(timestamp1); - timestamp1 = event.get("TestTimestamp"); - assertNotNull(timestamp1); - assertEquals(timeNow.getTime(), timestamp1); - - final double temperature = 123.456789; - Object temp1 = event.put("TestTemperature", temperature); - assertNull(temp1); - temp1 = event.get("TestTemperature"); - assertNotNull(temp1); - assertEquals(temperature, temp1); - - Object value = event.put("TestMatchCase", null); - assertEquals(16, ((Byte) value).intValue()); - value = event.get("TestMatchCase"); - assertNull(value); - - try { - event.put("TestMatchCase", "Hello"); - } catch (final Exception e) { - assertEquals( - "Event0000:0.0.1:NULL:TestMatchCase: object \"Hello\" of class \"java.lang.String\" not compatible with class \"java.lang.Byte\"", - e.getMessage()); - } - - try { - event.put("TestMatchCase", 123.45); - } catch (final Exception e) { - assertEquals( - "Event0000:0.0.1:NULL:TestMatchCase: object \"123.45\" of class \"java.lang.Double\" not compatible with class \"java.lang.Byte\"", - e.getMessage()); - } - - event.put("TestMatchCase", new Byte("16")); - - final String slogan2 = (String) event.get("TestSlogan"); - assertNotNull(slogan2); - assertEquals("This is a slogan", slogan2); - - final byte mc21 = (byte) event.get("TestMatchCase"); - assertNotNull(mc21); - assertEquals(16, mc21); - - final byte mc22 = (byte) event.get("TestMatchCase"); - assertNotNull(mc22); - assertEquals((byte) 16, mc22); - - final long timestamp2 = (Long) event.get("TestTimestamp"); - assertNotNull(timestamp2); - assertEquals(timestamp2, timestamp1); - - final double temp2 = (double) event.get("TestTemperature"); - assertNotNull(temp2); - assertTrue(temp2 == 123.456789); - - final Double temp3 = (Double) event.get("TestTemperature"); - assertNotNull(temp3); - assertTrue(temp3 == 123.456789); - - final Date aDate = new Date(1433453067123L); - final Map eventDataList = new HashMap(); - eventDataList.put("TestSlogan", "This is a test slogan"); - eventDataList.put("TestMatchCase", new Byte("123")); - eventDataList.put("TestTimestamp", aDate.getTime()); - eventDataList.put("TestTemperature", 34.5445667); - - event.putAll(eventDataList); - - final String slogan3 = (String) event.get("TestSlogan"); - assertNotNull(slogan3); - assertEquals("This is a test slogan", slogan3); - - final byte mc31 = (byte) event.get("TestMatchCase"); - assertNotNull(mc31); - assertEquals((byte) 123, mc31); - - final long timestamp3 = (Long) event.get("TestTimestamp"); - assertNotNull(timestamp3); - assertEquals(timestamp3, aDate.getTime()); - - final double temp4 = (double) event.get("TestTemperature"); - assertNotNull(temp4); - assertTrue(temp4 == 34.5445667); - - logger.debug(event.toString()); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexModelExport.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexModelExport.java deleted file mode 100644 index 6b72faa8f..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexModelExport.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.model.policymodel.handling.PolicyModelSplitter; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class TestApexModelReader tests Apex model reading. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestApexModelExport { - private static final XLogger logger = XLoggerFactory.getXLogger(TestApexModelExport.class); - - private AxPolicyModel model = null; - - @Before - public void initApexModelSmall() throws ApexException { - model = new TestApexSamplePolicyModelCreator("MVEL").getModel(); - } - - @Test - public void testApexModelExport() throws Exception { - logger.info("Starting test: testApexModelExport"); - - final List exportPolicyList = new ArrayList(); - exportPolicyList.addAll(model.getPolicies().getPolicyMap().keySet()); - - final AxPolicyModel exportedModel0 = PolicyModelSplitter.getSubPolicyModel(model, exportPolicyList); - - // Remove unused schemas and their keys - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem000", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem001", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem002", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem003", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem004", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem005", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem006", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem007", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem008", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem009", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem00A", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem00B", "0.0.1")); - model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem00C", "0.0.1")); - - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem000", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem001", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem002", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem003", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem004", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem005", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem006", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem007", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem008", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem009", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem00A", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem00B", "0.0.1")); - model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem00C", "0.0.1")); - - assertTrue(model.equals(exportedModel0)); - - exportPolicyList.remove(0); - - final AxPolicyModel exportedModel1 = PolicyModelSplitter.getSubPolicyModel(model, exportPolicyList); - assertFalse(model.equals(exportedModel1)); - assertTrue(model.getPolicies().get("Policy1").equals(exportedModel1.getPolicies().get("Policy1"))); - - exportPolicyList.clear(); - exportPolicyList.add(new AxArtifactKey("NonExistentPolicy", "0.0.1")); - - try { - final AxPolicyModel emptyExportedModel = PolicyModelSplitter.getSubPolicyModel(model, exportPolicyList); - assertNotNull(emptyExportedModel); - } catch (final Exception e) { - assertTrue(e.getMessage() - .equals("new model is invalid:\n" + "***validation of model failed***\n" - + "AxPolicies:Policies:0.0.1 - policyMap may not be null or empty\n" - + "AxEvents:Events:0.0.1 - eventMap may not be null or empty\n" - + "********************************")); - } - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexPolicyModelAnalysis.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexPolicyModelAnalysis.java deleted file mode 100644 index 91153d698..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexPolicyModelAnalysis.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.model.policymodel.handling.PolicyAnalyser; -import org.onap.policy.apex.model.policymodel.handling.PolicyAnalysisResult; - -public class TestApexPolicyModelAnalysis { - @Test - public void testApexPolicyModelAnalysis() throws Exception { - final AxPolicyModel model = new TestApexSamplePolicyModelCreator("MVEL").getModel(); - final PolicyAnalysisResult result = new PolicyAnalyser().analyse(model); - - assertNotNull(result); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyCreateModelFiles.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyCreateModelFiles.java deleted file mode 100644 index 384ad5114..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyCreateModelFiles.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestApexSamplePolicyCreateModelFiles { - @Test - public void testModelWriteReadJava() throws Exception { - final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JAVA"); - final TestApexModel testApexPolicyModel = - new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); - testApexPolicyModel.testApexModelWriteReadXml(); - testApexPolicyModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadJavascript() throws Exception { - final TestApexSamplePolicyModelCreator apexPolicyModelCreator = - new TestApexSamplePolicyModelCreator("JAVASCRIPT"); - final TestApexModel testApexPolicyModel = - new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); - testApexPolicyModel.testApexModelWriteReadXml(); - testApexPolicyModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadJRuby() throws Exception { - final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JRUBY"); - final TestApexModel testApexPolicyModel = - new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); - testApexPolicyModel.testApexModelWriteReadXml(); - testApexPolicyModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadJython() throws Exception { - final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JYTHON"); - final TestApexModel testApexPolicyModel = - new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); - testApexPolicyModel.testApexModelWriteReadXml(); - testApexPolicyModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadMvel() throws Exception { - final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("MVEL"); - final TestApexModel testApexPolicyModel = - new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); - testApexPolicyModel.testApexModelWriteReadXml(); - testApexPolicyModel.testApexModelWriteReadJson(); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyDBWrite.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyDBWrite.java deleted file mode 100644 index 45314672e..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyDBWrite.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestApexSamplePolicyDBWrite { - private Connection connection; - TestApexModel testApexModel; - - @Before - public void setup() throws Exception { - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("MVEL"); - testApexModel = new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); - } - - @After - public void teardown() throws Exception { - connection.close(); - } - - @Test - public void testModelWriteReadJPA() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass(DefaultApexDao.class.getCanonicalName()); - DaoParameters.setPersistenceUnit("SampleModelTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModel.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModel.java deleted file mode 100644 index 36810b44b..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModel.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -import static org.junit.Assert.assertTrue; - -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestApexSamplePolicyModel { - private static final String VALID_MODEL_STRING = "***validation of model successful***"; - private Connection connection; - private TestApexModel testApexModel; - - @Before - public void setup() throws Exception { - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = - new TestApexModel(AxPolicyModel.class, new TestApexSamplePolicyModelCreator("MVEL")); - } - - @After - public void teardown() throws Exception { - connection.close(); - } - - @Test - public void testModelValid() throws Exception { - final AxValidationResult result = testApexModel.testApexModelValid(); - assertTrue(result.toString().equals(VALID_MODEL_STRING)); - } - - @Test - public void testModelWriteReadXML() throws Exception { - testApexModel.testApexModelWriteReadXml(); - } - - @Test - public void testModelWriteReadJSON() throws Exception { - testApexModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadJPA() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass(DefaultApexDao.class.getCanonicalName()); - DaoParameters.setPersistenceUnit("SampleModelTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } - - -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModelCreator.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModelCreator.java deleted file mode 100644 index d5ba53699..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestApexSamplePolicyModelCreator.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestApexSamplePolicyModelCreator implements TestApexModelCreator { - private String logicExecutorType; - - public TestApexSamplePolicyModelCreator(final String logicExecutorType) { - this.logicExecutorType = logicExecutorType; - } - - @Override - public AxPolicyModel getModel() { - return new SampleDomainModelFactory().getSamplePolicyModel(logicExecutorType); - } - - @Override - public AxPolicyModel getMalstructuredModel() { - return null; - } - - @Override - public AxPolicyModel getObservationModel() { - return null; - } - - @Override - public AxPolicyModel getWarningModel() { - return getModel(); - } - - @Override - public AxPolicyModel getInvalidModel() { - return null; - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateDifferentModels.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateDifferentModels.java deleted file mode 100644 index 20159a3bf..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateDifferentModels.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -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 org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.ContextAlbum; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineImpl; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.plugins.executor.test.script.engine.TestApexActionListener; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class TestApexEngine. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContextUpdateDifferentModels { - // Logger for this class - private static final XLogger logger = XLoggerFactory.getXLogger(TestContextUpdateDifferentModels.class); - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - @Test - public void testContextUpdateDifferentModels() throws ApexException, InterruptedException, IOException { - logger.debug("Running test testContextUpdateDifferentModels . . ."); - - final AxPolicyModel apexModelSample = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(apexModelSample); - - final ApexEngineImpl apexEngine = - (ApexEngineImpl) new ApexEngineFactory().createApexEngine(new AxArtifactKey("TestApexEngine", "0.0.1")); - final TestApexActionListener listener = new TestApexActionListener("Test"); - apexEngine.addEventListener("listener", listener); - apexEngine.updateModel(apexModelSample); - apexEngine.start(); - - apexEngine.stop(); - - final AxPolicyModel someSpuriousModel = new AxPolicyModel(new AxArtifactKey("SomeSpuriousModel", "0.0.1")); - assertNotNull(someSpuriousModel); - - try { - apexEngine.updateModel(null); - fail("null model should throw an exception"); - } catch (final ApexException e) { - assertEquals("updateModel()<-TestApexEngine:0.0.1, Apex model is not defined, it has a null value", - e.getMessage()); - } - assertEquals(apexEngine.getInternalContext().getContextAlbums().size(), - apexModelSample.getAlbums().getAlbumsMap().size()); - for (final ContextAlbum contextAlbum : apexEngine.getInternalContext().getContextAlbums().values()) { - assertTrue( - contextAlbum.getAlbumDefinition().equals(apexModelSample.getAlbums().get(contextAlbum.getKey()))); - } - - apexEngine.updateModel(someSpuriousModel); - assertEquals(apexEngine.getInternalContext().getContextAlbums().size(), - someSpuriousModel.getAlbums().getAlbumsMap().size()); - for (final ContextAlbum contextAlbum : apexEngine.getInternalContext().getContextAlbums().values()) { - assertTrue( - contextAlbum.getAlbumDefinition().equals(someSpuriousModel.getAlbums().get(contextAlbum.getKey()))); - } - - apexEngine.clear(); - - logger.debug("Ran test testContextUpdateDifferentModels"); - } - -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateModel.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateModel.java deleted file mode 100644 index d5605ea4c..000000000 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/handling/TestContextUpdateModel.java +++ /dev/null @@ -1,202 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.executor.test.script.handling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.ContextException; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.ApexEngine; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.plugins.executor.test.script.engine.TestApexActionListener; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class TestApexEngine. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContextUpdateModel { - // Logger for this class - private static final XLogger logger = XLoggerFactory.getXLogger(TestContextUpdateModel.class); - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - ParameterService.register(engineParameters); - } - - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - @Test - public void testContextUpdateModel() throws ApexException, InterruptedException, IOException { - final AxArtifactKey key = new AxArtifactKey("TestApexEngine", "0.0.1"); - - final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(key); - final TestApexActionListener listener = new TestApexActionListener("Test"); - apexEngine.addEventListener("listener", listener); - - final AxPolicyModel model1 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(model1); - assertEquals(2, model1.getPolicies().getPolicyMap().size()); - - apexEngine.updateModel(model1); - apexEngine.start(); - sendEvent(apexEngine, listener, "Event0000", true); - sendEvent(apexEngine, listener, "Event0100", true); - apexEngine.stop(); - - final AxPolicyModel model2 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(model2); - model2.getPolicies().getPolicyMap().remove(new AxArtifactKey("Policy0", "0.0.1")); - assertEquals(1, model2.getPolicies().getPolicyMap().size()); - apexEngine.updateModel(model2); - apexEngine.start(); - sendEvent(apexEngine, listener, "Event0000", false); - sendEvent(apexEngine, listener, "Event0100", true); - apexEngine.stop(); - - final AxPolicyModel model3 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(model3); - model3.getPolicies().getPolicyMap().remove(new AxArtifactKey("Policy1", "0.0.1")); - assertEquals(1, model3.getPolicies().getPolicyMap().size()); - apexEngine.updateModel(model3); - apexEngine.start(); - sendEvent(apexEngine, listener, "Event0000", true); - sendEvent(apexEngine, listener, "Event0100", false); - apexEngine.stop(); - - final AxPolicyModel model4 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(model4); - assertEquals(2, model4.getPolicies().getPolicyMap().size()); - apexEngine.updateModel(model4); - apexEngine.start(); - sendEvent(apexEngine, listener, "Event0100", true); - sendEvent(apexEngine, listener, "Event0000", true); - apexEngine.stop(); - - apexEngine.clear(); - } - - @After - public void testContextUpdateModelAfter() {} - - private void sendEvent(final ApexEngine apexEngine, final TestApexActionListener listener, final String eventName, - final boolean shouldWork) throws ContextException { - final Date aDate = new Date(1433453067123L); - final Map eventDataMap = new HashMap(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", new Byte((byte) 123)); - eventDataMap.put("TestTimestamp", aDate.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final EnEvent event0 = apexEngine.createEvent(new AxArtifactKey(eventName, "0.0.1")); - event0.putAll(eventDataMap); - apexEngine.handleEvent(event0); - - final EnEvent result = listener.getResult(true); - logger.debug("result 1 is:" + result); - checkResult(result, shouldWork); - } - - private void checkResult(final EnEvent result, final boolean shouldWork) { - if (!shouldWork) { - assertNotNull(result.getExceptionMessage()); - return; - } - - assertTrue(result.getName().equals("Event0004") || result.getName().equals("Event0104")); - - if (result.getName().equals("Event0004")) { - assertEquals("This is a test slogan", result.get("TestSlogan")); - assertEquals((byte) 123, result.get("TestMatchCase")); - assertEquals(34.5445667, result.get("TestTemperature")); - assertEquals((byte) 2, result.get("TestMatchCaseSelected")); - assertEquals((byte) 0, result.get("TestEstablishCaseSelected")); - assertEquals((byte) 1, result.get("TestDecideCaseSelected")); - assertEquals((byte) 3, result.get("TestActCaseSelected")); - } else { - assertEquals("This is a test slogan", result.get("TestSlogan")); - assertEquals((byte) 123, result.get("TestMatchCase")); - assertEquals(34.5445667, result.get("TestTemperature")); - assertEquals((byte) 1, result.get("TestMatchCaseSelected")); - assertEquals((byte) 3, result.get("TestEstablishCaseSelected")); - assertEquals((byte) 1, result.get("TestDecideCaseSelected")); - assertEquals((byte) 2, result.get("TestActCaseSelected")); - } - } -} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexActionListener.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexActionListener.java new file mode 100644 index 000000000..2860f1736 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexActionListener.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.engine; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.policy.apex.core.engine.engine.EnEventListener; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The listener interface for receiving testApexAction events. The class that is interested in + * processing a testApexAction event implements this interface, and the object created with that + * class is registered with a component using the component's addTestApexActionListener + * method. When the testApexAction event occurs, that object's appropriate method is invoked. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestApexActionListener implements EnEventListener { + private static final XLogger logger = XLoggerFactory.getXLogger(TestApexActionListener.class); + + private List resultEvents = new ArrayList<>(); + + private final String id; + + /** + * Instantiates a new test apex action listener. + * + * @param id the id + */ + public TestApexActionListener(final String id) { + this.id = id; + } + + /** + * Gets the result. + * + * @param allowNulls if true and the returned event is null, then return, otherwise wait until + * an event is returned. + * @return the result + */ + public EnEvent getResult(final boolean allowNulls) { + EnEvent result = null; + while (true) { + while (resultEvents.isEmpty()) { + ThreadUtilities.sleep(100); + } + result = resultEvents.remove(0); + if (result != null || allowNulls) { + break; + } + } + return result; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.engine.engine.EnEventListener#onEnEvent(org.onap.policy.apex.core. + * engine.event.EnEvent) + */ + @Override + public void onEnEvent(final EnEvent actionEvent) { + ThreadUtilities.sleep(100); + if (actionEvent != null) { + logger.info("Action event from engine: {}", actionEvent.getName()); + } + resultEvents.add(actionEvent); + } + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngine.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngine.java new file mode 100644 index 000000000..cb51a8e9e --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngine.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.ApexEngine; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +public class TestApexEngine { + // Logger for this class + private static final XLogger logger = XLoggerFactory.getXLogger(TestApexEngine.class); + + /** + * Instantiates a new test apex engine. + * + * @param axLogicExecutorType the type of logic executor to use to construct the sample policy + * model for this test + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public TestApexEngine(final String axLogicExecutorType, final EngineParameters parameters) + throws ApexException, InterruptedException, IOException { + logger.debug("Running TestApexEngine test for + " + axLogicExecutorType + "logic . . ."); + + final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel(axLogicExecutorType); + assertNotNull(apexPolicyModel); + final AxArtifactKey key = new AxArtifactKey("TestApexEngine", "0.0.1"); + + final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(key); + final TestApexActionListener listener = new TestApexActionListener("Test"); + apexEngine.addEventListener("listener", listener); + apexEngine.updateModel(apexPolicyModel); + apexEngine.start(); + + for (final AxEvent axEvent : apexPolicyModel.getEvents().getEventMap().values()) { + final EnEvent event = apexEngine.createEvent(axEvent.getKey()); + + final Date aDate = new Date(1433453067123L); + final Map eventDataMap = new HashMap(); + eventDataMap.put("TestSlogan", "This is a test slogan for event " + event.getName()); + eventDataMap.put("TestMatchCase", new Byte((byte) 123)); + eventDataMap.put("TestTimestamp", aDate.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + event.putAll(eventDataMap); + + apexEngine.handleEvent(event); + } + + EnEvent result = listener.getResult(false); + logger.debug("result 1 is:" + result); + checkResult(result); + result = listener.getResult(false); + logger.debug("result 2 is:" + result); + checkResult(result); + + final Map> apexContext = apexEngine.getEngineContext(); + assertNotNull(apexContext); + apexEngine.stop(); + } + + /** + * Check result. + * + * @param result the result + */ + private void checkResult(final EnEvent result) { + if (result.getExceptionMessage() == null) { + assertTrue(result.getName().equals("Event0004") || result.getName().equals("Event0104")); + + assertTrue(((String) result.get("TestSlogan")).startsWith("This is a test slogan for event ")); + assertTrue(((String) result.get("TestSlogan")).contains(result.getName().substring(0, 8))); + + assertEquals((byte) 123, result.get("TestMatchCase")); + assertEquals(34.5445667, result.get("TestTemperature")); + assertTrue( + (Byte) result.get("TestMatchCaseSelected") >= 0 && (Byte) result.get("TestMatchCaseSelected") <= 4); + assertTrue((Byte) result.get("TestEstablishCaseSelected") >= 0 + && (Byte) result.get("TestEstablishCaseSelected") <= 4); + assertTrue((Byte) result.get("TestDecideCaseSelected") >= 0 + && (Byte) result.get("TestDecideCaseSelected") <= 4); + assertTrue((Byte) result.get("TestActCaseSelected") >= 0 && (Byte) result.get("TestActCaseSelected") <= 4); + } else { + assertTrue(result.getName().equals("Event0001") || result.getName().equals("Event0104")); + + assertTrue(((String) result.get("TestSlogan")).startsWith("This is a test slogan for event ")); + assertTrue(((String) result.get("TestSlogan")).contains(result.getName().substring(0, 8))); + + assertEquals((byte) 123, result.get("TestMatchCase")); + assertEquals(34.5445667, result.get("TestTemperature")); + } + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJRuby.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJRuby.java new file mode 100644 index 000000000..108e73ac1 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJRuby.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.engine; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.plugins.executor.jruby.JrubyExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; + +/** + * The Class TestApexEngineJRuby. + */ +public class TestApexEngineJRuby { + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("JRUBY", new JrubyExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test apex engine. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testApexEngineJRuby() throws ApexException, InterruptedException, IOException { + new TestApexEngine("JRUBY", engineParameters); + ThreadUtilities.sleep(5000); + new TestApexEngine("JRUBY", engineParameters); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJava.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJava.java new file mode 100644 index 000000000..b551a061e --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJava.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.engine; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; + +/** + * The Class TestApexEngine_Java. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestApexEngineJava { + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test apex engine. + * + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ + @Test + public void testApexEngineJava() throws InterruptedException, IOException, ApexException { + new TestApexEngine("JAVA", engineParameters); + new TestApexEngine("JAVA", engineParameters); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJavascript.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJavascript.java new file mode 100644 index 000000000..51e39cfe1 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJavascript.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.engine; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; + +/** + * The Class TestApexEngineJavascript. + */ +public class TestApexEngineJavascript { + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test apex engine. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testApexEngineJavascript() throws ApexException, InterruptedException, IOException { + + new TestApexEngine("JAVASCRIPT", engineParameters); + new TestApexEngine("JAVASCRIPT", engineParameters); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJython.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJython.java new file mode 100644 index 000000000..163a60d20 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineJython.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.engine; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.plugins.executor.jython.JythonExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; + +/** + * The Class TestApexEngineJython. + */ +public class TestApexEngineJython { + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("JYTHON", new JythonExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test apex engine. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testApexEngineJython() throws ApexException, InterruptedException, IOException { + new TestApexEngine("JYTHON", engineParameters); + new TestApexEngine("JYTHON", engineParameters); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineMvel.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineMvel.java new file mode 100644 index 000000000..604105a03 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/engine/TestApexEngineMvel.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.engine; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; + +/** + * The Class TestApexEngineMvel. + */ +public class TestApexEngineMvel { + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test apex engine. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testApexEngineMvel() throws ApexException, InterruptedException, IOException { + new TestApexEngine("MVEL", engineParameters); + new TestApexEngine("MVEL", engineParameters); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/event/TestEventInstantiation.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/event/TestEventInstantiation.java new file mode 100644 index 000000000..1ae258b01 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/event/TestEventInstantiation.java @@ -0,0 +1,238 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.event; + +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 java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.ApexEngine; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestEventInstantiation. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestEventInstantiation { + // Logger for this class + private static final XLogger logger = XLoggerFactory.getXLogger(TestEventInstantiation.class); + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test event instantiation. + * + * @throws ApexModelException on errors in handling Apex models + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ + @Test + public void testEventInstantiation() throws ApexModelException, IOException, ApexException { + final String xmlFileName = "xml/ApexModel_MVEL.xml"; + + logger.debug("Running TestEventInstantiation test on file {} . . .", xmlFileName); + + final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(apexPolicyModel); + + final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(apexPolicyModel.getKey()); + apexEngine.updateModel(apexPolicyModel); + apexEngine.start(); + + final EnEvent event = apexEngine.createEvent(new AxArtifactKey("Event0000", "0.0.1")); + + Object slogan1 = event.put("TestSlogan", "This is a slogan"); + assertNull(slogan1); + slogan1 = event.get("TestSlogan"); + assertNotNull(slogan1); + assertEquals("This is a slogan", slogan1); + + Object mc1 = event.put("TestMatchCase", new Byte("4")); + assertNull(mc1); + mc1 = event.get("TestMatchCase"); + assertNotNull(mc1); + assertEquals((byte) 4, mc1); + + Object mc2 = event.put("TestMatchCase", new Byte("16")); + assertNotNull(mc2); + assertEquals((byte) 4, mc2); + mc2 = event.get("TestMatchCase"); + assertNotNull(mc2); + assertEquals((byte) 16, mc2); + + final Date timeNow = new Date(); + Object timestamp1 = event.put("TestTimestamp", timeNow.getTime()); + assertNull(timestamp1); + timestamp1 = event.get("TestTimestamp"); + assertNotNull(timestamp1); + assertEquals(timeNow.getTime(), timestamp1); + + final double temperature = 123.456789; + Object temp1 = event.put("TestTemperature", temperature); + assertNull(temp1); + temp1 = event.get("TestTemperature"); + assertNotNull(temp1); + assertEquals(temperature, temp1); + + Object value = event.put("TestMatchCase", null); + assertEquals(16, ((Byte) value).intValue()); + value = event.get("TestMatchCase"); + assertNull(value); + + try { + event.put("TestMatchCase", "Hello"); + } catch (final Exception e) { + assertEquals("Event0000:0.0.1:NULL:TestMatchCase: object \"Hello\" of class \"java.lang.String\" " + + "not compatible with class \"java.lang.Byte\"", e.getMessage()); + } + + try { + event.put("TestMatchCase", 123.45); + } catch (final Exception e) { + assertEquals("Event0000:0.0.1:NULL:TestMatchCase: object \"123.45\" of class \"java.lang.Double\" " + + "not compatible with class \"java.lang.Byte\"", e.getMessage()); + } + + event.put("TestMatchCase", new Byte("16")); + + final String slogan2 = (String) event.get("TestSlogan"); + assertNotNull(slogan2); + assertEquals("This is a slogan", slogan2); + + final byte mc21 = (byte) event.get("TestMatchCase"); + assertNotNull(mc21); + assertEquals(16, mc21); + + final byte mc22 = (byte) event.get("TestMatchCase"); + assertNotNull(mc22); + assertEquals((byte) 16, mc22); + + final long timestamp2 = (Long) event.get("TestTimestamp"); + assertNotNull(timestamp2); + assertEquals(timestamp2, timestamp1); + + final double temp2 = (double) event.get("TestTemperature"); + assertNotNull(temp2); + assertTrue(temp2 == 123.456789); + + final Double temp3 = (Double) event.get("TestTemperature"); + assertNotNull(temp3); + assertTrue(temp3 == 123.456789); + + final Date aDate = new Date(1433453067123L); + final Map eventDataList = new HashMap(); + eventDataList.put("TestSlogan", "This is a test slogan"); + eventDataList.put("TestMatchCase", new Byte("123")); + eventDataList.put("TestTimestamp", aDate.getTime()); + eventDataList.put("TestTemperature", 34.5445667); + + event.putAll(eventDataList); + + final String slogan3 = (String) event.get("TestSlogan"); + assertNotNull(slogan3); + assertEquals("This is a test slogan", slogan3); + + final byte mc31 = (byte) event.get("TestMatchCase"); + assertNotNull(mc31); + assertEquals((byte) 123, mc31); + + final long timestamp3 = (Long) event.get("TestTimestamp"); + assertNotNull(timestamp3); + assertEquals(timestamp3, aDate.getTime()); + + final double temp4 = (double) event.get("TestTemperature"); + assertNotNull(temp4); + assertTrue(temp4 == 34.5445667); + + logger.debug(event.toString()); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexModelExport.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexModelExport.java new file mode 100644 index 000000000..1e419521f --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexModelExport.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.policymodel.handling.PolicyModelSplitter; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestApexModelReader tests Apex model reading. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestApexModelExport { + private static final XLogger logger = XLoggerFactory.getXLogger(TestApexModelExport.class); + + private AxPolicyModel model = null; + + @Before + public void initApexModelSmall() throws ApexException { + model = new TestApexSamplePolicyModelCreator("MVEL").getModel(); + } + + @Test + public void testApexModelExport() throws Exception { + logger.info("Starting test: testApexModelExport"); + + final List exportPolicyList = new ArrayList(); + exportPolicyList.addAll(model.getPolicies().getPolicyMap().keySet()); + + final AxPolicyModel exportedModel0 = PolicyModelSplitter.getSubPolicyModel(model, exportPolicyList); + + // Remove unused schemas and their keys + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem000", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem001", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem002", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem003", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem004", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem005", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem006", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem007", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem008", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem009", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem00A", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem00B", "0.0.1")); + model.getSchemas().getSchemasMap().remove(new AxArtifactKey("TestContextItem00C", "0.0.1")); + + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem000", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem001", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem002", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem003", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem004", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem005", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem006", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem007", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem008", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem009", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem00A", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem00B", "0.0.1")); + model.getKeyInformation().getKeyInfoMap().remove(new AxArtifactKey("TestContextItem00C", "0.0.1")); + + assertTrue(model.equals(exportedModel0)); + + exportPolicyList.remove(0); + + final AxPolicyModel exportedModel1 = PolicyModelSplitter.getSubPolicyModel(model, exportPolicyList); + assertFalse(model.equals(exportedModel1)); + assertTrue(model.getPolicies().get("Policy1").equals(exportedModel1.getPolicies().get("Policy1"))); + + exportPolicyList.clear(); + exportPolicyList.add(new AxArtifactKey("NonExistentPolicy", "0.0.1")); + + try { + final AxPolicyModel emptyExportedModel = PolicyModelSplitter.getSubPolicyModel(model, exportPolicyList); + assertNotNull(emptyExportedModel); + } catch (final Exception e) { + assertTrue(e.getMessage() + .equals("new model is invalid:\n" + "***validation of model failed***\n" + + "AxPolicies:Policies:0.0.1 - policyMap may not be null or empty\n" + + "AxEvents:Events:0.0.1 - eventMap may not be null or empty\n" + + "********************************")); + } + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexPolicyModelAnalysis.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexPolicyModelAnalysis.java new file mode 100644 index 000000000..abcd22a47 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexPolicyModelAnalysis.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.policymodel.handling.PolicyAnalyser; +import org.onap.policy.apex.model.policymodel.handling.PolicyAnalysisResult; + +public class TestApexPolicyModelAnalysis { + @Test + public void testApexPolicyModelAnalysis() throws Exception { + final AxPolicyModel model = new TestApexSamplePolicyModelCreator("MVEL").getModel(); + final PolicyAnalysisResult result = new PolicyAnalyser().analyse(model); + + assertNotNull(result); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java new file mode 100644 index 000000000..a00729268 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class TestApexSamplePolicyCreateModelFiles { + @Test + public void testModelWriteReadJava() throws Exception { + final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JAVA"); + final TestApexModel testApexPolicyModel = + new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); + testApexPolicyModel.testApexModelWriteReadXml(); + testApexPolicyModel.testApexModelWriteReadJson(); + } + + @Test + public void testModelWriteReadJavascript() throws Exception { + final TestApexSamplePolicyModelCreator apexPolicyModelCreator = + new TestApexSamplePolicyModelCreator("JAVASCRIPT"); + final TestApexModel testApexPolicyModel = + new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); + testApexPolicyModel.testApexModelWriteReadXml(); + testApexPolicyModel.testApexModelWriteReadJson(); + } + + @Test + public void testModelWriteReadJRuby() throws Exception { + final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JRUBY"); + final TestApexModel testApexPolicyModel = + new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); + testApexPolicyModel.testApexModelWriteReadXml(); + testApexPolicyModel.testApexModelWriteReadJson(); + } + + @Test + public void testModelWriteReadJython() throws Exception { + final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JYTHON"); + final TestApexModel testApexPolicyModel = + new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); + testApexPolicyModel.testApexModelWriteReadXml(); + testApexPolicyModel.testApexModelWriteReadJson(); + } + + @Test + public void testModelWriteReadMvel() throws Exception { + final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("MVEL"); + final TestApexModel testApexPolicyModel = + new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); + testApexPolicyModel.testApexModelWriteReadXml(); + testApexPolicyModel.testApexModelWriteReadJson(); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyDbWrite.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyDbWrite.java new file mode 100644 index 000000000..e863a990a --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyDbWrite.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +/** + * The Class TestApexSamplePolicyDbWrite. + */ +public class TestApexSamplePolicyDbWrite { + private Connection connection; + TestApexModel testApexModel; + + /** + * Setup. + * + * @throws Exception the exception + */ + @Before + public void setup() throws Exception { + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("MVEL"); + testApexModel = new TestApexModel(AxPolicyModel.class, apexPolicyModelCreator); + } + + /** + * Teardown. + * + * @throws Exception the exception + */ + @After + public void teardown() throws Exception { + connection.close(); + } + + /** + * Test model write read jpa. + * + * @throws Exception the exception + */ + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass(DefaultApexDao.class.getCanonicalName()); + DaoParameters.setPersistenceUnit("SampleModelTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModel.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModel.java new file mode 100644 index 000000000..1e7daad03 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModel.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +import static org.junit.Assert.assertTrue; + +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +/** + * The Class TestApexSamplePolicyModel. + */ +public class TestApexSamplePolicyModel { + private static final String VALID_MODEL_STRING = "***validation of model successful***"; + private Connection connection; + private TestApexModel testApexModel; + + /** + * Setup. + * + * @throws Exception the exception + */ + @Before + public void setup() throws Exception { + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = + new TestApexModel(AxPolicyModel.class, new TestApexSamplePolicyModelCreator("MVEL")); + } + + /** + * Teardown. + * + * @throws Exception the exception + */ + @After + public void teardown() throws Exception { + connection.close(); + } + + /** + * Test model valid. + * + * @throws Exception the exception + */ + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + /** + * Test model write read xml. + * + * @throws Exception the exception + */ + @Test + public void testModelWriteReadXml() throws Exception { + testApexModel.testApexModelWriteReadXml(); + } + + /** + * Test model write read json. + * + * @throws Exception the exception + */ + @Test + public void testModelWriteReadJson() throws Exception { + testApexModel.testApexModelWriteReadJson(); + } + + /** + * Test model write read jpa. + * + * @throws Exception the exception + */ + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass(DefaultApexDao.class.getCanonicalName()); + DaoParameters.setPersistenceUnit("SampleModelTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } + + +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModelCreator.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModelCreator.java new file mode 100644 index 000000000..7e44dd32e --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyModelCreator.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; + +/** + * The Class TestApexSamplePolicyModelCreator. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestApexSamplePolicyModelCreator implements TestApexModelCreator { + private String logicExecutorType; + + /** + * Instantiates a new test apex sample policy model creator. + * + * @param logicExecutorType the logic executor type + */ + public TestApexSamplePolicyModelCreator(final String logicExecutorType) { + this.logicExecutorType = logicExecutorType; + } + + /* (non-Javadoc) + * @see org.onap.policy.apex.model.basicmodel.handling.ApexModelCreator#getModel() + */ + @Override + public AxPolicyModel getModel() { + return new SampleDomainModelFactory().getSamplePolicyModel(logicExecutorType); + } + + /* (non-Javadoc) + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getMalstructuredModel() + */ + @Override + public AxPolicyModel getMalstructuredModel() { + return null; + } + + /* (non-Javadoc) + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getObservationModel() + */ + @Override + public AxPolicyModel getObservationModel() { + return null; + } + + /* (non-Javadoc) + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getWarningModel() + */ + @Override + public AxPolicyModel getWarningModel() { + return getModel(); + } + + /* (non-Javadoc) + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getInvalidModel() + */ + @Override + public AxPolicyModel getInvalidModel() { + return null; + } +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateDifferentModels.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateDifferentModels.java new file mode 100644 index 000000000..e8c45b201 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateDifferentModels.java @@ -0,0 +1,161 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +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 org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.ContextAlbum; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineImpl; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.onap.policy.apex.testsuites.integration.executor.engine.TestApexActionListener; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestApexEngine. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContextUpdateDifferentModels { + // Logger for this class + private static final XLogger logger = XLoggerFactory.getXLogger(TestContextUpdateDifferentModels.class); + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test context update different models. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testContextUpdateDifferentModels() throws ApexException, InterruptedException, IOException { + logger.debug("Running test testContextUpdateDifferentModels . . ."); + + final AxPolicyModel apexModelSample = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(apexModelSample); + + final ApexEngineImpl apexEngine = + (ApexEngineImpl) new ApexEngineFactory().createApexEngine(new AxArtifactKey("TestApexEngine", "0.0.1")); + final TestApexActionListener listener = new TestApexActionListener("Test"); + apexEngine.addEventListener("listener", listener); + apexEngine.updateModel(apexModelSample); + apexEngine.start(); + + apexEngine.stop(); + + final AxPolicyModel someSpuriousModel = new AxPolicyModel(new AxArtifactKey("SomeSpuriousModel", "0.0.1")); + assertNotNull(someSpuriousModel); + + try { + apexEngine.updateModel(null); + fail("null model should throw an exception"); + } catch (final ApexException e) { + assertEquals("updateModel()<-TestApexEngine:0.0.1, Apex model is not defined, it has a null value", + e.getMessage()); + } + assertEquals(apexEngine.getInternalContext().getContextAlbums().size(), + apexModelSample.getAlbums().getAlbumsMap().size()); + for (final ContextAlbum contextAlbum : apexEngine.getInternalContext().getContextAlbums().values()) { + assertTrue( + contextAlbum.getAlbumDefinition().equals(apexModelSample.getAlbums().get(contextAlbum.getKey()))); + } + + apexEngine.updateModel(someSpuriousModel); + assertEquals(apexEngine.getInternalContext().getContextAlbums().size(), + someSpuriousModel.getAlbums().getAlbumsMap().size()); + for (final ContextAlbum contextAlbum : apexEngine.getInternalContext().getContextAlbums().values()) { + assertTrue( + contextAlbum.getAlbumDefinition().equals(someSpuriousModel.getAlbums().get(contextAlbum.getKey()))); + } + + apexEngine.clear(); + + logger.debug("Ran test testContextUpdateDifferentModels"); + } + +} diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateModel.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateModel.java new file mode 100644 index 000000000..615781ab3 --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestContextUpdateModel.java @@ -0,0 +1,233 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.executor.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.ContextException; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.ApexEngine; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.onap.policy.apex.testsuites.integration.executor.engine.TestApexActionListener; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestApexEngine. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContextUpdateModel { + // Logger for this class + private static final XLogger logger = XLoggerFactory.getXLogger(TestContextUpdateModel.class); + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test context update model. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testContextUpdateModel() throws ApexException, InterruptedException, IOException { + final AxArtifactKey key = new AxArtifactKey("TestApexEngine", "0.0.1"); + + final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(key); + final TestApexActionListener listener = new TestApexActionListener("Test"); + apexEngine.addEventListener("listener", listener); + + final AxPolicyModel model1 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(model1); + assertEquals(2, model1.getPolicies().getPolicyMap().size()); + + apexEngine.updateModel(model1); + apexEngine.start(); + sendEvent(apexEngine, listener, "Event0000", true); + sendEvent(apexEngine, listener, "Event0100", true); + apexEngine.stop(); + + final AxPolicyModel model2 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(model2); + model2.getPolicies().getPolicyMap().remove(new AxArtifactKey("Policy0", "0.0.1")); + assertEquals(1, model2.getPolicies().getPolicyMap().size()); + apexEngine.updateModel(model2); + apexEngine.start(); + sendEvent(apexEngine, listener, "Event0000", false); + sendEvent(apexEngine, listener, "Event0100", true); + apexEngine.stop(); + + final AxPolicyModel model3 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(model3); + model3.getPolicies().getPolicyMap().remove(new AxArtifactKey("Policy1", "0.0.1")); + assertEquals(1, model3.getPolicies().getPolicyMap().size()); + apexEngine.updateModel(model3); + apexEngine.start(); + sendEvent(apexEngine, listener, "Event0000", true); + sendEvent(apexEngine, listener, "Event0100", false); + apexEngine.stop(); + + final AxPolicyModel model4 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(model4); + assertEquals(2, model4.getPolicies().getPolicyMap().size()); + apexEngine.updateModel(model4); + apexEngine.start(); + sendEvent(apexEngine, listener, "Event0100", true); + sendEvent(apexEngine, listener, "Event0000", true); + apexEngine.stop(); + + apexEngine.clear(); + } + + /** + * Test context update model after. + */ + @After + public void testContextUpdateModelAfter() {} + + /** + * Send event. + * + * @param apexEngine the apex engine + * @param listener the listener + * @param eventName the event name + * @param shouldWork the should work + * @throws ContextException the context exception + */ + private void sendEvent(final ApexEngine apexEngine, final TestApexActionListener listener, final String eventName, + final boolean shouldWork) throws ContextException { + final Date aDate = new Date(1433453067123L); + final Map eventDataMap = new HashMap(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", new Byte((byte) 123)); + eventDataMap.put("TestTimestamp", aDate.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final EnEvent event0 = apexEngine.createEvent(new AxArtifactKey(eventName, "0.0.1")); + event0.putAll(eventDataMap); + apexEngine.handleEvent(event0); + + final EnEvent result = listener.getResult(true); + logger.debug("result 1 is:" + result); + checkResult(result, shouldWork); + } + + /** + * Check result. + * + * @param result the result + * @param shouldWork the should work + */ + private void checkResult(final EnEvent result, final boolean shouldWork) { + if (!shouldWork) { + assertNotNull(result.getExceptionMessage()); + return; + } + + assertTrue(result.getName().equals("Event0004") || result.getName().equals("Event0104")); + + if (result.getName().equals("Event0004")) { + assertEquals("This is a test slogan", result.get("TestSlogan")); + assertEquals((byte) 123, result.get("TestMatchCase")); + assertEquals(34.5445667, result.get("TestTemperature")); + assertEquals((byte) 2, result.get("TestMatchCaseSelected")); + assertEquals((byte) 0, result.get("TestEstablishCaseSelected")); + assertEquals((byte) 1, result.get("TestDecideCaseSelected")); + assertEquals((byte) 3, result.get("TestActCaseSelected")); + } else { + assertEquals("This is a test slogan", result.get("TestSlogan")); + assertEquals((byte) 123, result.get("TestMatchCase")); + assertEquals(34.5445667, result.get("TestTemperature")); + assertEquals((byte) 1, result.get("TestMatchCaseSelected")); + assertEquals((byte) 3, result.get("TestEstablishCaseSelected")); + assertEquals((byte) 1, result.get("TestDecideCaseSelected")); + assertEquals((byte) 2, result.get("TestActCaseSelected")); + } + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java deleted file mode 100644 index 4c2ed5c88..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/events/EventGenerator.java +++ /dev/null @@ -1,501 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.events; - -import java.util.Random; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EventGenerator { - private static int nextEventNo = 0; - - public static String xmlEvents(final int eventCount) { - final StringBuilder builder = new StringBuilder(); - - for (int i = 0; i < eventCount; i++) { - if (i > 0) { - builder.append("\n"); - } - builder.append(xmlEvent()); - } - - return builder.toString(); - } - - public static String jsonEvents(final int eventCount) { - final StringBuilder builder = new StringBuilder(); - - for (int i = 0; i < eventCount; i++) { - if (i > 0) { - builder.append("\n"); - } - builder.append(jsonEvent()); - } - - return builder.toString(); - } - - public static String xmlEvent() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("\n"); - builder.append("\n"); - - builder.append(" " + eventName + "\n"); - builder.append(" 0.0.1\n"); - builder.append(" org.onap.policy.apex.sample.events\n"); - builder.append(" test\n"); - builder.append(" apex\n"); - builder.append(" \n"); - builder.append(" TestSlogan\n"); - builder.append(" Test slogan for External Event" + (nextEventNo++) + "\n"); - builder.append(" \n"); - builder.append(" \n"); - builder.append(" TestMatchCase\n"); - builder.append(" " + nextMatchCase + "\n"); - builder.append(" \n"); - builder.append(" \n"); - builder.append(" TestTimestamp\n"); - builder.append(" " + System.currentTimeMillis() + "\n"); - builder.append(" \n"); - builder.append(" \n"); - builder.append(" TestTemperature\n"); - builder.append(" " + nextTestTemperature + "\n"); - builder.append(" \n"); - builder.append(""); - - return builder.toString(); - } - - public static String jsonEvent() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoName() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"namez\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadName() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"%%%%\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoExName() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"I_DONT_EXIST\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoVersion() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"versiion\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadVersion() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"#####\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoExVersion() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"1.2.3\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoNamespace() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpacee\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadNamespace() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"hello.&&&&\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoExNamespace() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"pie.in.the.sky\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoSource() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"sourcee\": \"test\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadSource() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"%!@**@!\",\n"); - builder.append(" \"target\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNoTarget() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"targett\": \"apex\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventBadTarget() { - final Random rand = new Random(); - - final StringBuilder builder = new StringBuilder(); - - int nextEventNo = rand.nextInt(2); - final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); - final int nextMatchCase = rand.nextInt(4); - final float nextTestTemperature = rand.nextFloat() * 10000; - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"" + eventName + "\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"KNIO(*S)A(S)D\",\n"); - builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); - builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); - builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); - builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventMissingFields() { - final StringBuilder builder = new StringBuilder(); - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"apex\"\n"); - builder.append("}"); - - return builder.toString(); - } - - public static String jsonEventNullFields() { - final StringBuilder builder = new StringBuilder(); - - builder.append("{\n"); - builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); - builder.append(" \"name\": \"Event0000\",\n"); - builder.append(" \"version\": \"0.0.1\",\n"); - builder.append(" \"source\": \"test\",\n"); - builder.append(" \"target\": \"Apex\",\n"); - builder.append(" \"TestSlogan\": null,\n"); - builder.append(" \"TestMatchCase\": -1,\n"); - builder.append(" \"TestTimestamp\": -1,\n"); - builder.append(" \"TestTemperature\": -1.0\n"); - builder.append("}"); - - return builder.toString(); - } - - public static void main(final String[] args) { - if (args.length != 2) { - System.err.println("usage EventGenerator #events XML|JSON"); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage EventGenerator #events XML|JSON"); - e.printStackTrace(); - return; - } - - if (args[1].equalsIgnoreCase("XML")) { - System.out.println(xmlEvents(eventCount)); - } else if (args[1].equalsIgnoreCase("JSON")) { - System.out.println(jsonEvents(eventCount)); - } else { - System.err.println("usage EventGenerator #events XML|JSON"); - return; - } - } - - public static int getNextEventNo() { - return nextEventNo; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java deleted file mode 100644 index 347cce80e..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2File.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.file; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestFile2File { - - @Test - public void testJsonFileEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; - - testFileEvents(args, "src/test/resources/events/EventsOut.json", 48956); - } - - @Test - public void testXMLFileEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileXmlEvent.json"}; - - testFileEvents(args, "src/test/resources/events/EventsOut.xmlfile", 106739); - } - - private void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) - throws MessagingException, ApexException, IOException { - final ApexMain apexMain = new ApexMain(args); - - final File outFile = new File(outFilePath); - - while (!outFile.exists()) { - ThreadUtilities.sleep(500); - } - - // Wait for the file to be filled - long outFileSize = 0; - while (true) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); - outFileSize = fileString.length(); - if (outFileSize > 0 && outFileSize >= expectedFileSize) { - break; - } - ThreadUtilities.sleep(500); - } - - apexMain.shutdown(); - outFile.delete(); - assertEquals(outFileSize, expectedFileSize); - } -} - - diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java deleted file mode 100644 index c2b097273..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileFiltered.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.file; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestFile2FileFiltered { - - @Test - public void testJsonFilteredFileInOutEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json"}; - - final String[] outFilePaths = - {"src/test/resources/events/Events0004Out.json", "src/test/resources/events/Events0104Out.json"}; - - final long[] expectedFileSizes = {25949, 23007}; - - testFilteredFileEvents(args, outFilePaths, expectedFileSizes); - } - - @Test - public void testJsonFilteredFileOutEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json"}; - - final String[] outFilePaths = - {"src/test/resources/events/Events0004Out.json", "src/test/resources/events/Events0104Out.json"}; - - final long[] expectedFileSizes = {25949, 23007}; - - testFilteredFileEvents(args, outFilePaths, expectedFileSizes); - } - - @Test - public void testJsonFilteredFileInEvents() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2FileFilteredInJsonEvent.json"}; - - final String[] outFilePaths = {"src/test/resources/events/Events0004Out.json"}; - - final long[] expectedFileSizes = {25949}; - - testFilteredFileEvents(args, outFilePaths, expectedFileSizes); - } - - private void testFilteredFileEvents(final String[] args, final String[] outFilePaths, - final long[] expectedFileSizes) throws MessagingException, ApexException, IOException { - final ApexMain apexMain = new ApexMain(args); - - final File outFile0 = new File(outFilePaths[0]); - - while (!outFile0.exists()) { - ThreadUtilities.sleep(500); - } - - // Wait for the file to be filled - long outFile0Size = 0; - for (int i = 0; i < 4; i++) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[0]).replaceAll("\\s+", ""); - outFile0Size = fileString.length(); - if (outFile0Size > 0 && outFile0Size >= expectedFileSizes[0]) { - break; - } - ThreadUtilities.sleep(500); - } - - ThreadUtilities.sleep(500); - apexMain.shutdown(); - - final long[] actualFileSizes = new long[expectedFileSizes.length]; - - for (int i = 0; i < outFilePaths.length; i++) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[i]).replaceAll("\\s+", ""); - actualFileSizes[i] = fileString.length(); - new File(outFilePaths[i]).delete(); - } - - for (int i = 0; i < actualFileSizes.length; i++) { - assertEquals(actualFileSizes[i], expectedFileSizes[i]); - } - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java deleted file mode 100644 index c952d73b5..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/file/TestFile2FileIgnore.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.file; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; - -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestFile2FileIgnore { - - // This test is used just to bring up an instance of Apex for manual testing and demonstrations - // It should always be ignored in automated testing because it holds Apex up for a very long - // time - public static void main(final String[] args) throws MessagingException, ApexException, IOException { - final String[] apexArgs = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; - - testFileEvents(apexArgs, "src/test/resources/events/EventsOut.json", 48656); - } - - private static void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) - throws MessagingException, ApexException, IOException { - final ApexMain apexMain = new ApexMain(args); - - final File outFile = new File(outFilePath); - - while (!outFile.exists()) { - ThreadUtilities.sleep(500); - } - - // Wait for the file to be filled - long outFileSize = 0; - while (true) { - final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); - outFileSize = fileString.length(); - if (outFileSize > 0 && outFileSize >= expectedFileSize) { - break; - } - ThreadUtilities.sleep(500); - } - - // Here's the long time I was talking about above! - ThreadUtilities.sleep(100000000); - - apexMain.shutdown(); - outFile.delete(); - assertEquals(outFileSize, expectedFileSize); - } -} - - diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java deleted file mode 100644 index 8b9f2a112..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventProducer.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.Topic; - -import org.apache.activemq.command.ActiveMQTopic; -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JMSEventProducer implements Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(JMSEventProducer.class); - - private final String topic; - private final int eventCount; - private final boolean sendObjects; - private final long eventInterval; - private long eventsSentCount = 0; - - private final Thread producerThread; - private boolean sendEventsFlag = false; - private boolean stopFlag = false; - private final Connection connection; - - public JMSEventProducer(final String topic, final ConnectionFactory connectionFactory, final String username, - final String password, final int eventCount, final boolean sendObjects, final long eventInterval) - throws JMSException { - this.topic = topic; - this.eventCount = eventCount; - this.sendObjects = sendObjects; - this.eventInterval = eventInterval; - connection = connectionFactory.createConnection(username, password); - connection.start(); - - producerThread = new Thread(this); - producerThread.start(); - } - - @Override - public void run() { - final Topic jmsTopic = new ActiveMQTopic(topic); - try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer jmsProducer = jmsSession.createProducer(jmsTopic);) { - - while (producerThread.isAlive() && !stopFlag) { - ThreadUtilities.sleep(50); - - if (sendEventsFlag) { - sendEventsToTopic(jmsSession, jmsProducer); - sendEventsFlag = false; - } - } - - } catch (final Exception e) { - throw new ApexEventRuntimeException("JMS event consumption failed", e); - } - } - - public void sendEvents() { - sendEventsFlag = true; - } - - private void sendEventsToTopic(final Session jmsSession, final MessageProducer jmsProducer) throws JMSException { - - LOGGER.info("{} : sending events to JMS server, event count {}", this.getClass().getCanonicalName(), - eventCount); - - for (int i = 0; i < eventCount; i++) { - ThreadUtilities.sleep(eventInterval); - - Message jmsMessage = null; - if (sendObjects) { - jmsMessage = jmsSession.createObjectMessage(new TestPing()); - } else { - jmsMessage = jmsSession.createTextMessage(EventGenerator.jsonEvent()); - } - jmsProducer.send(jmsMessage); - eventsSentCount++; - } - LOGGER.info("{} : completed, number of events sent", this.getClass().getCanonicalName(), eventsSentCount); - } - - public long getEventsSentCount() { - return eventsSentCount; - } - - public void shutdown() { - LOGGER.info("{} : stopping", this.getClass().getCanonicalName()); - stopFlag = true; - - while (producerThread.isAlive()) { - ThreadUtilities.sleep(10); - } - LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java deleted file mode 100644 index 916216a5a..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/JMSEventSubscriber.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.ObjectMessage; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import org.apache.activemq.command.ActiveMQTopic; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JMSEventSubscriber implements Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(JMSEventSubscriber.class); - - private final String topic; - private long eventsReceivedCount = 0; - - private final Thread subscriberThread; - private final Connection connection; - - - public JMSEventSubscriber(final String topic, final ConnectionFactory connectionFactory, final String username, - final String password) throws JMSException { - this.topic = topic; - connection = connectionFactory.createConnection(username, password); - connection.start(); - - subscriberThread = new Thread(this); - subscriberThread.start(); - } - - @Override - public void run() { - final Topic jmsTopic = new ActiveMQTopic(topic); - try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer jmsConsumer = jmsSession.createConsumer(jmsTopic);) { - - while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { - try { - final Message message = jmsConsumer.receive(100); - if (message == null) { - continue; - } - - if (message instanceof ObjectMessage) { - final TestPing testPing = (TestPing) ((ObjectMessage) message).getObject(); - testPing.verify(); - } else if (message instanceof TextMessage) { - ((TextMessage) message).getText(); - } else { - throw new ApexEventException("unknowm message \"" + message + "\" of type \"" - + message.getClass().getCanonicalName() + "\" received"); - } - eventsReceivedCount++; - } catch (final Exception e) { - break; - } - } - - } catch (final Exception e) { - throw new ApexEventRuntimeException("JMS event consumption failed", e); - } - - LOGGER.info("{} : event reception completed", this.getClass().getCanonicalName()); - } - - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - public void shutdown() throws JMSException { - subscriberThread.interrupt(); - - while (subscriberThread.isAlive()) { - ThreadUtilities.sleep(10); - } - - connection.close(); - LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java deleted file mode 100644 index de3c8d37b..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestContext.java +++ /dev/null @@ -1,191 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.HOST; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.JMS_TOPIC_APEX_IN; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.JMS_TOPIC_APEX_OUT; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.PORT; -import static org.onap.policy.apex.apps.uservice.test.adapt.jms.TestJMS2JMS.connectionFactory; - -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; -import java.util.Properties; - -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.NameParser; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; - -import org.apache.activemq.command.ActiveMQTopic; -import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContext implements Context { - - private Properties testProperties; - - public TestContext() { - try { - testProperties = new Properties(); - - final Map params = new HashMap(); - params.put("host", HOST); - params.put("port", PORT); - testProperties.put("ConnectionFactory", connectionFactory); - testProperties.put(JMS_TOPIC_APEX_IN, new ActiveMQTopic(JMS_TOPIC_APEX_IN)); - testProperties.put(JMS_TOPIC_APEX_OUT, new ActiveMQTopic(JMS_TOPIC_APEX_OUT)); - } catch (final Exception e) { - e.printStackTrace(); - throw new ApexRuntimeException("Context initiation failed", e); - } - } - - @Override - public Object lookup(final Name name) throws NamingException { - return null; - } - - @Override - public Object lookup(final String name) throws NamingException { - return testProperties.get(name); - } - - @Override - public void bind(final Name name, final Object obj) throws NamingException {} - - @Override - public void bind(final String name, final Object obj) throws NamingException {} - - @Override - public void rebind(final Name name, final Object obj) throws NamingException {} - - @Override - public void rebind(final String name, final Object obj) throws NamingException {} - - @Override - public void unbind(final Name name) throws NamingException {} - - @Override - public void unbind(final String name) throws NamingException {} - - @Override - public void rename(final Name oldName, final Name newName) throws NamingException {} - - @Override - public void rename(final String oldName, final String newName) throws NamingException {} - - @Override - public NamingEnumeration list(final Name name) throws NamingException { - return null; - } - - @Override - public NamingEnumeration list(final String name) throws NamingException { - return null; - } - - @Override - public NamingEnumeration listBindings(final Name name) throws NamingException { - return null; - } - - @Override - public NamingEnumeration listBindings(final String name) throws NamingException { - return null; - } - - @Override - public void destroySubcontext(final Name name) throws NamingException {} - - @Override - public void destroySubcontext(final String name) throws NamingException {} - - @Override - public Context createSubcontext(final Name name) throws NamingException { - return null; - } - - @Override - public Context createSubcontext(final String name) throws NamingException { - return null; - } - - @Override - public Object lookupLink(final Name name) throws NamingException { - return null; - } - - @Override - public Object lookupLink(final String name) throws NamingException { - return null; - } - - @Override - public NameParser getNameParser(final Name name) throws NamingException { - return null; - } - - @Override - public NameParser getNameParser(final String name) throws NamingException { - return null; - } - - @Override - public Name composeName(final Name name, final Name prefix) throws NamingException { - return null; - } - - @Override - public String composeName(final String name, final String prefix) throws NamingException { - return null; - } - - @Override - public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { - return null; - } - - @Override - public Object removeFromEnvironment(final String propName) throws NamingException { - return null; - } - - @Override - public Hashtable getEnvironment() throws NamingException { - return null; - } - - @Override - public void close() throws NamingException {} - - @Override - public String getNameInNamespace() throws NamingException { - return null; - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java deleted file mode 100644 index 6cb874671..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestInitialContextFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import java.util.Hashtable; - -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.spi.InitialContextFactory; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestInitialContextFactory implements InitialContextFactory { - - private final Context context = new TestContext(); - - public TestInitialContextFactory() throws NamingException {} - - /* - * (non-Javadoc) - * - * @see javax.naming.spi.InitialContextFactory#getInitialContext(java.util.Hashtable) - */ - @Override - public Context getInitialContext(final Hashtable environment) throws NamingException { - return context; - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java deleted file mode 100644 index f021b2674..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestJMS2JMS.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.jms.JMSException; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.security.AuthenticationUser; -import org.apache.activemq.security.SimpleAuthenticationPlugin; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class TestJMS2JMS { - public static final String PORT = "5445"; - public static final String HOST = "localhost"; - public static final String JMS_TOPIC_APEX_IN = "jms/topic/apexIn"; - public static final String JMS_TOPIC_APEX_OUT = "jms/topic/apexOut"; - - private static final int SLEEP_TIME = 1500; - private static final String GROUP_ROLE = "guests"; - private static final String PACKAGE_NAME = "org.onap.policy.apex.apps.uservice.test.adapt.jms"; - private static final String USERNAME = "guest"; - private static final String PASSWORD = "IAmAGuest"; - private static final String URL = "tcp://" + HOST + ":" + PORT; - - private static final String DATA_PARENT_DIR = Paths.get("target", "activemq-data").toString(); - - private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestJMS2JMS.class); - - private static final long MAX_TEST_LENGTH = 10000; - private static final int EVENT_COUNT = 100; - private static final int EVENT_INTERVAL = 20; - - private static BrokerService broker; - - public static ActiveMQConnectionFactory connectionFactory; - - - @BeforeClass - public static void setupEmbeddedJMSServer() throws Exception { - final ArrayList plugins = new ArrayList(); - final BrokerPlugin authenticationPlugin = getAuthenticationBrokerPlugin(); - plugins.add(authenticationPlugin); - - broker = new BrokerService(); - broker.setUseJmx(false); - broker.setPersistent(false); - broker.addConnector(URL); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPlugins(plugins.toArray(new BrokerPlugin[0])); - broker.setDataDirectory(DATA_PARENT_DIR); - broker.start(); - broker.waitUntilStarted(); - connectionFactory = new ActiveMQConnectionFactory(URL); - connectionFactory.setTrustedPackages(Arrays.asList(PACKAGE_NAME)); - } - - private static BrokerPlugin getAuthenticationBrokerPlugin() { - final List users = new ArrayList(); - users.add(new AuthenticationUser(USERNAME, PASSWORD, GROUP_ROLE)); - final SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(users); - return authenticationPlugin; - } - - @AfterClass - public static void shutdownEmbeddedJMSServer() throws IOException { - try { - if (broker != null) { - broker.stop(); - } - } catch (final Exception e) { - LOGGER.warn("Failed to stop JMS server", e); - } - - } - - @Test - public void testJMSObjectEvents() throws ApexException, JMSException { - final String[] args = { "src/test/resources/prodcons/JMS2JMSObjectEvent.json" }; - testJMSEvents(args, true); - } - - @Test - public void testJMSJsonEvents() throws ApexException, JMSException { - final String[] args = { "src/test/resources/prodcons/JMS2JMSJsonEvent.json" }; - testJMSEvents(args, false); - } - - private void testJMSEvents(final String[] args, final Boolean sendObjects) throws ApexException, JMSException { - final JMSEventSubscriber subscriber = - new JMSEventSubscriber(JMS_TOPIC_APEX_OUT, connectionFactory, USERNAME, PASSWORD); - final JMSEventProducer producer = new JMSEventProducer(JMS_TOPIC_APEX_IN, connectionFactory, USERNAME, PASSWORD, - EVENT_COUNT, sendObjects, EVENT_INTERVAL); - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(3000); - - producer.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (isTimedOut(testStartTime) && subscriber.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - ThreadUtilities.sleep(SLEEP_TIME); - apexMain.shutdown(); - subscriber.shutdown(); - producer.shutdown(); - ThreadUtilities.sleep(SLEEP_TIME); - - assertEquals(EVENT_COUNT, producer.getEventsSentCount()); - assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); - - } - - private boolean isTimedOut(final long testStartTime) { - return System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java deleted file mode 100644 index caf6e2ffd..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/jms/TestPing.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.jms; - -import java.io.Serializable; - -import org.onap.policy.apex.service.engine.event.ApexEventException; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestPing implements Serializable { - private static final long serialVersionUID = -3400711508992955886L; - - private String name = "Rose"; - private String description = "A rose by any other name would smell as sweet"; - private long pingTime = System.currentTimeMillis(); - private long pongTime = -1; - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(final String description) { - this.description = description; - } - - public long getPingTime() { - return pingTime; - } - - public void setPingTime(final long pingTime) { - this.pingTime = pingTime; - } - - public long getPongTime() { - return pongTime; - } - - public void setPongTime(final long pongTime) { - this.pongTime = pongTime; - } - - @Override - public String toString() { - return "TestPing [name=" + name + ", description=" + description + ", pingTime=" + pingTime + ", pongTime=" - + pongTime + "]"; - } - - public void verify() throws ApexEventException { - if (!name.startsWith("Rose")) { - throw new ApexEventException("TestPing is not valid"); - } - - if (name.length() <= 4) { - throw new ApexEventException("TestPing is not valid"); - } - - if (!description.startsWith("A rose by any other name would smell as sweet")) { - throw new ApexEventException("TestPing is not valid"); - } - - if (description.length() <= 44) { - throw new ApexEventException("TestPing is not valid"); - } - - if (pongTime <= pingTime) { - throw new ApexEventException("TestPing is not valid"); - } - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java deleted file mode 100644 index c243b8b07..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventProducer.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class KafkaEventProducer implements Runnable { - private final String topic; - private final String kafkaServerAddress; - private final int eventCount; - private final boolean xmlEvents; - private final long eventInterval; - private long eventsSentCount = 0; - - private final Thread producerThread; - private boolean sendEventsFlag = false; - private boolean stopFlag = false; - - public KafkaEventProducer(final String topic, final String kafkaServerAddress, final int eventCount, - final boolean xmlEvents, final long eventInterval) { - this.topic = topic; - this.kafkaServerAddress = kafkaServerAddress; - this.eventCount = eventCount; - this.xmlEvents = xmlEvents; - this.eventInterval = eventInterval; - - producerThread = new Thread(this); - producerThread.start(); - } - - @Override - public void run() { - final Properties kafkaProducerProperties = new Properties(); - kafkaProducerProperties.put("bootstrap.servers", kafkaServerAddress); - kafkaProducerProperties.put("acks", "all"); - kafkaProducerProperties.put("retries", 0); - kafkaProducerProperties.put("batch.size", 16384); - kafkaProducerProperties.put("linger.ms", 1); - kafkaProducerProperties.put("buffer.memory", 33554432); - kafkaProducerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - kafkaProducerProperties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - - final Producer producer = new KafkaProducer(kafkaProducerProperties); - - while (producerThread.isAlive() && !stopFlag) { - ThreadUtilities.sleep(50); - - if (sendEventsFlag) { - sendEventsToTopic(producer); - sendEventsFlag = false; - } - } - - producer.close(1000, TimeUnit.MILLISECONDS); - } - - public void sendEvents() { - sendEventsFlag = true; - } - - private void sendEventsToTopic(final Producer producer) { - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sending events to Kafka server at " - + kafkaServerAddress + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - - for (int i = 0; i < eventCount; i++) { - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": waiting " + eventInterval - + " milliseconds before sending next event"); - ThreadUtilities.sleep(eventInterval); - - String eventString = null; - if (xmlEvents) { - eventString = EventGenerator.xmlEvent(); - } else { - eventString = EventGenerator.jsonEvent(); - } - producer.send(new ProducerRecord(topic, "Event" + i + "Of" + eventCount, eventString)); - producer.flush(); - eventsSentCount++; - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sent event " + eventString); - } - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": completed"); - } - - public long getEventsSentCount() { - return eventsSentCount; - } - - public void shutdown() { - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopping"); - - stopFlag = true; - - while (producerThread.isAlive()) { - ThreadUtilities.sleep(10); - } - - System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopped"); - } - - public static void main(final String[] args) { - if (args.length != 5) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[2]); - } catch (final Exception e) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - long eventInterval = 0; - try { - eventInterval = Long.parseLong(args[4]); - } catch (final Exception e) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - boolean xmlEvents = false; - if (args[3].equalsIgnoreCase("XML")) { - xmlEvents = true; - } else if (!args[3].equalsIgnoreCase("JSON")) { - System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); - return; - } - - final KafkaEventProducer producer = new KafkaEventProducer(args[0], args[1], eventCount, xmlEvents, - eventInterval); - - producer.sendEvents(); - producer.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java deleted file mode 100644 index 8bdc56dda..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/KafkaEventSubscriber.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import java.util.Arrays; -import java.util.Properties; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class KafkaEventSubscriber implements Runnable { - private final String topic; - private final String kafkaServerAddress; - private long eventsReceivedCount = 0; - - KafkaConsumer consumer; - - Thread subscriberThread; - - public KafkaEventSubscriber(final String topic, final String kafkaServerAddress) throws MessagingException { - this.topic = topic; - this.kafkaServerAddress = kafkaServerAddress; - - final Properties props = new Properties(); - props.put("bootstrap.servers", kafkaServerAddress); - props.put("group.id", "test"); - props.put("enable.auto.commit", "true"); - props.put("auto.commit.interval.ms", "1000"); - props.put("session.timeout.ms", "30000"); - props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); - - consumer = new KafkaConsumer(props); - consumer.subscribe(Arrays.asList(topic)); - - subscriberThread = new Thread(this); - subscriberThread.start(); - } - - @Override - public void run() { - System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": receiving events from Kafka server at " - + kafkaServerAddress + " on topic " + topic); - - while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { - try { - final ConsumerRecords records = consumer.poll(100); - for (final ConsumerRecord record : records) { - System.out.println("******"); - System.out.println("offset=" + record.offset()); - System.out.println("key=" + record.key()); - System.out.println("name=" + record.value()); - eventsReceivedCount++; - } - } catch (final Exception e) { - // Thread interrupted - break; - } - } - - System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": event reception completed"); - } - - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - public void shutdown() { - subscriberThread.interrupt(); - - while (subscriberThread.isAlive()) { - ThreadUtilities.sleep(10); - } - - consumer.close(); - System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": stopped"); - } - - - public static void main(final String[] args) throws MessagingException { - if (args.length != 2) { - System.err.println("usage KafkaEventSubscriber topic kafkaServerAddress"); - return; - } - new KafkaEventSubscriber(args[0], args[1]); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java deleted file mode 100644 index c95498a05..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafka2Kafka.java +++ /dev/null @@ -1,185 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.nio.file.Files; -import java.util.Properties; - -import kafka.admin.AdminUtils; -import kafka.admin.RackAwareMode; -import kafka.server.KafkaConfig; -import kafka.server.KafkaServer; -import kafka.utils.TestUtils; -import kafka.utils.ZKStringSerializer$; -import kafka.utils.ZkUtils; -import kafka.zk.EmbeddedZookeeper; - -import org.I0Itec.zkclient.ZkClient; -import org.apache.kafka.common.utils.MockTime; -import org.apache.kafka.common.utils.Time; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - - -/** - * The Class TestKafka2Kafka. - */ -public class TestKafka2Kafka { - // The method of starting an embedded Kafka server used in this example is based on the method - // on stack overflow at - // https://github.com/asmaier/mini-kafka - - private static final long MAX_TEST_LENGTH = 20000; - - private static final int EVENT_COUNT = 10; - private static final int EVENT_INTERVAL = 20; - - private static final String ZKHOST = "127.0.0.1"; - private static final String BROKERHOST = "127.0.0.1"; - private static final String BROKERPORT = "39902"; - - private static EmbeddedZookeeper zkServer; - private static ZkClient zkClient; - private static KafkaServer kafkaServer; - - /** - * Setup dummy kafka server. - * - * @throws IOException Signals that an I/O exception has occurred. - */ - @BeforeClass - public static void setupDummyKafkaServer() throws IOException { - // setup Zookeeper - zkServer = new EmbeddedZookeeper(); - final String zkConnect = ZKHOST + ":" + zkServer.port(); - zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer$.MODULE$); - final ZkUtils zkUtils = ZkUtils.apply(zkClient, false); - - // setup Broker - final Properties brokerProps = new Properties(); - brokerProps.setProperty("zookeeper.connect", zkConnect); - brokerProps.setProperty("broker.id", "0"); - brokerProps.setProperty("log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString()); - brokerProps.setProperty("listeners", "PLAINTEXT://" + BROKERHOST + ":" + BROKERPORT); - brokerProps.setProperty("offsets.topic.replication.factor", "1"); - brokerProps.setProperty("transaction.state.log.replication.factor", "1"); - brokerProps.setProperty("transaction.state.log.min.isr", "1"); - final KafkaConfig config = new KafkaConfig(brokerProps); - final Time mock = new MockTime(); - kafkaServer = TestUtils.createServer(config, mock); - kafkaServer.startup(); - - // create topics - AdminUtils.createTopic(zkUtils, "apex-in-0", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); - AdminUtils.createTopic(zkUtils, "apex-in-1", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); - AdminUtils.createTopic(zkUtils, "apex-out", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); - - } - - /** - * Shutdown dummy kafka server. - * - * @throws IOException Signals that an I/O exception has occurred. - */ - @AfterClass - public static void shutdownDummyKafkaServer() throws IOException { - if (kafkaServer != null) { - kafkaServer.shutdown(); - } - if (zkClient != null) { - zkClient.close(); - } - if (zkServer != null) { - zkServer.shutdown(); - } - } - - /** - * Test json kafka events. - * - * @throws MessagingException the messaging exception - * @throws ApexException the apex exception - */ - @Test - public void testJsonKafkaEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Kafka2KafkaJsonEvent.json"}; - testKafkaEvents(args, false, "json"); - } - - /** - * Test XML kafka events. - * - * @throws MessagingException the messaging exception - * @throws ApexException the apex exception - */ - @Test - public void testXmlKafkaEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Kafka2KafkaXmlEvent.json"}; - testKafkaEvents(args, true, "xml"); - } - - /** - * Test kafka events. - * - * @param args the args - * @param xmlEvents the xml events - * @param topicSuffix the topic suffix - * @throws MessagingException the messaging exception - * @throws ApexException the apex exception - */ - private void testKafkaEvents(final String[] args, final Boolean xmlEvents, final String topicSuffix) - throws MessagingException, ApexException { - final KafkaEventSubscriber subscriber = - new KafkaEventSubscriber("apex-out-" + topicSuffix, "localhost:" + BROKERPORT); - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(3000); - - final KafkaEventProducer producer = new KafkaEventProducer("apex-in-" + topicSuffix, "localhost:" + BROKERPORT, - EVENT_COUNT, xmlEvents, EVENT_INTERVAL); - - producer.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH - && subscriber.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - ThreadUtilities.sleep(1000); - - assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); - - apexMain.shutdown(); - subscriber.shutdown(); - producer.shutdown(); - ThreadUtilities.sleep(1000); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java deleted file mode 100644 index 80b4aef55..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/kafka/TestKafkaXMLEventProducer.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.kafka; - -import java.util.Properties; - -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent; -import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestKafkaXMLEventProducer { - - public static void main(final String[] args) { - final Properties props = new Properties(); - props.put("bootstrap.servers", "localhost:49092"); - props.put("acks", "all"); - props.put("retries", 0); - props.put("batch.size", 16384); - props.put("linger.ms", 1); - props.put("buffer.memory", 33554432); - props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); - - final XMLApexEvent xmlEvent = new XMLApexEvent(); - xmlEvent.setName("XMLEvent-1"); - xmlEvent.setVersion("0.0.1"); - xmlEvent.getData().add(new XMLApexEventData("Data-1", "Data Value -1")); - - final Producer producer = new KafkaProducer(props); - for (int i = 0; i < 100; i++) { - xmlEvent.setName("XMLEvent" + Integer.toString(i)); - xmlEvent.setVersion("0.0.1"); - xmlEvent.getData() - .add(new XMLApexEventData("Data" + Integer.toString(i), "Data Value " + Integer.toString(i))); - - producer.send(new ProducerRecord("apex-in-0", xmlEvent.getName(), xmlEvent.toString())); - } - producer.close(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java deleted file mode 100644 index dd3f15ab6..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestFile2REST.java +++ /dev/null @@ -1,205 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.net.URI; -import java.util.Map; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.core.Response; - -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.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -import com.google.gson.Gson; - - -public class TestFile2REST { - private static final String BASE_URI = "http://localhost:32801/TestFile2Rest"; - private static HttpServer server; - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - - private final PrintStream stdout = System.out; - private final PrintStream stderr = System.err; - - @BeforeClass - public static void setUp() throws Exception { - final ResourceConfig rc = new ResourceConfig(TestRESTClientEndpoint.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); - - while (!server.isStarted()) { - ThreadUtilities.sleep(50); - } - } - - @AfterClass - public static void tearDown() throws Exception { - server.shutdown(); - } - - @Test - public void testFileEventsPost() throws MessagingException, ApexException, IOException { - final Client client = ClientBuilder.newClient(); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPost.json"}; - final ApexMain apexMain = new ApexMain(args); - - // Wait for the required amount of events to be received or for 10 seconds - for (int i = 0; i < 100; i++) { - ThreadUtilities.sleep(100); - final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") - .request("application/json").get(); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - if ((double) jsonMap.get("POST") == 100) { - break; - } - } - - apexMain.shutdown(); - } - - @Test - public void testFileEventsPut() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPut.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - // Wait for the required amount of events to be received or for 10 seconds - for (int i = 0; i < 100; i++) { - ThreadUtilities.sleep(100); - final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") - .request("application/json").get(); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - if ((double) jsonMap.get("PUT") == 100) { - break; - } - } - - apexMain.shutdown(); - } - - @Test - public void testFileEventsNoURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventNoURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" no URL has been set for event sending on REST client")); - } - - @Test - public void testFileEventsBadURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/Bad\" using HTTP \"POST\" failed with status code 404")); - } - - @Test - public void testFileEventsBadHTTPMethod() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "specified HTTP method of \"DELETE\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supproted for event sending on REST client producer")); - } - - @Test - public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(500); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/PostEventBadResponse\" using HTTP \"POST\" failed with status code 400")); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java deleted file mode 100644 index 922e03217..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestREST2File.java +++ /dev/null @@ -1,188 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restclient; - -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.net.URI; - -import org.glassfish.grizzly.http.server.HttpServer; -import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; -import org.glassfish.jersey.server.ResourceConfig; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; - - -public class TestREST2File { - - private static final String BASE_URI = "http://localhost:32801/TestRest2File"; - private HttpServer server; - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - - private final PrintStream stdout = System.out; - private final PrintStream stderr = System.err; - - @Before - public void setUp() throws Exception { - final ResourceConfig rc = new ResourceConfig(TestRESTClientEndpoint.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); - - while (!server.isStarted()) { - ThreadUtilities.sleep(50); - } - } - - @After - public void tearDown() throws Exception { - server.shutdown(); - } - - @AfterClass - public static void deleteTempFiles() { - new File("src/test/resources/events/EventsOut.json").delete(); - } - - @Test - public void testRESTEventsIn() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEvent.json"}; - - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outputEventText = TextFileUtils.getTextFileAsString("src/test/resources/events/EventsOut.json"); - assertTrue(outputEventText.contains( - "04\",\n" + " \"version\": \"0.0.1\",\n" + " \"nameSpace\": \"org.onap.policy.apex.sample.events\"")); - } - - @Test - public void testFileEmptyEvents() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEmptyEvents.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "received an empty event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"")); - } - - @Test - public void testFileEventsNoURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventNoURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" no URL has been set for event sending on REST client")); - } - - @Test - public void testFileEventsBadURL() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadURL.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404")); - } - - @Test - public void testFileEventsBadHTTPMethod() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "specified HTTP method of \"POST\" is invalid, only HTTP method \"GET\" is supported for event reception on REST client consumer")); - } - - @Test - public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadResponse.json"}; - final ApexMain apexMain = new ApexMain(args); - - ThreadUtilities.sleep(1000); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" failed with status code 400 and message \"\"")); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java deleted file mode 100644 index 79634ebcb..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restclient/TestRESTClientEndpoint.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Map; -import java.util.Random; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; - -import com.google.gson.Gson; - - -@Path("/apex") -public class TestRESTClientEndpoint { - - private static int postMessagesReceived = 0; - private static int putMessagesReceived = 0; - private static int statMessagesReceived = 0; - private static int getMessagesReceived = 0; - - @Path("/event/Stats") - @GET - public Response serviceGetStats() { - statMessagesReceived++; - return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } - - @Path("/event/GetEvent") - @GET - public Response serviceGetEvent() { - final Random rand = new Random(); - final int nextMatchCase = rand.nextInt(4); - final String nextEventName = "Event0" + rand.nextInt(2) + "00"; - - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" - + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + getMessagesReceived - + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" - + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() - + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; - - getMessagesReceived++; - - return Response.status(200).entity(eventString).build(); - } - - @Path("/event/GetEmptyEvent") - @GET - public Response serviceGetEmptyEvent() { - return Response.status(200).build(); - } - - @Path("/event/GetEventBadResponse") - @GET - public Response serviceGetEventBadResponse() { - return Response.status(400).build(); - } - - @Path("/event/PostEvent") - @POST - public Response servicePostRequest(final String jsonString) { - postMessagesReceived++; - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(jsonString, Map.class); - assertTrue(jsonMap.containsKey("name")); - assertEquals("0.0.1", jsonMap.get("version")); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Act", jsonMap.get("source")); - assertEquals("Outside", jsonMap.get("target")); - - return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } - - @Path("/event/PostEventBadResponse") - @POST - public Response servicePostRequestBadResponse(final String jsonString) { - return Response.status(400).build(); - } - - @Path("/event/PutEvent") - @PUT - public Response servicePutRequest(final String jsonString) { - putMessagesReceived++; - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(jsonString, Map.class); - assertTrue(jsonMap.containsKey("name")); - assertEquals("0.0.1", jsonMap.get("version")); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Act", jsonMap.get("source")); - assertEquals("Outside", jsonMap.get("target")); - - return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java deleted file mode 100644 index 15928b3c7..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServer.java +++ /dev/null @@ -1,343 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restserver; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Map; -import java.util.Random; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -import com.google.gson.Gson; - - -public class TestRESTServer { - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - - private final PrintStream stdout = System.out; - private final PrintStream stderr = System.err; - - private static int eventsSent = 0; - - @Test - public void testRESTServerPut() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEvent.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); - } - - apexMain.shutdown(); - } - - @Test - public void testRESTServerPost() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEvent.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); - } - - apexMain.shutdown(); - } - - @Test - public void testRESTServerGetStatus() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEvent.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - // trigger 10 POST & PUT events - for (int i = 0; i < 10; i++) { - final Response postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - final Response putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(getEvent())); - assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus()); - assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus()); - } - - final Response statResponse = - client.target("http://localhost:23324/apex/FirstConsumer/Status").request("application/json").get(); - - assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus()); - final String responseString = statResponse.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("[FirstConsumer]", jsonMap.get("INPUTS")); - assertEquals(1.0, jsonMap.get("STAT")); - assertEquals(10.0, jsonMap.get("POST")); - assertEquals(10.0, jsonMap.get("PUT")); - - apexMain.shutdown(); - } - - @Test - public void testRESTServerMultiInputs() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventMultiIn.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus()); - final String firstResponseString = firstResponse.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map firstJsonMap = new Gson().fromJson(firstResponseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan")); - - final Response secondResponse = client.target("http://localhost:23324/apex/SecondConsumer/EventIn") - .request("application/json").post(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus()); - final String secondResponseString = secondResponse.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map secondJsonMap = new Gson().fromJson(secondResponseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan")); - } - - apexMain.shutdown(); - } - - @Test - public void testRESTServerProducerStandalone() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString - .contains("the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer")); - } - - @Test - public void testRESTServerProducerHost() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerHost.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" host is specified only in standalone mode")); - } - - @Test - public void testRESTServerProducerPort() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerPort.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains(" port is specified only in standalone mode")); - } - - @Test - public void testRESTServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "the parameters \"host\" and \"port\" must be defined for REST Server consumer (FirstConsumer) in standalone mode")); - } - - @Test - public void testRESTServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "the parameters \"host\" and \"port\" must be defined for REST Server consumer (FirstConsumer) in standalone mode")); - } - - @Test - public void testRESTServerProducerNotSync() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "REST Server producer (FirstProducer) must run in synchronous mode with a REST Server consumer")); - } - - @Test - public void testRESTServerConsumerNotSync() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json"}; - - final ApexMain apexMain = new ApexMain(args); - ThreadUtilities.sleep(200); - apexMain.shutdown(); - - final String outString = outContent.toString(); - - System.setOut(stdout); - System.setErr(stderr); - - assertTrue(outString.contains( - "peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined with the same peered mode")); - } - - @Test - public void testRESTServerDivideByZero() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - for (int i = 0; i < 20; i++) { - final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(getEvent())); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - final String responseString = response.readEntity(String.class); - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(responseString, Map.class); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); - assertTrue(((String) jsonMap.get("exceptionMessage")).contains("caused by: / by zero")); - } - - apexMain.shutdown(); - } - - private String getEvent() { - final Random rand = new Random(); - final int nextMatchCase = rand.nextInt(4); - final String nextEventName = "Event0" + rand.nextInt(2) + "00"; - - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" - + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + "\",\n" - + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" - + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() - + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; - - return eventString; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java deleted file mode 100644 index cb52dd50b..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restserver/TestRESTServerVPNContext.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.restserver; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Response; - -import org.junit.Ignore; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - - -public class TestRESTServerVPNContext { - private static int eventsSent = 0; - - @Ignore - @Test - public void testRESTServerPut() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextJava.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(setupLinkContext("L09", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupLinkContext("L10", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - ThreadUtilities.sleep(100000); - - apexMain.shutdown(); - } - - @Ignore - @Test - public void testRESTServerPutAvro() throws MessagingException, ApexException, IOException { - final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextAvro.json"}; - final ApexMain apexMain = new ApexMain(args); - - final Client client = ClientBuilder.newClient(); - - Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") - .request("application/json").put(Entity.json(setupLinkContext("L09", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupLinkContext("L10", true))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") - .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - ThreadUtilities.sleep(100000); - - apexMain.shutdown(); - } - - private String setupLinkContext(final String link, final Boolean isUp) { - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" - + "\"name\": \"VPNLinkCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" - + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"Link\": \"" + link + "\",\n" + "\"LinkUp\": " - + isUp + "\n" + "}"; - - return eventString; - } - - private String setupCustomerContext(final String customerName, final String linkList, final int slaDT, - final int ytdDT) { - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" - + "\"name\": \"VPNCustomerCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" - + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"CustomerName\": \"" + customerName + "\",\n" - + "\"LinkList\": \"" + linkList + "\",\n" + "\"SlaDT\": \"" + slaDT + "\",\n" + "\"YtdDT\": " + ytdDT - + "\n" + "}"; - - return eventString; - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java deleted file mode 100644 index da075b6a2..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/Foo.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.sampletypes; - -public class Foo { - private String bar; - - public String getBar() { - return bar; - } - - public void setBar(final String bar) { - this.bar = bar; - } - - public Foo(final String bar) { - this(); - this.bar = bar; - } - - public Foo() { - super(); - } - - @Override - public String toString() { - return "Foo [bar=(String)\"" + bar + "\"]"; - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java deleted file mode 100644 index 9adaf6dae..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/sampletypes/FooMap.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.sampletypes; - -import java.util.LinkedHashMap; -import java.util.Map; - -public class FooMap extends LinkedHashMap { - private static final long serialVersionUID = -7125986379378753022L; - - public FooMap() { - super(); - } - - public FooMap(final int initialCapacity, final float loadFactor, final boolean accessOrder) { - super(initialCapacity, loadFactor, accessOrder); - } - - public FooMap(final int initialCapacity, final float loadFactor) { - super(initialCapacity, loadFactor); - } - - public FooMap(final int initialCapacity) { - super(initialCapacity); - } - - public FooMap(final Map m) { - super(m); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java deleted file mode 100644 index 52e896438..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsClient.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestWs2WsClient { - private static final long MAX_TEST_LENGTH = 10000; - - private static final int EVENT_COUNT = 100; - private static final int EVENT_INTERVAL = 20; - - @Test - public void testJsonWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsClientJsonEvent.json"}; - testWSEvents(args, false); - } - - @Test - public void testXMLWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsClientXMLEvent.json"}; - testWSEvents(args, true); - } - - private void testWSEvents(final String[] args, final Boolean xmlEvents) throws MessagingException, ApexException { - final WebSocketEventSubscriberServer subServer = new WebSocketEventSubscriberServer(42453); - final WebSocketEventProducerServer prodServer = - new WebSocketEventProducerServer(42451, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); - - final ApexMain apexMain = new ApexMain(args); - - prodServer.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH - && subServer.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - assertEquals(prodServer.getEventsSentCount(), subServer.getEventsReceivedCount()); - - apexMain.shutdown(); - prodServer.shutdown(); - subServer.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java deleted file mode 100644 index 86f6ee123..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/TestWs2WsServer.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; - -public class TestWs2WsServer { - private static final long MAX_TEST_LENGTH = 10000; - - private static final int EVENT_COUNT = 100; - private static final int EVENT_INTERVAL = 20; - - @Test - public void testJsonWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsServerJsonEvent.json"}; - testWSEvents(args, false); - } - - @Test - public void testXMLWSEvents() throws MessagingException, ApexException { - final String[] args = {"src/test/resources/prodcons/Ws2WsServerXMLEvent.json"}; - testWSEvents(args, true); - } - - public void testWSEvents(final String[] args, final boolean xmlEvents) throws MessagingException, ApexException { - final ApexMain apexMain = new ApexMain(args); - - final WebSocketEventSubscriberClient subClient = new WebSocketEventSubscriberClient("localhost", 42452); - final WebSocketEventProducerClient prodClient = - new WebSocketEventProducerClient("localhost", 42450, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); - - prodClient.sendEvents(); - - final long testStartTime = System.currentTimeMillis(); - - while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH - && subClient.getEventsReceivedCount() < EVENT_COUNT) { - ThreadUtilities.sleep(EVENT_INTERVAL); - } - - assertEquals(subClient.getEventsReceivedCount(), prodClient.getEventsSentCount()); - - prodClient.shutdown(); - subClient.shutdown(); - apexMain.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java deleted file mode 100644 index fd78ba5c0..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerClient.java +++ /dev/null @@ -1,176 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * The Class WebSocketEventProducerClient. - */ -public class WebSocketEventProducerClient implements WsStringMessageListener { - private final String host; - private final int port; - private final int eventCount; - private final boolean xmlEvents; - private final long eventInterval; - private long eventsSentCount = 0; - - WsStringMessageClient client; - - /** - * Instantiates a new web socket event producer client. - * - * @param host the host - * @param port the port - * @param eventCount the event count - * @param xmlEvents the xml events - * @param eventInterval the event interval - * @throws MessagingException the messaging exception - */ - public WebSocketEventProducerClient(final String host, final int port, final int eventCount, - final boolean xmlEvents, final long eventInterval) throws MessagingException { - this.host = host; - this.port = port; - this.eventCount = eventCount; - this.xmlEvents = xmlEvents; - this.eventInterval = eventInterval; - - client = new WsStringMessageClient(host, port); - client.start(this); - - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " + port - + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - } - - /** - * Send events. - */ - public void sendEvents() { - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": sending events on host " + host - + ", port " + port + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - - for (int i = 0; i < eventCount; i++) { - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": waiting " + eventInterval - + " milliseconds before sending next event"); - ThreadUtilities.sleep(eventInterval); - - String eventString = null; - if (xmlEvents) { - eventString = EventGenerator.xmlEvent(); - } else { - eventString = EventGenerator.jsonEvent(); - } - client.sendString(eventString); - eventsSentCount++; - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " - + port + ", sent event " + eventString); - } - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": completed"); - } - - /** - * Gets the events sent count. - * - * @return the events sent count - */ - public long getEventsSentCount() { - return eventsSentCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - client.stop(); - System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": stopped"); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": host " + host + ", port " + port - + ", received event " + eventString); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 5) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[1]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[2]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - long eventInterval = 0; - try { - eventInterval = Long.parseLong(args[4]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - boolean xmlEvents = false; - if (args[3].equalsIgnoreCase("XML")) { - xmlEvents = true; - } else if (!args[3].equalsIgnoreCase("JSON")) { - System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); - return; - } - - final WebSocketEventProducerClient client = - new WebSocketEventProducerClient(args[0], port, eventCount, xmlEvents, eventInterval); - - client.sendEvents(); - client.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java deleted file mode 100644 index 53aa0cab4..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventProducerServer.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.apps.uservice.test.adapt.events.EventGenerator; -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -/** - * The Class WebSocketEventProducerServer. - */ -public class WebSocketEventProducerServer implements WsStringMessageListener { - private final int port; - private final int eventCount; - private final boolean xmlEvents; - private final long eventInterval; - private long eventsSentCount = 0; - - WsStringMessageServer server; - - /** - * Instantiates a new web socket event producer server. - * - * @param port the port - * @param eventCount the event count - * @param xmlEvents the xml events - * @param eventInterval the event interval - * @throws MessagingException the messaging exception - */ - public WebSocketEventProducerServer(final int port, final int eventCount, final boolean xmlEvents, - final long eventInterval) throws MessagingException { - this.port = port; - this.eventCount = eventCount; - this.xmlEvents = xmlEvents; - this.eventInterval = eventInterval; - - server = new WsStringMessageServer(port); - server.start(this); - - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + ", event count " - + eventCount + ", xmlEvents " + xmlEvents); - } - - /** - * Send events. - */ - public void sendEvents() { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": sending events on port " + port - + ", event count " + eventCount + ", xmlEvents " + xmlEvents); - - for (int i = 0; i < eventCount; i++) { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": waiting " + eventInterval - + " milliseconds before sending next event"); - ThreadUtilities.sleep(eventInterval); - - String eventString = null; - if (xmlEvents) { - eventString = EventGenerator.xmlEvent(); - } else { - eventString = EventGenerator.jsonEvent(); - } - server.sendString(eventString); - eventsSentCount++; - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port - + ", sent event " + eventString); - } - - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": event sending completed"); - } - - /** - * Gets the events sent count. - * - * @return the events sent count - */ - public long getEventsSentCount() { - return eventsSentCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - server.stop(); - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": stopped"); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port - + ", received event " + eventString); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 4) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[1]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - long eventInterval = 0; - try { - eventInterval = Long.parseLong(args[3]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); - e.printStackTrace(); - return; - } - - boolean xmlEvents = false; - if (args[2].equalsIgnoreCase("XML")) { - xmlEvents = true; - } else if (!args[2].equalsIgnoreCase("JSON")) { - System.err.println("usage WebSocketEventProducerServer port #events XML|JSON startDelay eventInterval"); - return; - } - - final WebSocketEventProducerServer server = - new WebSocketEventProducerServer(port, eventCount, xmlEvents, eventInterval); - - server.sendEvents(); - server.shutdown(); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java deleted file mode 100644 index 27a34a92e..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberClient.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; - -/** - * The Class WebSocketEventSubscriberClient. - */ -public class WebSocketEventSubscriberClient implements WsStringMessageListener { - private final int port; - private long eventsReceivedCount = 0; - - private final WsStringMessageClient client; - - /** - * Instantiates a new web socket event subscriber client. - * - * @param host the host - * @param port the port - * @throws MessagingException the messaging exception - */ - public WebSocketEventSubscriberClient(final String host, final int port) throws MessagingException { - this.port = port; - - client = new WsStringMessageClient(host, port); - client.start(this); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventSubscriberClient.class.getCanonicalName() + ": port " + port - + ", received event " + eventString); - eventsReceivedCount++; - } - - /** - * Gets the events received count. - * - * @return the events received count - */ - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - client.stop(); - System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 2) { - System.err.println("usage WebSocketEventSubscriberClient host port"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventSubscriberClient port"); - e.printStackTrace(); - return; - } - - new WebSocketEventSubscriberClient(args[0], port); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java deleted file mode 100644 index 854a0e410..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/websocket/WebSocketEventSubscriberServer.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.adapt.websocket; - -import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; -import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; - -/** - * The Class WebSocketEventSubscriberServer. - */ -public class WebSocketEventSubscriberServer implements WsStringMessageListener { - private final int port; - private long eventsReceivedCount = 0; - - private final WsStringMessageServer server; - - /** - * Instantiates a new web socket event subscriber server. - * - * @param port the port - * @throws MessagingException the messaging exception - */ - public WebSocketEventSubscriberServer(final int port) throws MessagingException { - this.port = port; - - server = new WsStringMessageServer(port); - server.start(this); - - System.out.println( - WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port + ", waiting for events"); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# - * receiveString(java.lang.String) - */ - @Override - public void receiveString(final String eventString) { - System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port - + ", received event " + eventString); - eventsReceivedCount++; - } - - /** - * Gets the events received count. - * - * @return the events received count - */ - public long getEventsReceivedCount() { - return eventsReceivedCount; - } - - /** - * Shutdown. - */ - public void shutdown() { - server.stop(); - System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); - } - - /** - * The main method. - * - * @param args the arguments - * @throws MessagingException the messaging exception - */ - public static void main(final String[] args) throws MessagingException { - if (args.length != 1) { - System.err.println("usage WebSocketEventSubscriberClient port"); - return; - } - - int port = 0; - try { - port = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage WebSocketEventSubscriberClient port"); - e.printStackTrace(); - return; - } - - new WebSocketEventSubscriberServer(port); - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java deleted file mode 100644 index 8f9aa6cee..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/context/EventAlbumContextTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.context; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.main.ApexMain; -import org.onap.policy.common.utils.resources.ResourceUtils; - -public class EventAlbumContextTest { - private File tempCommandFile; - private File tempLogFile; - private File tempModelFile; - private String eventContextString; - private String configFile; - private String outputFile; - private String compareFile; - - @Rule - public TemporaryFolder tempTestDir = new TemporaryFolder(); - - @Test - public void testJavaEventAlbumContextTest() throws IOException, ApexException { - tempCommandFile = tempTestDir.newFile("TestPolicyJavaEventContext.apex"); - tempLogFile = tempTestDir.newFile("TestPolicyJavaEventContext.log"); - tempModelFile = tempTestDir.newFile("TestPolicyJavaEventContext.json"); - - eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyJavaEventContext.apex"); - - configFile = "src/test/resources/prodcons/Context_JavaEventAlbum_file2file.json"; - outputFile = "src/test/resources/events/Context_JavaEventAlbum_EventOut.json"; - compareFile = "src/test/resources/events/Context_JavaEventAlbum_EventOutCompare.json"; - - testEventAlbumContextTest(); - } - - @Test - public void testAvroEventAlbumContextTest() throws IOException, ApexException { - tempCommandFile = tempTestDir.newFile("TestPolicyAvroEventContext.apex"); - tempLogFile = tempTestDir.newFile("TestPolicyAvroEventContext.log"); - tempModelFile = tempTestDir.newFile("TestPolicyAvroEventContext.json"); - - eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyAvroEventContext.apex"); - - configFile = "src/test/resources/prodcons/Context_AvroEventAlbum_file2file.json"; - outputFile = "src/test/resources/events/Context_AvroEventAlbum_EventOut.json"; - compareFile = "src/test/resources/events/Context_AvroEventAlbum_EventOutCompare.json"; - - testEventAlbumContextTest(); - } - - private void testEventAlbumContextTest() throws IOException, ApexException { - TextFileUtils.putStringAsFile(eventContextString, tempCommandFile); - - final String[] cliArgs = new String[] { "-c", tempCommandFile.getCanonicalPath(), "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath() }; - - new ApexCommandLineEditorMain(cliArgs); - - final String[] args = new String[] { "-m", tempModelFile.getAbsolutePath(), "-c", configFile }; - final ApexMain apexMain = new ApexMain(args); - - // The output event will be in this file - final File outputEventFile = new File(outputFile); - String receivedApexOutputString = ""; - for (int tenthsOfSecondsToWait = 100; tenthsOfSecondsToWait > 0; tenthsOfSecondsToWait--) { - if (outputEventFile.exists() && outputEventFile.length() > 0) { - // The output event is in this file - receivedApexOutputString = TextFileUtils.getTextFileAsString(outputEventFile.getCanonicalPath()) - .replaceAll("\\s+", ""); - break; - } - - ThreadUtilities.sleep(100); - } - - // Shut down Apex - apexMain.shutdown(); - - assertTrue("Test failed, the output event file was not created", outputEventFile.exists()); - outputEventFile.delete(); - - assertTrue("Test failed, the output event file was empty", receivedApexOutputString.length() > 0); - - // We compare the output to what we expect to get - final String expectedFileContent = TextFileUtils - .getTextFileAsString(compareFile); - final String outputEventCompareString = expectedFileContent.replaceAll("\\s+", ""); - - assertEquals(outputEventCompareString, receivedApexOutputString); - } - -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java deleted file mode 100644 index 187a2a316..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngDepMessagingTest.java +++ /dev/null @@ -1,219 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.engdep; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.deployment.BatchDeployer; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -// CHECKSTYLE:OFF: checkstyle:magicNumber - -/** - * The Class EngDepMessagingTest. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EngDepMessagingTest { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngDepMessagingTest.class); - - private static final long MAX_START_WAIT = 10000; // 10 sec - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineServiceParameters engineServiceParameters; - - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineServiceParameters = new EngineServiceParameters(); - engineServiceParameters.setName("EngDepMessagingTest"); - engineServiceParameters.setVersion("0.0.1"); - engineServiceParameters.setDeploymentPort(58820); - engineServiceParameters.setInstanceCount(3); - engineServiceParameters.setId(100); - engineServiceParameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - - ParameterService.register(engineServiceParameters); - ParameterService.register(engineServiceParameters.getEngineParameters()); - } - - @After - public void afterTest() { - ParameterService.deregister(engineServiceParameters); - ParameterService.deregister(engineServiceParameters.getEngineParameters()); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test EngDep messaging. - * - * @throws URISyntaxException the URI syntax exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexException the apex exception - */ - @Test - public void testEngDepMessaging() throws URISyntaxException, IOException, ApexException { - LOGGER.debug("engine<-->deployment messaging test starting . . ."); - - ModelService.clear(); - - final EngineTestServer server = new EngineTestServer(engineServiceParameters); - assertNotNull(server); - - final Thread serverThread = new Thread(server); - serverThread.start(); - final long starttime = System.currentTimeMillis(); - while (server.isStarting() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { - ThreadUtilities.sleep(100); - } - if (server.isStarting()) { - fail("Test server failed to start after " + MAX_START_WAIT + " ms"); - } - - final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - - final BatchDeployer deployer1 = new BatchDeployer("localhost", 58820); - assertNotNull(deployer1); - - deployer1.init(); - deployer1.deployModel(apexPolicyModel, false, false); - deployer1.stopEngines(); - deployer1.startEngines(); - deployer1.close(); - - // Send events - final Date testStartTime = new Date(); - final Map eventDataMap = new HashMap<>(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", (byte) 123); - eventDataMap.put("TestTimestamp", testStartTime.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final ApexEvent event0 = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "apex", "test"); - event0.putAll(eventDataMap); - server.sendEvent(event0); - - final ApexEvent event1 = - new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "apex", "test"); - event1.putAll(eventDataMap); - server.sendEvent(event1); - - // Wait for results - while (server.getTotalActionEventsReceived() < 2) { - ThreadUtilities.sleep(100); - } - ThreadUtilities.sleep(500); - - assertEquals(2, server.getTotalActionEventsReceived()); - - deployer1.init(); - deployer1.stopEngines(); - deployer1.close(); - - // Test re-initialization of model - final BatchDeployer deployer2 = new BatchDeployer("localhost", 58820); - assertNotNull(deployer2); - - deployer2.init(); - deployer2.deployModel(apexPolicyModel, true, true); - deployer2.stopEngines(); - deployer2.startEngines(); - deployer2.close(); - - server.sendEvent(event0); - server.sendEvent(event1); - - // Wait for results - while (server.getTotalActionEventsReceived() < 4) { - ThreadUtilities.sleep(100); - } - ThreadUtilities.sleep(500); - - assertEquals(4, server.getTotalActionEventsReceived()); - - deployer2.init(); - deployer2.stopEngines(); - deployer2.close(); - - server.stopServer(); - LOGGER.debug("engine<-->deployment messaging test finished"); - } - - /** - * Tear down. - * - * @throws Exception the exception - */ - @After - public void tearDown() throws Exception {} -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java deleted file mode 100644 index 1a8b1d364..000000000 --- a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/apps/uservice/test/engdep/EngineTestServer.java +++ /dev/null @@ -1,269 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.apps.uservice.test.engdep; - -import java.util.Date; - -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.engdep.EngDepMessagingService; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.runtime.ApexEventListener; -import org.onap.policy.apex.service.engine.runtime.EngineService; -import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; -import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class EngineTestServer is a test Apex service used to test the performance of Apex engines. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EngineTestServer implements Runnable, EngineServiceEventInterface { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineTestServer.class); - - private static final int TEST_SERVER_WAIT_TIME = 200; - - // The engine service for sending events to the Apex engines and the EngDEp service for engine - // administration - private EngineService engineService = null; - private EngDepMessagingService messageService = null; - - // The inner class used to receive and process events - private TestApexListener testApexListener = null; - - // Status flags - private boolean starting = true; - private boolean interrupted = false; - - // Parameters for the test - private final EngineServiceParameters parameters; - - // Apex performance statistics - private Date statsStartDate = null; - private long actionEventsReceivedCount = 0; - private long accumulatedExecutionTime = 0; - private long totalActionEventsReceivedCount = 0; - - private ApexEvent lastEventReceived = null; - - /** - * Instantiates a new engine test server to test Apex performance. - * - * @param parameters the parameters - */ - public EngineTestServer(final EngineServiceParameters parameters) { - this.parameters = parameters; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - LOGGER.debug("engine<-->deployment test server starting . . ."); - - // Set the name of the test server thread - Thread.currentThread().setName(EngineTestServer.class.getName()); - - try { - // Create the engine service and set the listener for events emitted by the Apex service - engineService = EngineServiceImpl.create(parameters); - testApexListener = new TestApexListener(); - engineService.registerActionListener("testApexListener", testApexListener); - - // Create the EngDep messaging service and start it - messageService = new EngDepMessagingService(engineService, parameters.getDeploymentPort()); - messageService.start(); - - // Record the start date for statistics - statsStartDate = new Date(); - } catch (final Exception e) { - LOGGER.error("engine<-->deployment test server exception", e); - e.printStackTrace(); - return; - } - LOGGER.debug("engine<-->deployment test server started"); - - starting = false; - - while (!interrupted) { - if (!ThreadUtilities.sleep(TEST_SERVER_WAIT_TIME)) { - interrupted = true; - } - } - } - - /** - * Stop the test server. - */ - public void stopServer() { - LOGGER.debug("engine<-->deployment test server stopping . . ."); - - interrupted = true; - messageService.stop(); - - LOGGER.debug("engine<-->deployment test server stopped"); - } - - /** - * Checks if the test server is interrupted. - * - * @return true, if is interrupted - */ - public boolean isInterrupted() { - return interrupted; - } - - /** - * Gets the total action events received. - * - * @return the total action events received - */ - public long getTotalActionEventsReceived() { - return totalActionEventsReceivedCount; - } - - /** - * Gets the last action events received. - * - * @return the last action event received - */ - public ApexEvent getLastActionEvent() { - return lastEventReceived; - } - - /** - * Gets the Apex statistics and resets them. - * - * @return the statistics - */ - public long[] getAndResetStats() { - // Check if we have statistics - if (statsStartDate == null || actionEventsReceivedCount == 0) { - return null; - } - - // Calculate, save, and reset the statistics - final long[] stats = new long[2]; - synchronized (statsStartDate) { - final long averageExecutionTime = accumulatedExecutionTime / actionEventsReceivedCount; - final long measuringTime = new Date().getTime() - statsStartDate.getTime(); - final long transactionsPerMillisecond = actionEventsReceivedCount / measuringTime; - stats[0] = averageExecutionTime; - stats[1] = transactionsPerMillisecond; - statsStartDate = new Date(); - - actionEventsReceivedCount = 0; - accumulatedExecutionTime = 0; - } - - // Return the statistics - return stats; - } - - /** - * Checks if the test server is starting. - * - * @return true, if the server is starting - */ - public boolean isStarting() { - return starting; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface#sendEvent(org.onap. - * policy.apex.service.engine.event.ApexEvent) - */ - @Override - public void sendEvent(final ApexEvent event) { - // Send the event onto the service being tested - engineService.getEngineServiceEventInterface().sendEvent(event); - } - - /** - * The listener interface for receiving testApex events. The class that is interested in - * processing a testApex event implements this interface, and the object created with that class - * is registered with a component using the component's {@code addTestApexListener} method. When - * the testApex event occurs, that object's appropriate method is invoked. - * - * This class listens for events from the Apex engine - * - * @see TestApexEvent - */ - private final class TestApexListener implements ApexEventListener { - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy - * .apex.service.engine.event.ApexEvent) - */ - @Override - public synchronized void onApexEvent(final ApexEvent apexEvent) { - LOGGER.debug("result is:" + apexEvent); - - // Check the result event is correct - checkResult(apexEvent); - - // Calculate the performance of the Apex engine service on this policy execution run and - // accumulate the total statistics - final Date testStartTime = new Date((Long) apexEvent.get("TestTimestamp")); - final Date testEndTime = new Date(); - final long testTime = testEndTime.getTime() - testStartTime.getTime(); - LOGGER.debug("policy execution time: " + testTime + "ms"); - synchronized (statsStartDate) { - actionEventsReceivedCount++; - totalActionEventsReceivedCount++; - accumulatedExecutionTime += testTime; - } - lastEventReceived = apexEvent; - } - - /** - * Check that a reply event from the Apex engine is valid. - * - * @param result the result event from the Apex engine - */ - private void checkResult(final ApexEvent result) { - assert result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"); - - // CHECKSTYLE:OFF: checkstyle:magicNumber - assert result.get("TestSlogan").equals("This is a test slogan"); - assert result.get("TestMatchCase").equals(new Byte((byte) 123)); - assert result.get("TestTemperature").equals(34.5445667); - assert ((byte) result.get("TestMatchCaseSelected") >= 0 && (byte) result.get("TestMatchCaseSelected") <= 3); - assert ((byte) result.get("TestEstablishCaseSelected") >= 0 - && (byte) result.get("TestEstablishCaseSelected") <= 3); - assert ((byte) result.get("TestDecideCaseSelected") >= 0 - && (byte) result.get("TestDecideCaseSelected") <= 3); - assert ((byte) result.get("TestActCaseSelected") >= 0 && (byte) result.get("TestActCaseSelected") <= 3); - // CHECKSTYLE:ON: checkstyle:magicNumber - } - } -} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java new file mode 100644 index 000000000..6a585d7c5 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/events/EventGenerator.java @@ -0,0 +1,610 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.events; + +import java.util.Random; + +/** + * The Class EventGenerator. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EventGenerator { + private static int nextEventNo = 0; + + /** + * Xml events. + * + * @param eventCount the event count + * @return the string + */ + public static String xmlEvents(final int eventCount) { + final StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < eventCount; i++) { + if (i > 0) { + builder.append("\n"); + } + builder.append(xmlEvent()); + } + + return builder.toString(); + } + + /** + * Json events. + * + * @param eventCount the event count + * @return the string + */ + public static String jsonEvents(final int eventCount) { + final StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < eventCount; i++) { + if (i > 0) { + builder.append("\n"); + } + builder.append(jsonEvent()); + } + + return builder.toString(); + } + + /** + * Xml event. + * + * @return the string + */ + public static String xmlEvent() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("\n"); + builder.append("\n"); + + builder.append(" " + eventName + "\n"); + builder.append(" 0.0.1\n"); + builder.append(" org.onap.policy.apex.sample.events\n"); + builder.append(" test\n"); + builder.append(" apex\n"); + builder.append(" \n"); + builder.append(" TestSlogan\n"); + builder.append(" Test slogan for External Event" + (nextEventNo++) + "\n"); + builder.append(" \n"); + builder.append(" \n"); + builder.append(" TestMatchCase\n"); + builder.append(" " + nextMatchCase + "\n"); + builder.append(" \n"); + builder.append(" \n"); + builder.append(" TestTimestamp\n"); + builder.append(" " + System.currentTimeMillis() + "\n"); + builder.append(" \n"); + builder.append(" \n"); + builder.append(" TestTemperature\n"); + builder.append(" " + nextTestTemperature + "\n"); + builder.append(" \n"); + builder.append(""); + + return builder.toString(); + } + + /** + * Json event. + * + * @return the string + */ + public static String jsonEvent() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no name. + * + * @return the string + */ + public static String jsonEventNoName() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"namez\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad name. + * + * @return the string + */ + public static String jsonEventBadName() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"%%%%\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no ex name. + * + * @return the string + */ + public static String jsonEventNoExName() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"I_DONT_EXIST\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no version. + * + * @return the string + */ + public static String jsonEventNoVersion() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"versiion\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad version. + * + * @return the string + */ + public static String jsonEventBadVersion() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"#####\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no ex version. + * + * @return the string + */ + public static String jsonEventNoExVersion() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"1.2.3\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no namespace. + * + * @return the string + */ + public static String jsonEventNoNamespace() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpacee\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad namespace. + * + * @return the string + */ + public static String jsonEventBadNamespace() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"hello.&&&&\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no ex namespace. + * + * @return the string + */ + public static String jsonEventNoExNamespace() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"pie.in.the.sky\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no source. + * + * @return the string + */ + public static String jsonEventNoSource() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"sourcee\": \"test\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad source. + * + * @return the string + */ + public static String jsonEventBadSource() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"%!@**@!\",\n"); + builder.append(" \"target\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event no target. + * + * @return the string + */ + public static String jsonEventNoTarget() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"targett\": \"apex\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event bad target. + * + * @return the string + */ + public static String jsonEventBadTarget() { + final Random rand = new Random(); + + final StringBuilder builder = new StringBuilder(); + + int nextEventNo = rand.nextInt(2); + final String eventName = (nextEventNo == 0 ? "Event0000" : "Event0100"); + final int nextMatchCase = rand.nextInt(4); + final float nextTestTemperature = rand.nextFloat() * 10000; + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"" + eventName + "\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"KNIO(*S)A(S)D\",\n"); + builder.append(" \"TestSlogan\": \"Test slogan for External Event" + (nextEventNo++) + "\",\n"); + builder.append(" \"TestMatchCase\": " + nextMatchCase + ",\n"); + builder.append(" \"TestTimestamp\": " + System.currentTimeMillis() + ",\n"); + builder.append(" \"TestTemperature\": " + nextTestTemperature + "\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event missing fields. + * + * @return the string + */ + public static String jsonEventMissingFields() { + final StringBuilder builder = new StringBuilder(); + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"apex\"\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * Json event null fields. + * + * @return the string + */ + public static String jsonEventNullFields() { + final StringBuilder builder = new StringBuilder(); + + builder.append("{\n"); + builder.append(" \"nameSpace\": \"org.onap.policy.apex.sample.events\",\n"); + builder.append(" \"name\": \"Event0000\",\n"); + builder.append(" \"version\": \"0.0.1\",\n"); + builder.append(" \"source\": \"test\",\n"); + builder.append(" \"target\": \"Apex\",\n"); + builder.append(" \"TestSlogan\": null,\n"); + builder.append(" \"TestMatchCase\": -1,\n"); + builder.append(" \"TestTimestamp\": -1,\n"); + builder.append(" \"TestTemperature\": -1.0\n"); + builder.append("}"); + + return builder.toString(); + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + if (args.length != 2) { + System.err.println("usage EventGenerator #events XML|JSON"); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage EventGenerator #events XML|JSON"); + e.printStackTrace(); + return; + } + + if (args[1].equalsIgnoreCase("XML")) { + System.out.println(xmlEvents(eventCount)); + } else if (args[1].equalsIgnoreCase("JSON")) { + System.out.println(jsonEvents(eventCount)); + } else { + System.err.println("usage EventGenerator #events XML|JSON"); + return; + } + } + + /** + * Gets the next event no. + * + * @return the next event no + */ + public static int getNextEventNo() { + return nextEventNo; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java new file mode 100644 index 000000000..5483501b2 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2File.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.file; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +public class TestFile2File { + + @Test + public void testJsonFileEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; + + testFileEvents(args, "src/test/resources/events/EventsOut.json", 48956); + } + + @Test + public void testXmlFileEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileXmlEvent.json"}; + + testFileEvents(args, "src/test/resources/events/EventsOut.xmlfile", 106739); + } + + private void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) + throws MessagingException, ApexException, IOException { + final ApexMain apexMain = new ApexMain(args); + + final File outFile = new File(outFilePath); + + while (!outFile.exists()) { + ThreadUtilities.sleep(500); + } + + // Wait for the file to be filled + long outFileSize = 0; + while (true) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); + outFileSize = fileString.length(); + if (outFileSize > 0 && outFileSize >= expectedFileSize) { + break; + } + ThreadUtilities.sleep(500); + } + + apexMain.shutdown(); + outFile.delete(); + assertEquals(outFileSize, expectedFileSize); + } +} + + diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java new file mode 100644 index 000000000..48cd6c013 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.file; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +public class TestFile2FileFiltered { + + @Test + public void testJsonFilteredFileInOutEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json"}; + + final String[] outFilePaths = { + "src/test/resources/events/Events0004Out.json", + "src/test/resources/events/Events0104Out.json" + }; + + final long[] expectedFileSizes = {25949, 23007}; + + testFilteredFileEvents(args, outFilePaths, expectedFileSizes); + } + + @Test + public void testJsonFilteredFileOutEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json"}; + + final String[] outFilePaths = { + "src/test/resources/events/Events0004Out.json", + "src/test/resources/events/Events0104Out.json" + }; + + final long[] expectedFileSizes = {25949, 23007}; + + testFilteredFileEvents(args, outFilePaths, expectedFileSizes); + } + + @Test + public void testJsonFilteredFileInEvents() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/File2FileFilteredInJsonEvent.json"}; + + final String[] outFilePaths = {"src/test/resources/events/Events0004Out.json"}; + + final long[] expectedFileSizes = {25949}; + + testFilteredFileEvents(args, outFilePaths, expectedFileSizes); + } + + private void testFilteredFileEvents(final String[] args, final String[] outFilePaths, + final long[] expectedFileSizes) throws MessagingException, ApexException, IOException { + final ApexMain apexMain = new ApexMain(args); + + final File outFile0 = new File(outFilePaths[0]); + + while (!outFile0.exists()) { + ThreadUtilities.sleep(500); + } + + // Wait for the file to be filled + long outFile0Size = 0; + for (int i = 0; i < 4; i++) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[0]).replaceAll("\\s+", ""); + outFile0Size = fileString.length(); + if (outFile0Size > 0 && outFile0Size >= expectedFileSizes[0]) { + break; + } + ThreadUtilities.sleep(500); + } + + ThreadUtilities.sleep(500); + apexMain.shutdown(); + + final long[] actualFileSizes = new long[expectedFileSizes.length]; + + for (int i = 0; i < outFilePaths.length; i++) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePaths[i]).replaceAll("\\s+", ""); + actualFileSizes[i] = fileString.length(); + new File(outFilePaths[i]).delete(); + } + + for (int i = 0; i < actualFileSizes.length; i++) { + assertEquals(actualFileSizes[i], expectedFileSizes[i]); + } + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java new file mode 100644 index 000000000..49c7a96d1 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileIgnore.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.file; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestFile2FileIgnore. + */ +public class TestFile2FileIgnore { + + // This test is used just to bring up an instance of Apex for manual testing and demonstrations + // It should always be ignored in automated testing because it holds Apex up for a very long + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + // time + public static void main(final String[] args) throws MessagingException, ApexException, IOException { + final String[] apexArgs = {"src/test/resources/prodcons/File2FileJsonEvent.json"}; + + testFileEvents(apexArgs, "src/test/resources/events/EventsOut.json", 48656); + } + + /** + * Test file events. + * + * @param args the args + * @param outFilePath the out file path + * @param expectedFileSize the expected file size + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + private static void testFileEvents(final String[] args, final String outFilePath, final long expectedFileSize) + throws MessagingException, ApexException, IOException { + final ApexMain apexMain = new ApexMain(args); + + final File outFile = new File(outFilePath); + + while (!outFile.exists()) { + ThreadUtilities.sleep(500); + } + + // Wait for the file to be filled + long outFileSize = 0; + while (true) { + final String fileString = TextFileUtils.getTextFileAsString(outFilePath).replaceAll("\\s+", ""); + outFileSize = fileString.length(); + if (outFileSize > 0 && outFileSize >= expectedFileSize) { + break; + } + ThreadUtilities.sleep(500); + } + + // Here's the long time I was talking about above! + ThreadUtilities.sleep(100000000); + + apexMain.shutdown(); + outFile.delete(); + assertEquals(outFileSize, expectedFileSize); + } +} + + diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java new file mode 100644 index 000000000..6a7e61739 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventProducer.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.Topic; + +import org.apache.activemq.command.ActiveMQTopic; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class JmsEventProducer. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JmsEventProducer implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(JmsEventProducer.class); + + private final String topic; + private final int eventCount; + private final boolean sendObjects; + private final long eventInterval; + private long eventsSentCount = 0; + + private final Thread producerThread; + private boolean sendEventsFlag = false; + private boolean stopFlag = false; + private final Connection connection; + + /** + * Instantiates a new jms event producer. + * + * @param topic the topic + * @param connectionFactory the connection factory + * @param username the username + * @param password the password + * @param eventCount the event count + * @param sendObjects the send objects + * @param eventInterval the event interval + * @throws JMSException the JMS exception + */ + public JmsEventProducer(final String topic, final ConnectionFactory connectionFactory, final String username, + final String password, final int eventCount, final boolean sendObjects, final long eventInterval) + throws JMSException { + this.topic = topic; + this.eventCount = eventCount; + this.sendObjects = sendObjects; + this.eventInterval = eventInterval; + connection = connectionFactory.createConnection(username, password); + connection.start(); + + producerThread = new Thread(this); + producerThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + final Topic jmsTopic = new ActiveMQTopic(topic); + try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer jmsProducer = jmsSession.createProducer(jmsTopic);) { + + while (producerThread.isAlive() && !stopFlag) { + ThreadUtilities.sleep(50); + + if (sendEventsFlag) { + sendEventsToTopic(jmsSession, jmsProducer); + sendEventsFlag = false; + } + } + + } catch (final Exception e) { + throw new ApexEventRuntimeException("JMS event consumption failed", e); + } + } + + /** + * Send events. + */ + public void sendEvents() { + sendEventsFlag = true; + } + + /** + * Send events to topic. + * + * @param jmsSession the jms session + * @param jmsProducer the jms producer + * @throws JMSException the JMS exception + */ + private void sendEventsToTopic(final Session jmsSession, final MessageProducer jmsProducer) throws JMSException { + + LOGGER.info("{} : sending events to JMS server, event count {}", this.getClass().getCanonicalName(), + eventCount); + + for (int i = 0; i < eventCount; i++) { + ThreadUtilities.sleep(eventInterval); + + Message jmsMessage = null; + if (sendObjects) { + jmsMessage = jmsSession.createObjectMessage(new TestPing()); + } else { + jmsMessage = jmsSession.createTextMessage(EventGenerator.jsonEvent()); + } + jmsProducer.send(jmsMessage); + eventsSentCount++; + } + LOGGER.info("{} : completed, number of events sent", this.getClass().getCanonicalName(), eventsSentCount); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + LOGGER.info("{} : stopping", this.getClass().getCanonicalName()); + stopFlag = true; + + while (producerThread.isAlive()) { + ThreadUtilities.sleep(10); + } + LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java new file mode 100644 index 000000000..d1af8c39a --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.ObjectMessage; +import javax.jms.Session; +import javax.jms.TextMessage; +import javax.jms.Topic; + +import org.apache.activemq.command.ActiveMQTopic; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class JmsEventSubscriber. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JmsEventSubscriber implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(JmsEventSubscriber.class); + + private final String topic; + private long eventsReceivedCount = 0; + + private final Thread subscriberThread; + private final Connection connection; + + + /** + * Instantiates a new jms event subscriber. + * + * @param topic the topic + * @param connectionFactory the connection factory + * @param username the username + * @param password the password + * @throws JMSException the JMS exception + */ + public JmsEventSubscriber(final String topic, final ConnectionFactory connectionFactory, final String username, + final String password) throws JMSException { + this.topic = topic; + connection = connectionFactory.createConnection(username, password); + connection.start(); + + subscriberThread = new Thread(this); + subscriberThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + final Topic jmsTopic = new ActiveMQTopic(topic); + try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageConsumer jmsConsumer = jmsSession.createConsumer(jmsTopic);) { + + while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { + try { + final Message message = jmsConsumer.receive(100); + if (message == null) { + continue; + } + + if (message instanceof ObjectMessage) { + final TestPing testPing = (TestPing) ((ObjectMessage) message).getObject(); + testPing.verify(); + } else if (message instanceof TextMessage) { + ((TextMessage) message).getText(); + } else { + throw new ApexEventException("unknowm message \"" + message + "\" of type \"" + + message.getClass().getCanonicalName() + "\" received"); + } + eventsReceivedCount++; + } catch (final Exception e) { + break; + } + } + + } catch (final Exception e) { + throw new ApexEventRuntimeException("JMS event consumption failed", e); + } + + LOGGER.info("{} : event reception completed", this.getClass().getCanonicalName()); + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + * + * @throws JMSException the JMS exception + */ + public void shutdown() throws JMSException { + subscriberThread.interrupt(); + + while (subscriberThread.isAlive()) { + ThreadUtilities.sleep(10); + } + + connection.close(); + LOGGER.info("{} : stopped", this.getClass().getCanonicalName()); + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java new file mode 100644 index 000000000..b8ea0c7fe --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestContext.java @@ -0,0 +1,282 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.HOST; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.JMS_TOPIC_APEX_IN; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.JMS_TOPIC_APEX_OUT; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.PORT; +import static org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestJms2Jms.connectionFactory; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; +import java.util.Properties; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +import org.apache.activemq.command.ActiveMQTopic; +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; + +/** + * The Class TestContext. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContext implements Context { + + private Properties testProperties; + + /** + * Instantiates a new test context. + */ + public TestContext() { + try { + testProperties = new Properties(); + + final Map params = new HashMap(); + params.put("host", HOST); + params.put("port", PORT); + testProperties.put("ConnectionFactory", connectionFactory); + testProperties.put(JMS_TOPIC_APEX_IN, new ActiveMQTopic(JMS_TOPIC_APEX_IN)); + testProperties.put(JMS_TOPIC_APEX_OUT, new ActiveMQTopic(JMS_TOPIC_APEX_OUT)); + } catch (final Exception e) { + e.printStackTrace(); + throw new ApexRuntimeException("Context initiation failed", e); + } + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookup(javax.naming.Name) + */ + @Override + public Object lookup(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookup(java.lang.String) + */ + @Override + public Object lookup(final String name) throws NamingException { + return testProperties.get(name); + } + + /* (non-Javadoc) + * @see javax.naming.Context#bind(javax.naming.Name, java.lang.Object) + */ + @Override + public void bind(final Name name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#bind(java.lang.String, java.lang.Object) + */ + @Override + public void bind(final String name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rebind(javax.naming.Name, java.lang.Object) + */ + @Override + public void rebind(final Name name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rebind(java.lang.String, java.lang.Object) + */ + @Override + public void rebind(final String name, final Object obj) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#unbind(javax.naming.Name) + */ + @Override + public void unbind(final Name name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#unbind(java.lang.String) + */ + @Override + public void unbind(final String name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rename(javax.naming.Name, javax.naming.Name) + */ + @Override + public void rename(final Name oldName, final Name newName) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#rename(java.lang.String, java.lang.String) + */ + @Override + public void rename(final String oldName, final String newName) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#list(javax.naming.Name) + */ + @Override + public NamingEnumeration list(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#list(java.lang.String) + */ + @Override + public NamingEnumeration list(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#listBindings(javax.naming.Name) + */ + @Override + public NamingEnumeration listBindings(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#listBindings(java.lang.String) + */ + @Override + public NamingEnumeration listBindings(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#destroySubcontext(javax.naming.Name) + */ + @Override + public void destroySubcontext(final Name name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#destroySubcontext(java.lang.String) + */ + @Override + public void destroySubcontext(final String name) throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#createSubcontext(javax.naming.Name) + */ + @Override + public Context createSubcontext(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#createSubcontext(java.lang.String) + */ + @Override + public Context createSubcontext(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookupLink(javax.naming.Name) + */ + @Override + public Object lookupLink(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#lookupLink(java.lang.String) + */ + @Override + public Object lookupLink(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#getNameParser(javax.naming.Name) + */ + @Override + public NameParser getNameParser(final Name name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#getNameParser(java.lang.String) + */ + @Override + public NameParser getNameParser(final String name) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#composeName(javax.naming.Name, javax.naming.Name) + */ + @Override + public Name composeName(final Name name, final Name prefix) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#composeName(java.lang.String, java.lang.String) + */ + @Override + public String composeName(final String name, final String prefix) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#addToEnvironment(java.lang.String, java.lang.Object) + */ + @Override + public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#removeFromEnvironment(java.lang.String) + */ + @Override + public Object removeFromEnvironment(final String propName) throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#getEnvironment() + */ + @Override + public Hashtable getEnvironment() throws NamingException { + return null; + } + + /* (non-Javadoc) + * @see javax.naming.Context#close() + */ + @Override + public void close() throws NamingException {} + + /* (non-Javadoc) + * @see javax.naming.Context#getNameInNamespace() + */ + @Override + public String getNameInNamespace() throws NamingException { + return null; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java new file mode 100644 index 000000000..d04cd5791 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestInitialContextFactory.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import java.util.Hashtable; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.spi.InitialContextFactory; + +/** + * A factory for creating TestInitialContext objects. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestInitialContextFactory implements InitialContextFactory { + + private final Context context = new TestContext(); + + /** + * Instantiates a new test initial context factory. + * + * @throws NamingException the naming exception + */ + public TestInitialContextFactory() throws NamingException {} + + /* + * (non-Javadoc) + * + * @see javax.naming.spi.InitialContextFactory#getInitialContext(java.util.Hashtable) + */ + @Override + public Context getInitialContext(final Hashtable environment) throws NamingException { + return context; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java new file mode 100644 index 000000000..422a97a11 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestJms2Jms.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.jms.JMSException; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.broker.BrokerPlugin; +import org.apache.activemq.broker.BrokerService; +import org.apache.activemq.security.AuthenticationUser; +import org.apache.activemq.security.SimpleAuthenticationPlugin; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestJms2Jms. + */ +public class TestJms2Jms { + public static final String PORT = "5445"; + public static final String HOST = "localhost"; + public static final String JMS_TOPIC_APEX_IN = "jms/topic/apexIn"; + public static final String JMS_TOPIC_APEX_OUT = "jms/topic/apexOut"; + + private static final int SLEEP_TIME = 1500; + private static final String GROUP_ROLE = "guests"; + private static final String PACKAGE_NAME = "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms"; + private static final String USERNAME = "guest"; + private static final String PASSWORD = "IAmAGuest"; + private static final String URL = "tcp://" + HOST + ":" + PORT; + + private static final String DATA_PARENT_DIR = Paths.get("target", "activemq-data").toString(); + + private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestJms2Jms.class); + + private static final long MAX_TEST_LENGTH = 10000; + private static final int EVENT_COUNT = 100; + private static final int EVENT_INTERVAL = 20; + + private static BrokerService broker; + + public static ActiveMQConnectionFactory connectionFactory; + + + /** + * Setup embedded jms server. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setupEmbeddedJmsServer() throws Exception { + final ArrayList plugins = new ArrayList(); + final BrokerPlugin authenticationPlugin = getAuthenticationBrokerPlugin(); + plugins.add(authenticationPlugin); + + broker = new BrokerService(); + broker.setUseJmx(false); + broker.setPersistent(false); + broker.addConnector(URL); + broker.setDeleteAllMessagesOnStartup(true); + broker.setPlugins(plugins.toArray(new BrokerPlugin[0])); + broker.setDataDirectory(DATA_PARENT_DIR); + broker.start(); + broker.waitUntilStarted(); + connectionFactory = new ActiveMQConnectionFactory(URL); + connectionFactory.setTrustedPackages(Arrays.asList(PACKAGE_NAME)); + } + + /** + * Gets the authentication broker plugin. + * + * @return the authentication broker plugin + */ + private static BrokerPlugin getAuthenticationBrokerPlugin() { + final List users = new ArrayList(); + users.add(new AuthenticationUser(USERNAME, PASSWORD, GROUP_ROLE)); + final SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(users); + return authenticationPlugin; + } + + /** + * Shutdown embedded jms server. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @AfterClass + public static void shutdownEmbeddedJmsServer() throws IOException { + try { + if (broker != null) { + broker.stop(); + } + } catch (final Exception e) { + LOGGER.warn("Failed to stop JMS server", e); + } + + } + + /** + * Test jms object events. + * + * @throws ApexException the apex exception + * @throws JMSException the JMS exception + */ + @Test + public void testJmsObjectEvents() throws ApexException, JMSException { + final String[] args = { "src/test/resources/prodcons/JMS2JMSObjectEvent.json" }; + testJmsEvents(args, true); + } + + /** + * Test jms json events. + * + * @throws ApexException the apex exception + * @throws JMSException the JMS exception + */ + @Test + public void testJmsJsonEvents() throws ApexException, JMSException { + final String[] args = { "src/test/resources/prodcons/JMS2JMSJsonEvent.json" }; + testJmsEvents(args, false); + } + + /** + * Test jms events. + * + * @param args the args + * @param sendObjects the send objects + * @throws ApexException the apex exception + * @throws JMSException the JMS exception + */ + private void testJmsEvents(final String[] args, final Boolean sendObjects) throws ApexException, JMSException { + final JmsEventSubscriber subscriber = + new JmsEventSubscriber(JMS_TOPIC_APEX_OUT, connectionFactory, USERNAME, PASSWORD); + final JmsEventProducer producer = new JmsEventProducer(JMS_TOPIC_APEX_IN, connectionFactory, USERNAME, PASSWORD, + EVENT_COUNT, sendObjects, EVENT_INTERVAL); + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(3000); + + producer.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (isTimedOut(testStartTime) && subscriber.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + ThreadUtilities.sleep(SLEEP_TIME); + apexMain.shutdown(); + subscriber.shutdown(); + producer.shutdown(); + ThreadUtilities.sleep(SLEEP_TIME); + + assertEquals(EVENT_COUNT, producer.getEventsSentCount()); + assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); + + } + + /** + * Checks if is timed out. + * + * @param testStartTime the test start time + * @return true, if is timed out + */ + private boolean isTimedOut(final long testStartTime) { + return System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java new file mode 100644 index 000000000..b0dfb553a --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/TestPing.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms; + +import java.io.Serializable; + +import org.onap.policy.apex.service.engine.event.ApexEventException; + +/** + * The Class TestPing. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestPing implements Serializable { + private static final long serialVersionUID = -3400711508992955886L; + + private String name = "Rose"; + private String description = "A rose by any other name would smell as sweet"; + private long pingTime = System.currentTimeMillis(); + private long pongTime = -1; + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(final String name) { + this.name = name; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets the description. + * + * @param description the new description + */ + public void setDescription(final String description) { + this.description = description; + } + + /** + * Gets the ping time. + * + * @return the ping time + */ + public long getPingTime() { + return pingTime; + } + + /** + * Sets the ping time. + * + * @param pingTime the new ping time + */ + public void setPingTime(final long pingTime) { + this.pingTime = pingTime; + } + + /** + * Gets the pong time. + * + * @return the pong time + */ + public long getPongTime() { + return pongTime; + } + + /** + * Sets the pong time. + * + * @param pongTime the new pong time + */ + public void setPongTime(final long pongTime) { + this.pongTime = pongTime; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "TestPing [name=" + name + ", description=" + description + ", pingTime=" + pingTime + ", pongTime=" + + pongTime + "]"; + } + + /** + * Verify. + * + * @throws ApexEventException the apex event exception + */ + public void verify() throws ApexEventException { + if (!name.startsWith("Rose")) { + throw new ApexEventException("TestPing is not valid"); + } + + if (name.length() <= 4) { + throw new ApexEventException("TestPing is not valid"); + } + + if (!description.startsWith("A rose by any other name would smell as sweet")) { + throw new ApexEventException("TestPing is not valid"); + } + + if (description.length() <= 44) { + throw new ApexEventException("TestPing is not valid"); + } + + if (pongTime <= pingTime) { + throw new ApexEventException("TestPing is not valid"); + } + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java new file mode 100644 index 000000000..072d67864 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventProducer.java @@ -0,0 +1,201 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; + +/** + * The Class KafkaEventProducer. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class KafkaEventProducer implements Runnable { + private final String topic; + private final String kafkaServerAddress; + private final int eventCount; + private final boolean xmlEvents; + private final long eventInterval; + private long eventsSentCount = 0; + + private final Thread producerThread; + private boolean sendEventsFlag = false; + private boolean stopFlag = false; + + /** + * Instantiates a new kafka event producer. + * + * @param topic the topic + * @param kafkaServerAddress the kafka server address + * @param eventCount the event count + * @param xmlEvents the xml events + * @param eventInterval the event interval + */ + public KafkaEventProducer(final String topic, final String kafkaServerAddress, final int eventCount, + final boolean xmlEvents, final long eventInterval) { + this.topic = topic; + this.kafkaServerAddress = kafkaServerAddress; + this.eventCount = eventCount; + this.xmlEvents = xmlEvents; + this.eventInterval = eventInterval; + + producerThread = new Thread(this); + producerThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + final Properties kafkaProducerProperties = new Properties(); + kafkaProducerProperties.put("bootstrap.servers", kafkaServerAddress); + kafkaProducerProperties.put("acks", "all"); + kafkaProducerProperties.put("retries", 0); + kafkaProducerProperties.put("batch.size", 16384); + kafkaProducerProperties.put("linger.ms", 1); + kafkaProducerProperties.put("buffer.memory", 33554432); + kafkaProducerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + kafkaProducerProperties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + + final Producer producer = new KafkaProducer(kafkaProducerProperties); + + while (producerThread.isAlive() && !stopFlag) { + ThreadUtilities.sleep(50); + + if (sendEventsFlag) { + sendEventsToTopic(producer); + sendEventsFlag = false; + } + } + + producer.close(1000, TimeUnit.MILLISECONDS); + } + + /** + * Send events. + */ + public void sendEvents() { + sendEventsFlag = true; + } + + /** + * Send events to topic. + * + * @param producer the producer + */ + private void sendEventsToTopic(final Producer producer) { + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sending events to Kafka server at " + + kafkaServerAddress + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + + for (int i = 0; i < eventCount; i++) { + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": waiting " + eventInterval + + " milliseconds before sending next event"); + ThreadUtilities.sleep(eventInterval); + + String eventString = null; + if (xmlEvents) { + eventString = EventGenerator.xmlEvent(); + } else { + eventString = EventGenerator.jsonEvent(); + } + producer.send(new ProducerRecord(topic, "Event" + i + "Of" + eventCount, eventString)); + producer.flush(); + eventsSentCount++; + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": sent event " + eventString); + } + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": completed"); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopping"); + + stopFlag = true; + + while (producerThread.isAlive()) { + ThreadUtilities.sleep(10); + } + + System.out.println(KafkaEventProducer.class.getCanonicalName() + ": stopped"); + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + if (args.length != 5) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[2]); + } catch (final Exception e) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + long eventInterval = 0; + try { + eventInterval = Long.parseLong(args[4]); + } catch (final Exception e) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + boolean xmlEvents = false; + if (args[3].equalsIgnoreCase("XML")) { + xmlEvents = true; + } else if (!args[3].equalsIgnoreCase("JSON")) { + System.err.println("usage KafkaEventProducer topic kafkaServerAddress #events XML|JSON eventInterval"); + return; + } + + final KafkaEventProducer producer = new KafkaEventProducer(args[0], args[1], eventCount, xmlEvents, + eventInterval); + + producer.sendEvents(); + producer.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java new file mode 100644 index 000000000..4b6a62e28 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/KafkaEventSubscriber.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import java.util.Arrays; +import java.util.Properties; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; + +/** + * The Class KafkaEventSubscriber. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class KafkaEventSubscriber implements Runnable { + private final String topic; + private final String kafkaServerAddress; + private long eventsReceivedCount = 0; + + KafkaConsumer consumer; + + Thread subscriberThread; + + /** + * Instantiates a new kafka event subscriber. + * + * @param topic the topic + * @param kafkaServerAddress the kafka server address + * @throws MessagingException the messaging exception + */ + public KafkaEventSubscriber(final String topic, final String kafkaServerAddress) throws MessagingException { + this.topic = topic; + this.kafkaServerAddress = kafkaServerAddress; + + final Properties props = new Properties(); + props.put("bootstrap.servers", kafkaServerAddress); + props.put("group.id", "test"); + props.put("enable.auto.commit", "true"); + props.put("auto.commit.interval.ms", "1000"); + props.put("session.timeout.ms", "30000"); + props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); + + consumer = new KafkaConsumer(props); + consumer.subscribe(Arrays.asList(topic)); + + subscriberThread = new Thread(this); + subscriberThread.start(); + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": receiving events from Kafka server at " + + kafkaServerAddress + " on topic " + topic); + + while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) { + try { + final ConsumerRecords records = consumer.poll(100); + for (final ConsumerRecord record : records) { + System.out.println("******"); + System.out.println("offset=" + record.offset()); + System.out.println("key=" + record.key()); + System.out.println("name=" + record.value()); + eventsReceivedCount++; + } + } catch (final Exception e) { + // Thread interrupted + break; + } + } + + System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": event reception completed"); + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + subscriberThread.interrupt(); + + while (subscriberThread.isAlive()) { + ThreadUtilities.sleep(10); + } + + consumer.close(); + System.out.println(KafkaEventSubscriber.class.getCanonicalName() + ": stopped"); + } + + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 2) { + System.err.println("usage KafkaEventSubscriber topic kafkaServerAddress"); + return; + } + new KafkaEventSubscriber(args[0], args[1]); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java new file mode 100644 index 000000000..e70a597c2 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafka2Kafka.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.Properties; + +import kafka.admin.AdminUtils; +import kafka.admin.RackAwareMode; +import kafka.server.KafkaConfig; +import kafka.server.KafkaServer; +import kafka.utils.TestUtils; +import kafka.utils.ZKStringSerializer$; +import kafka.utils.ZkUtils; +import kafka.zk.EmbeddedZookeeper; + +import org.I0Itec.zkclient.ZkClient; +import org.apache.kafka.common.utils.MockTime; +import org.apache.kafka.common.utils.Time; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + + +/** + * The Class TestKafka2Kafka. + */ +public class TestKafka2Kafka { + // The method of starting an embedded Kafka server used in this example is based on the method + // on stack overflow at + // https://github.com/asmaier/mini-kafka + + private static final long MAX_TEST_LENGTH = 20000; + + private static final int EVENT_COUNT = 10; + private static final int EVENT_INTERVAL = 20; + + private static final String ZKHOST = "127.0.0.1"; + private static final String BROKERHOST = "127.0.0.1"; + private static final String BROKERPORT = "39902"; + + private static EmbeddedZookeeper zkServer; + private static ZkClient zkClient; + private static KafkaServer kafkaServer; + + /** + * Setup dummy kafka server. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @BeforeClass + public static void setupDummyKafkaServer() throws IOException { + // setup Zookeeper + zkServer = new EmbeddedZookeeper(); + final String zkConnect = ZKHOST + ":" + zkServer.port(); + zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer$.MODULE$); + final ZkUtils zkUtils = ZkUtils.apply(zkClient, false); + + // setup Broker + final Properties brokerProps = new Properties(); + brokerProps.setProperty("zookeeper.connect", zkConnect); + brokerProps.setProperty("broker.id", "0"); + brokerProps.setProperty("log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString()); + brokerProps.setProperty("listeners", "PLAINTEXT://" + BROKERHOST + ":" + BROKERPORT); + brokerProps.setProperty("offsets.topic.replication.factor", "1"); + brokerProps.setProperty("transaction.state.log.replication.factor", "1"); + brokerProps.setProperty("transaction.state.log.min.isr", "1"); + final KafkaConfig config = new KafkaConfig(brokerProps); + final Time mock = new MockTime(); + kafkaServer = TestUtils.createServer(config, mock); + kafkaServer.startup(); + + // create topics + AdminUtils.createTopic(zkUtils, "apex-in-0", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); + AdminUtils.createTopic(zkUtils, "apex-in-1", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); + AdminUtils.createTopic(zkUtils, "apex-out", 1, 1, new Properties(), RackAwareMode.Disabled$.MODULE$); + + } + + /** + * Shutdown dummy kafka server. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @AfterClass + public static void shutdownDummyKafkaServer() throws IOException { + if (kafkaServer != null) { + kafkaServer.shutdown(); + } + if (zkClient != null) { + zkClient.close(); + } + if (zkServer != null) { + zkServer.shutdown(); + } + } + + /** + * Test json kafka events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testJsonKafkaEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Kafka2KafkaJsonEvent.json"}; + testKafkaEvents(args, false, "json"); + } + + /** + * Test XML kafka events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testXmlKafkaEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Kafka2KafkaXmlEvent.json"}; + testKafkaEvents(args, true, "xml"); + } + + /** + * Test kafka events. + * + * @param args the args + * @param xmlEvents the xml events + * @param topicSuffix the topic suffix + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + private void testKafkaEvents(final String[] args, final Boolean xmlEvents, final String topicSuffix) + throws MessagingException, ApexException { + final KafkaEventSubscriber subscriber = + new KafkaEventSubscriber("apex-out-" + topicSuffix, "localhost:" + BROKERPORT); + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(3000); + + final KafkaEventProducer producer = new KafkaEventProducer("apex-in-" + topicSuffix, "localhost:" + BROKERPORT, + EVENT_COUNT, xmlEvents, EVENT_INTERVAL); + + producer.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH + && subscriber.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + ThreadUtilities.sleep(1000); + + assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount()); + + apexMain.shutdown(); + subscriber.shutdown(); + producer.shutdown(); + ThreadUtilities.sleep(1000); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java new file mode 100644 index 000000000..2b16d71d4 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/kafka/TestKafkaXmlEventProducer.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka; + +import java.util.Properties; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent; +import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData; + +/** + * The Class TestKafkaXmlEventProducer. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestKafkaXmlEventProducer { + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + final Properties props = new Properties(); + props.put("bootstrap.servers", "localhost:49092"); + props.put("acks", "all"); + props.put("retries", 0); + props.put("batch.size", 16384); + props.put("linger.ms", 1); + props.put("buffer.memory", 33554432); + props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); + + final XMLApexEvent xmlEvent = new XMLApexEvent(); + xmlEvent.setName("XMLEvent-1"); + xmlEvent.setVersion("0.0.1"); + xmlEvent.getData().add(new XMLApexEventData("Data-1", "Data Value -1")); + + final Producer producer = new KafkaProducer(props); + for (int i = 0; i < 100; i++) { + xmlEvent.setName("XMLEvent" + Integer.toString(i)); + xmlEvent.setVersion("0.0.1"); + xmlEvent.getData() + .add(new XMLApexEventData("Data" + Integer.toString(i), "Data Value " + Integer.toString(i))); + + producer.send(new ProducerRecord("apex-in-0", xmlEvent.getName(), xmlEvent.toString())); + } + producer.close(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java new file mode 100644 index 000000000..d681fd471 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestFile2Rest.java @@ -0,0 +1,266 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; +import java.util.Map; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.core.Response; + +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.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestFile2Rest. + */ +public class TestFile2Rest { + private static final String BASE_URI = "http://localhost:32801/TestFile2Rest"; + private static HttpServer server; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + + private final PrintStream stdout = System.out; + private final PrintStream stderr = System.err; + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setUp() throws Exception { + final ResourceConfig rc = new ResourceConfig(TestRestClientEndpoint.class); + server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); + + while (!server.isStarted()) { + ThreadUtilities.sleep(50); + } + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + @AfterClass + public static void tearDown() throws Exception { + server.shutdown(); + } + + /** + * Test file events post. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsPost() throws MessagingException, ApexException, IOException { + final Client client = ClientBuilder.newClient(); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventPost.json" }; + final ApexMain apexMain = new ApexMain(args); + + // Wait for the required amount of events to be received or for 10 seconds + for (int i = 0; i < 100; i++) { + ThreadUtilities.sleep(100); + final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") + .request("application/json").get(); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + if ((double) jsonMap.get("POST") == 100) { + break; + } + } + + apexMain.shutdown(); + } + + /** + * Test file events put. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsPut() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventPut.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + // Wait for the required amount of events to be received or for 10 seconds + for (int i = 0; i < 100; i++) { + ThreadUtilities.sleep(100); + final Response response = client.target("http://localhost:32801/TestFile2Rest/apex/event/Stats") + .request("application/json").get(); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + if ((double) jsonMap.get("PUT") == 100) { + break; + } + } + + apexMain.shutdown(); + } + + /** + * Test file events no url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsNoUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventNoURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" no URL has been set for event sending on REST client")); + } + + /** + * Test file events bad url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventBadURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/Bad\" using HTTP \"POST\" failed with status code 404")); + } + + /** + * Test file events bad http method. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadHttpMethod() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "specified HTTP method of \"DELETE\" is invalid, only HTTP methods \"POST\" and \"PUT\" " + + "are supproted for event sending on REST client producer")); + } + + /** + * Test file events bad response. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(500); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "send of event to URL \"http://localhost:32801/TestFile2Rest/apex/event/PostEventBadResponse\" using HTTP \"POST\" failed with status code 400")); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java new file mode 100644 index 000000000..ec41de5fb --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java @@ -0,0 +1,251 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; + +import org.glassfish.grizzly.http.server.HttpServer; +import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestRest2File. + */ +public class TestRest2File { + + private static final String BASE_URI = "http://localhost:32801/TestRest2File"; + private HttpServer server; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + + private final PrintStream stdout = System.out; + private final PrintStream stderr = System.err; + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @Before + public void setUp() throws Exception { + final ResourceConfig rc = new ResourceConfig(TestRestClientEndpoint.class); + server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); + + while (!server.isStarted()) { + ThreadUtilities.sleep(50); + } + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + @After + public void tearDown() throws Exception { + server.shutdown(); + } + + /** + * Delete temp files. + */ + @AfterClass + public static void deleteTempFiles() { + new File("src/test/resources/events/EventsOut.json").delete(); + } + + /** + * Test rest events in. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestEventsIn() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEvent.json" }; + + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outputEventText = TextFileUtils.getTextFileAsString("src/test/resources/events/EventsOut.json"); + assertTrue(outputEventText.contains("04\",\n" + " \"version\": \"0.0.1\",\n" + + " \"nameSpace\": \"org.onap.policy.apex.sample.events\"")); + } + + /** + * Test file empty events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEmptyEvents() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEmptyEvents.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "received an empty event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"")); + } + + /** + * Test file events no url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsNoUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventNoURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" no URL has been set for event sending on REST client")); + } + + /** + * Test file events bad url. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadUrl() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventBadURL.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404")); + } + + /** + * Test file events bad http method. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadHttpMethod() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("specified HTTP method of \"POST\" is invalid, " + + "only HTTP method \"GET\" is supported for event reception on REST client consumer")); + } + + /** + * Test file events bad response. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/REST2FileJsonEventBadResponse.json" }; + final ApexMain apexMain = new ApexMain(args); + + ThreadUtilities.sleep(1000); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" failed with status code 400 and message \"\"")); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java new file mode 100644 index 000000000..906b20bf2 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRestClientEndpoint.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.util.Map; +import java.util.Random; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; + +/** + * The Class TestRestClientEndpoint. + */ +@Path("/apex") +public class TestRestClientEndpoint { + + private static int postMessagesReceived = 0; + private static int putMessagesReceived = 0; + private static int statMessagesReceived = 0; + private static int getMessagesReceived = 0; + + /** + * Service get stats. + * + * @return the response + */ + @Path("/event/Stats") + @GET + public Response serviceGetStats() { + statMessagesReceived++; + return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } + + /** + * Service get event. + * + * @return the response + */ + @Path("/event/GetEvent") + @GET + public Response serviceGetEvent() { + final Random rand = new Random(); + final int nextMatchCase = rand.nextInt(4); + final String nextEventName = "Event0" + rand.nextInt(2) + "00"; + + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" + + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + getMessagesReceived + + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" + + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; + + getMessagesReceived++; + + return Response.status(200).entity(eventString).build(); + } + + /** + * Service get empty event. + * + * @return the response + */ + @Path("/event/GetEmptyEvent") + @GET + public Response serviceGetEmptyEvent() { + return Response.status(200).build(); + } + + /** + * Service get event bad response. + * + * @return the response + */ + @Path("/event/GetEventBadResponse") + @GET + public Response serviceGetEventBadResponse() { + return Response.status(400).build(); + } + + /** + * Service post request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PostEvent") + @POST + public Response servicePostRequest(final String jsonString) { + postMessagesReceived++; + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(jsonString, Map.class); + assertTrue(jsonMap.containsKey("name")); + assertEquals("0.0.1", jsonMap.get("version")); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Act", jsonMap.get("source")); + assertEquals("Outside", jsonMap.get("target")); + + return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } + + /** + * Service post request bad response. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PostEventBadResponse") + @POST + public Response servicePostRequestBadResponse(final String jsonString) { + return Response.status(400).build(); + } + + /** + * Service put request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PutEvent") + @PUT + public Response servicePutRequest(final String jsonString) { + putMessagesReceived++; + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(jsonString, Map.class); + assertTrue(jsonMap.containsKey("name")); + assertEquals("0.0.1", jsonMap.get("version")); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Act", jsonMap.get("source")); + assertEquals("Outside", jsonMap.get("target")); + + return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java new file mode 100644 index 000000000..59cc2ceea --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServer.java @@ -0,0 +1,447 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Map; +import java.util.Random; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestRestServer. + */ +public class TestRestServer { + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + + private final PrintStream stdout = System.out; + private final PrintStream stderr = System.err; + + private static int eventsSent = 0; + + /** + * Test rest server put. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerPut() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEvent.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); + } + + apexMain.shutdown(); + } + + /** + * Test rest server post. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerPost() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEvent.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); + } + + apexMain.shutdown(); + } + + /** + * Test rest server get status. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerGetStatus() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEvent.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + // trigger 10 POST & PUT events + for (int i = 0; i < 10; i++) { + final Response postResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + final Response putResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(getEvent())); + assertEquals(Response.Status.OK.getStatusCode(), postResponse.getStatus()); + assertEquals(Response.Status.OK.getStatusCode(), putResponse.getStatus()); + } + + final Response statResponse = client.target("http://localhost:23324/apex/FirstConsumer/Status") + .request("application/json").get(); + + assertEquals(Response.Status.OK.getStatusCode(), statResponse.getStatus()); + final String responseString = statResponse.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("[FirstConsumer", ((String)jsonMap.get("INPUTS")).substring(0, 14)); + assertEquals(1.0, jsonMap.get("STAT")); + assertTrue((double)jsonMap.get("POST") >= 10.0); + assertTrue((double)jsonMap.get("PUT") >= 10.0); + + apexMain.shutdown(); + } + + /** + * Test rest server multi inputs. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerMultiInputs() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventMultiIn.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response firstResponse = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), firstResponse.getStatus()); + final String firstResponseString = firstResponse.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map firstJsonMap = new Gson().fromJson(firstResponseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", firstJsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", firstJsonMap.get("TestSlogan")); + + final Response secondResponse = client.target("http://localhost:23324/apex/SecondConsumer/EventIn") + .request("application/json").post(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), secondResponse.getStatus()); + final String secondResponseString = secondResponse.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map secondJsonMap = new Gson().fromJson(secondResponseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", secondJsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", secondJsonMap.get("TestSlogan")); + } + + apexMain.shutdown(); + } + + /** + * Test rest server producer standalone. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerStandalone() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains( + "the parameters \"host\", \"port\", and \"standalone\" are illegal on REST Server producer")); + } + + /** + * Test rest server producer host. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerHost() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerHost.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" host is specified only in standalone mode")); + } + + /** + * Test rest server producer port. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerPort() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerPort.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains(" port is specified only in standalone mode")); + } + + /** + * Test rest server consumer standalone no host. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerConsumerStandaloneNoHost() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer " + + "(FirstConsumer) in standalone mode")); + } + + /** + * Test rest server consumer standalone no port. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerConsumerStandaloneNoPort() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("the parameters \"host\" and \"port\" must be defined for REST Server consumer " + + "(FirstConsumer) in standalone mode")); + } + + /** + * Test rest server producer not sync. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerProducerNotSync() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString.contains("REST Server producer (FirstProducer) must run in synchronous mode " + + "with a REST Server consumer")); + } + + /** + * Test rest server consumer not sync. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerConsumerNotSync() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json" }; + + final ApexMain apexMain = new ApexMain(args); + ThreadUtilities.sleep(200); + apexMain.shutdown(); + + final String outString = outContent.toString(); + + System.setOut(stdout); + System.setErr(stderr); + + assertTrue(outString + .contains("peer \"FirstConsumer for peered mode SYNCHRONOUS does not exist or is not defined " + + "with the same peered mode")); + } + + /** + * Test rest server divide by zero. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestServerDivideByZero() throws MessagingException, ApexException, IOException { + final String[] args = + { "src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json" }; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + for (int i = 0; i < 20; i++) { + final Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(getEvent())); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + final String responseString = response.readEntity(String.class); + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(responseString, Map.class); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Test slogan for External Event0", jsonMap.get("TestSlogan")); + assertTrue(((String) jsonMap.get("exceptionMessage")).contains("caused by: / by zero")); + } + + apexMain.shutdown(); + } + + /** + * Gets the event. + * + * @return the event + */ + private String getEvent() { + final Random rand = new Random(); + final int nextMatchCase = rand.nextInt(4); + final String nextEventName = "Event0" + rand.nextInt(2) + "00"; + + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" + + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + eventsSent++ + + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" + + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + + System.currentTimeMillis() + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; + + return eventString; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java new file mode 100644 index 000000000..1791033e6 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restserver/TestRestServerVpnContext.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.restserver; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; + +import org.junit.Ignore; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + + +public class TestRestServerVpnContext { + private static int eventsSent = 0; + + @Ignore + @Test + public void testRestServerPut() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextJava.json"}; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(setupLinkContext("L09", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupLinkContext("L10", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + ThreadUtilities.sleep(100000); + + apexMain.shutdown(); + } + + @Ignore + @Test + public void testRestServerPutAvro() throws MessagingException, ApexException, IOException { + final String[] args = {"src/test/resources/prodcons/RESTServerJsonEventContextAvro.json"}; + final ApexMain apexMain = new ApexMain(args); + + final Client client = ClientBuilder.newClient(); + + Response response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn") + .request("application/json").put(Entity.json(setupLinkContext("L09", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupLinkContext("L10", true))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("A", "L09 L10", 300, 50))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("B", "L09 L10", 300, 299))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("C", "L09 L10", 300, 300))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + response = client.target("http://localhost:23324/apex/FirstConsumer/EventIn").request("application/json") + .put(Entity.json(setupCustomerContext("D", "L09 L10", 300, 400))); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + ThreadUtilities.sleep(100000); + + apexMain.shutdown(); + } + + private String setupLinkContext(final String link, final Boolean isUp) { + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" + + "\"name\": \"VPNLinkCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"Link\": \"" + link + "\",\n" + "\"LinkUp\": " + + isUp + "\n" + "}"; + + return eventString; + } + + private String setupCustomerContext(final String customerName, final String linkList, final int slaDt, + final int ytdDt) { + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.domains.vpn.events\",\n" + + "\"name\": \"VPNCustomerCtxtTriggerEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + + eventsSent++ + "\",\n" + "\"target\": \"apex\",\n" + "\"CustomerName\": \"" + customerName + "\",\n" + + "\"LinkList\": \"" + linkList + "\",\n" + "\"SlaDT\": \"" + slaDt + "\",\n" + "\"YtdDT\": " + ytdDt + + "\n" + "}"; + + return eventString; + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java new file mode 100644 index 000000000..2d6ab4629 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/Foo.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.sampletypes; + +public class Foo { + private String bar; + + public String getBar() { + return bar; + } + + public void setBar(final String bar) { + this.bar = bar; + } + + public Foo(final String bar) { + this(); + this.bar = bar; + } + + public Foo() { + super(); + } + + @Override + public String toString() { + return "Foo [bar=(String)\"" + bar + "\"]"; + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java new file mode 100644 index 000000000..af09e5a3b --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/sampletypes/FooMap.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.sampletypes; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class FooMap extends LinkedHashMap { + private static final long serialVersionUID = -7125986379378753022L; + + public FooMap() { + super(); + } + + public FooMap(final int initialCapacity, final float loadFactor, final boolean accessOrder) { + super(initialCapacity, loadFactor, accessOrder); + } + + public FooMap(final int initialCapacity, final float loadFactor) { + super(initialCapacity, loadFactor); + } + + public FooMap(final int initialCapacity) { + super(initialCapacity); + } + + public FooMap(final Map map) { + super(map); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java new file mode 100644 index 000000000..c2db95860 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsClient.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +public class TestWs2WsClient { + private static final long MAX_TEST_LENGTH = 10000; + + private static final int EVENT_COUNT = 100; + private static final int EVENT_INTERVAL = 20; + + @Test + public void testJsonWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsClientJsonEvent.json"}; + testWsEvents(args, false); + } + + @Test + public void testXmlWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsClientXMLEvent.json"}; + testWsEvents(args, true); + } + + private void testWsEvents(final String[] args, final Boolean xmlEvents) throws MessagingException, ApexException { + final WebSocketEventSubscriberServer subServer = new WebSocketEventSubscriberServer(42453); + final WebSocketEventProducerServer prodServer = + new WebSocketEventProducerServer(42451, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); + + final ApexMain apexMain = new ApexMain(args); + + prodServer.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH + && subServer.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + assertEquals(prodServer.getEventsSentCount(), subServer.getEventsReceivedCount()); + + apexMain.shutdown(); + prodServer.shutdown(); + subServer.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java new file mode 100644 index 000000000..34871e3c6 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/TestWs2WsServer.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * The Class TestWs2WsServer. + */ +public class TestWs2WsServer { + private static final long MAX_TEST_LENGTH = 10000; + + private static final int EVENT_COUNT = 100; + private static final int EVENT_INTERVAL = 20; + + /** + * Test json ws events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testJsonWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsServerJsonEvent.json"}; + testWsEvents(args, false); + } + + /** + * Test xml ws events. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + @Test + public void testXmlWsEvents() throws MessagingException, ApexException { + final String[] args = {"src/test/resources/prodcons/Ws2WsServerXMLEvent.json"}; + testWsEvents(args, true); + } + + /** + * Test ws events. + * + * @param args the args + * @param xmlEvents the xml events + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + */ + public void testWsEvents(final String[] args, final boolean xmlEvents) throws MessagingException, ApexException { + final ApexMain apexMain = new ApexMain(args); + + final WebSocketEventSubscriberClient subClient = new WebSocketEventSubscriberClient("localhost", 42452); + final WebSocketEventProducerClient prodClient = + new WebSocketEventProducerClient("localhost", 42450, EVENT_COUNT, xmlEvents, EVENT_INTERVAL); + + prodClient.sendEvents(); + + final long testStartTime = System.currentTimeMillis(); + + while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH + && subClient.getEventsReceivedCount() < EVENT_COUNT) { + ThreadUtilities.sleep(EVENT_INTERVAL); + } + + assertEquals(subClient.getEventsReceivedCount(), prodClient.getEventsSentCount()); + + prodClient.shutdown(); + subClient.shutdown(); + apexMain.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java new file mode 100644 index 000000000..84a337362 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerClient.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; + +/** + * The Class WebSocketEventProducerClient. + */ +public class WebSocketEventProducerClient implements WsStringMessageListener { + private final String host; + private final int port; + private final int eventCount; + private final boolean xmlEvents; + private final long eventInterval; + private long eventsSentCount = 0; + + WsStringMessageClient client; + + /** + * Instantiates a new web socket event producer client. + * + * @param host the host + * @param port the port + * @param eventCount the event count + * @param xmlEvents the xml events + * @param eventInterval the event interval + * @throws MessagingException the messaging exception + */ + public WebSocketEventProducerClient(final String host, final int port, final int eventCount, + final boolean xmlEvents, final long eventInterval) throws MessagingException { + this.host = host; + this.port = port; + this.eventCount = eventCount; + this.xmlEvents = xmlEvents; + this.eventInterval = eventInterval; + + client = new WsStringMessageClient(host, port); + client.start(this); + + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " + port + + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + } + + /** + * Send events. + */ + public void sendEvents() { + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": sending events on host " + host + + ", port " + port + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + + for (int i = 0; i < eventCount; i++) { + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": waiting " + eventInterval + + " milliseconds before sending next event"); + ThreadUtilities.sleep(eventInterval); + + String eventString = null; + if (xmlEvents) { + eventString = EventGenerator.xmlEvent(); + } else { + eventString = EventGenerator.jsonEvent(); + } + client.sendString(eventString); + eventsSentCount++; + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": host " + host + ", port " + + port + ", sent event " + eventString); + } + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": completed"); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + client.stop(); + System.out.println(WebSocketEventProducerClient.class.getCanonicalName() + ": stopped"); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": host " + host + ", port " + port + + ", received event " + eventString); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 5) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[1]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[2]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + long eventInterval = 0; + try { + eventInterval = Long.parseLong(args[4]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + boolean xmlEvents = false; + if (args[3].equalsIgnoreCase("XML")) { + xmlEvents = true; + } else if (!args[3].equalsIgnoreCase("JSON")) { + System.err.println("usage WebSocketEventProducerClient host port #events XML|JSON eventInterval"); + return; + } + + final WebSocketEventProducerClient client = + new WebSocketEventProducerClient(args[0], port, eventCount, xmlEvents, eventInterval); + + client.sendEvents(); + client.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java new file mode 100644 index 000000000..3e5ff714e --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventProducerServer.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator; + +/** + * The Class WebSocketEventProducerServer. + */ +public class WebSocketEventProducerServer implements WsStringMessageListener { + private final int port; + private final int eventCount; + private final boolean xmlEvents; + private final long eventInterval; + private long eventsSentCount = 0; + + WsStringMessageServer server; + + /** + * Instantiates a new web socket event producer server. + * + * @param port the port + * @param eventCount the event count + * @param xmlEvents the xml events + * @param eventInterval the event interval + * @throws MessagingException the messaging exception + */ + public WebSocketEventProducerServer(final int port, final int eventCount, final boolean xmlEvents, + final long eventInterval) throws MessagingException { + this.port = port; + this.eventCount = eventCount; + this.xmlEvents = xmlEvents; + this.eventInterval = eventInterval; + + server = new WsStringMessageServer(port); + server.start(this); + + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + ", event count " + + eventCount + ", xmlEvents " + xmlEvents); + } + + /** + * Send events. + */ + public void sendEvents() { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": sending events on port " + port + + ", event count " + eventCount + ", xmlEvents " + xmlEvents); + + for (int i = 0; i < eventCount; i++) { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": waiting " + eventInterval + + " milliseconds before sending next event"); + ThreadUtilities.sleep(eventInterval); + + String eventString = null; + if (xmlEvents) { + eventString = EventGenerator.xmlEvent(); + } else { + eventString = EventGenerator.jsonEvent(); + } + server.sendString(eventString); + eventsSentCount++; + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + + ", sent event " + eventString); + } + + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": event sending completed"); + } + + /** + * Gets the events sent count. + * + * @return the events sent count + */ + public long getEventsSentCount() { + return eventsSentCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + server.stop(); + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": stopped"); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": port " + port + + ", received event " + eventString); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 4) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[1]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + long eventInterval = 0; + try { + eventInterval = Long.parseLong(args[3]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON eventInterval"); + e.printStackTrace(); + return; + } + + boolean xmlEvents = false; + if (args[2].equalsIgnoreCase("XML")) { + xmlEvents = true; + } else if (!args[2].equalsIgnoreCase("JSON")) { + System.err.println("usage WebSocketEventProducerServer port #events XML|JSON startDelay eventInterval"); + return; + } + + final WebSocketEventProducerServer server = + new WebSocketEventProducerServer(port, eventCount, xmlEvents, eventInterval); + + server.sendEvents(); + server.shutdown(); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java new file mode 100644 index 000000000..6477a0dc9 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberClient.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageClient; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; + +/** + * The Class WebSocketEventSubscriberClient. + */ +public class WebSocketEventSubscriberClient implements WsStringMessageListener { + private final int port; + private long eventsReceivedCount = 0; + + private final WsStringMessageClient client; + + /** + * Instantiates a new web socket event subscriber client. + * + * @param host the host + * @param port the port + * @throws MessagingException the messaging exception + */ + public WebSocketEventSubscriberClient(final String host, final int port) throws MessagingException { + this.port = port; + + client = new WsStringMessageClient(host, port); + client.start(this); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventSubscriberClient.class.getCanonicalName() + ": port " + port + + ", received event " + eventString); + eventsReceivedCount++; + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + client.stop(); + System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 2) { + System.err.println("usage WebSocketEventSubscriberClient host port"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventSubscriberClient port"); + e.printStackTrace(); + return; + } + + new WebSocketEventSubscriberClient(args[0], port); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java new file mode 100644 index 000000000..92329236f --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/websocket/WebSocketEventSubscriberServer.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.adapt.websocket; + +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageListener; +import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStringMessageServer; + +/** + * The Class WebSocketEventSubscriberServer. + */ +public class WebSocketEventSubscriberServer implements WsStringMessageListener { + private final int port; + private long eventsReceivedCount = 0; + + private final WsStringMessageServer server; + + /** + * Instantiates a new web socket event subscriber server. + * + * @param port the port + * @throws MessagingException the messaging exception + */ + public WebSocketEventSubscriberServer(final int port) throws MessagingException { + this.port = port; + + server = new WsStringMessageServer(port); + server.start(this); + + System.out.println( + WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port + ", waiting for events"); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WSStringMessageListener# + * receiveString(java.lang.String) + */ + @Override + public void receiveString(final String eventString) { + System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": port " + port + + ", received event " + eventString); + eventsReceivedCount++; + } + + /** + * Gets the events received count. + * + * @return the events received count + */ + public long getEventsReceivedCount() { + return eventsReceivedCount; + } + + /** + * Shutdown. + */ + public void shutdown() { + server.stop(); + System.out.println(WebSocketEventSubscriberServer.class.getCanonicalName() + ": stopped"); + } + + /** + * The main method. + * + * @param args the arguments + * @throws MessagingException the messaging exception + */ + public static void main(final String[] args) throws MessagingException { + if (args.length != 1) { + System.err.println("usage WebSocketEventSubscriberClient port"); + return; + } + + int port = 0; + try { + port = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage WebSocketEventSubscriberClient port"); + e.printStackTrace(); + return; + } + + new WebSocketEventSubscriberServer(port); + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java new file mode 100644 index 000000000..757a48302 --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/context/EventAlbumContextTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.context; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; +import org.onap.policy.common.utils.resources.ResourceUtils; + +public class EventAlbumContextTest { + private File tempCommandFile; + private File tempLogFile; + private File tempModelFile; + private String eventContextString; + private String configFile; + private String outputFile; + private String compareFile; + + @Rule + public TemporaryFolder tempTestDir = new TemporaryFolder(); + + @Test + public void testJavaEventAlbumContextTest() throws IOException, ApexException { + tempCommandFile = tempTestDir.newFile("TestPolicyJavaEventContext.apex"); + tempLogFile = tempTestDir.newFile("TestPolicyJavaEventContext.log"); + tempModelFile = tempTestDir.newFile("TestPolicyJavaEventContext.json"); + + eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyJavaEventContext.apex"); + + configFile = "src/test/resources/prodcons/Context_JavaEventAlbum_file2file.json"; + outputFile = "src/test/resources/events/Context_JavaEventAlbum_EventOut.json"; + compareFile = "src/test/resources/events/Context_JavaEventAlbum_EventOutCompare.json"; + + testEventAlbumContextTest(); + } + + @Test + public void testAvroEventAlbumContextTest() throws IOException, ApexException { + tempCommandFile = tempTestDir.newFile("TestPolicyAvroEventContext.apex"); + tempLogFile = tempTestDir.newFile("TestPolicyAvroEventContext.log"); + tempModelFile = tempTestDir.newFile("TestPolicyAvroEventContext.json"); + + eventContextString = ResourceUtils.getResourceAsString("examples/scripts/TestPolicyAvroEventContext.apex"); + + configFile = "src/test/resources/prodcons/Context_AvroEventAlbum_file2file.json"; + outputFile = "src/test/resources/events/Context_AvroEventAlbum_EventOut.json"; + compareFile = "src/test/resources/events/Context_AvroEventAlbum_EventOutCompare.json"; + + testEventAlbumContextTest(); + } + + private void testEventAlbumContextTest() throws IOException, ApexException { + TextFileUtils.putStringAsFile(eventContextString, tempCommandFile); + + final String[] cliArgs = new String[] { "-c", tempCommandFile.getCanonicalPath(), "-l", + tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath() }; + + new ApexCommandLineEditorMain(cliArgs); + + final String[] args = new String[] { "-m", tempModelFile.getAbsolutePath(), "-c", configFile }; + final ApexMain apexMain = new ApexMain(args); + + // The output event will be in this file + final File outputEventFile = new File(outputFile); + String receivedApexOutputString = ""; + for (int tenthsOfSecondsToWait = 100; tenthsOfSecondsToWait > 0; tenthsOfSecondsToWait--) { + if (outputEventFile.exists() && outputEventFile.length() > 0) { + // The output event is in this file + receivedApexOutputString = TextFileUtils.getTextFileAsString(outputEventFile.getCanonicalPath()) + .replaceAll("\\s+", ""); + break; + } + + ThreadUtilities.sleep(100); + } + + // Shut down Apex + apexMain.shutdown(); + + assertTrue("Test failed, the output event file was not created", outputEventFile.exists()); + outputEventFile.delete(); + + assertTrue("Test failed, the output event file was empty", receivedApexOutputString.length() > 0); + + // We compare the output to what we expect to get + final String expectedFileContent = TextFileUtils + .getTextFileAsString(compareFile); + final String outputEventCompareString = expectedFileContent.replaceAll("\\s+", ""); + + assertEquals(outputEventCompareString, receivedApexOutputString); + } + +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java new file mode 100644 index 000000000..a306b536e --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngDepMessagingTest.java @@ -0,0 +1,227 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.engdep; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.deployment.BatchDeployer; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +// CHECKSTYLE:OFF: checkstyle:magicNumber + +/** + * The Class EngDepMessagingTest. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EngDepMessagingTest { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngDepMessagingTest.class); + + private static final long MAX_START_WAIT = 10000; // 10 sec + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineServiceParameters engineServiceParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters, true); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters, true); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineServiceParameters = new EngineServiceParameters(); + engineServiceParameters.setName("EngDepMessagingTest"); + engineServiceParameters.setVersion("0.0.1"); + engineServiceParameters.setDeploymentPort(58820); + engineServiceParameters.setInstanceCount(3); + engineServiceParameters.setId(100); + engineServiceParameters.getEngineParameters().getExecutorParameterMap().put("MVEL", + new MvelExecutorParameters()); + + ParameterService.register(engineServiceParameters); + ParameterService.register(engineServiceParameters.getEngineParameters()); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineServiceParameters); + ParameterService.deregister(engineServiceParameters.getEngineParameters()); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test EngDep messaging. + * + * @throws URISyntaxException the URI syntax exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ + @Test + public void testEngDepMessaging() throws URISyntaxException, IOException, ApexException { + LOGGER.debug("engine<-->deployment messaging test starting . . ."); + + ModelService.clear(); + + final EngineTestServer server = new EngineTestServer(engineServiceParameters); + assertNotNull(server); + + final Thread serverThread = new Thread(server); + serverThread.start(); + final long starttime = System.currentTimeMillis(); + while (server.isStarting() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { + ThreadUtilities.sleep(100); + } + if (server.isStarting()) { + fail("Test server failed to start after " + MAX_START_WAIT + " ms"); + } + + final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + + final BatchDeployer deployer1 = new BatchDeployer("localhost", 58820); + assertNotNull(deployer1); + + deployer1.init(); + deployer1.deployModel(apexPolicyModel, false, false); + deployer1.stopEngines(); + deployer1.startEngines(); + deployer1.close(); + + // Send events + final Date testStartTime = new Date(); + final Map eventDataMap = new HashMap<>(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", (byte) 123); + eventDataMap.put("TestTimestamp", testStartTime.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final ApexEvent event0 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", + "apex", "test"); + event0.putAll(eventDataMap); + server.sendEvent(event0); + + final ApexEvent event1 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", + "apex", "test"); + event1.putAll(eventDataMap); + server.sendEvent(event1); + + // Wait for results + while (server.getTotalActionEventsReceived() < 2) { + ThreadUtilities.sleep(100); + } + ThreadUtilities.sleep(500); + + assertEquals(2, server.getTotalActionEventsReceived()); + + deployer1.init(); + deployer1.stopEngines(); + deployer1.close(); + + // Test re-initialization of model + final BatchDeployer deployer2 = new BatchDeployer("localhost", 58820); + assertNotNull(deployer2); + + deployer2.init(); + deployer2.deployModel(apexPolicyModel, true, true); + deployer2.stopEngines(); + deployer2.startEngines(); + deployer2.close(); + + server.sendEvent(event0); + server.sendEvent(event1); + + // Wait for results + while (server.getTotalActionEventsReceived() < 4) { + ThreadUtilities.sleep(100); + } + ThreadUtilities.sleep(500); + + assertEquals(4, server.getTotalActionEventsReceived()); + + deployer2.init(); + deployer2.stopEngines(); + deployer2.close(); + + server.stopServer(); + LOGGER.debug("engine<-->deployment messaging test finished"); + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + @After + public void tearDown() throws Exception { + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java new file mode 100644 index 000000000..9e6ff67ca --- /dev/null +++ b/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/engdep/EngineTestServer.java @@ -0,0 +1,269 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.uservice.engdep; + +import java.util.Date; + +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.engdep.EngDepMessagingService; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.runtime.ApexEventListener; +import org.onap.policy.apex.service.engine.runtime.EngineService; +import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; +import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class EngineTestServer is a test Apex service used to test the performance of Apex engines. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EngineTestServer implements Runnable, EngineServiceEventInterface { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineTestServer.class); + + private static final int TEST_SERVER_WAIT_TIME = 200; + + // The engine service for sending events to the Apex engines and the EngDEp service for engine + // administration + private EngineService engineService = null; + private EngDepMessagingService messageService = null; + + // The inner class used to receive and process events + private TestApexListener testApexListener = null; + + // Status flags + private boolean starting = true; + private boolean interrupted = false; + + // Parameters for the test + private final EngineServiceParameters parameters; + + // Apex performance statistics + private Date statsStartDate = null; + private long actionEventsReceivedCount = 0; + private long accumulatedExecutionTime = 0; + private long totalActionEventsReceivedCount = 0; + + private ApexEvent lastEventReceived = null; + + /** + * Instantiates a new engine test server to test Apex performance. + * + * @param parameters the parameters + */ + public EngineTestServer(final EngineServiceParameters parameters) { + this.parameters = parameters; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + LOGGER.debug("engine<-->deployment test server starting . . ."); + + // Set the name of the test server thread + Thread.currentThread().setName(EngineTestServer.class.getName()); + + try { + // Create the engine service and set the listener for events emitted by the Apex service + engineService = EngineServiceImpl.create(parameters); + testApexListener = new TestApexListener(); + engineService.registerActionListener("testApexListener", testApexListener); + + // Create the EngDep messaging service and start it + messageService = new EngDepMessagingService(engineService, parameters.getDeploymentPort()); + messageService.start(); + + // Record the start date for statistics + statsStartDate = new Date(); + } catch (final Exception e) { + LOGGER.error("engine<-->deployment test server exception", e); + e.printStackTrace(); + return; + } + LOGGER.debug("engine<-->deployment test server started"); + + starting = false; + + while (!interrupted) { + if (!ThreadUtilities.sleep(TEST_SERVER_WAIT_TIME)) { + interrupted = true; + } + } + } + + /** + * Stop the test server. + */ + public void stopServer() { + LOGGER.debug("engine<-->deployment test server stopping . . ."); + + interrupted = true; + messageService.stop(); + + LOGGER.debug("engine<-->deployment test server stopped"); + } + + /** + * Checks if the test server is interrupted. + * + * @return true, if is interrupted + */ + public boolean isInterrupted() { + return interrupted; + } + + /** + * Gets the total action events received. + * + * @return the total action events received + */ + public long getTotalActionEventsReceived() { + return totalActionEventsReceivedCount; + } + + /** + * Gets the last action events received. + * + * @return the last action event received + */ + public ApexEvent getLastActionEvent() { + return lastEventReceived; + } + + /** + * Gets the Apex statistics and resets them. + * + * @return the statistics + */ + public long[] getAndResetStats() { + // Check if we have statistics + if (statsStartDate == null || actionEventsReceivedCount == 0) { + return null; + } + + // Calculate, save, and reset the statistics + final long[] stats = new long[2]; + synchronized (statsStartDate) { + final long averageExecutionTime = accumulatedExecutionTime / actionEventsReceivedCount; + final long measuringTime = new Date().getTime() - statsStartDate.getTime(); + final long transactionsPerMillisecond = actionEventsReceivedCount / measuringTime; + stats[0] = averageExecutionTime; + stats[1] = transactionsPerMillisecond; + statsStartDate = new Date(); + + actionEventsReceivedCount = 0; + accumulatedExecutionTime = 0; + } + + // Return the statistics + return stats; + } + + /** + * Checks if the test server is starting. + * + * @return true, if the server is starting + */ + public boolean isStarting() { + return starting; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface#sendEvent(org.onap. + * policy.apex.service.engine.event.ApexEvent) + */ + @Override + public void sendEvent(final ApexEvent event) { + // Send the event onto the service being tested + engineService.getEngineServiceEventInterface().sendEvent(event); + } + + /** + * The listener interface for receiving testApex events. The class that is interested in + * processing a testApex event implements this interface, and the object created with that class + * is registered with a component using the component's {@code addTestApexListener} method. When + * the testApex event occurs, that object's appropriate method is invoked. + * + *

This class listens for events from the Apex engine + * + * @see TestApexEvent + */ + private final class TestApexListener implements ApexEventListener { + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy + * .apex.service.engine.event.ApexEvent) + */ + @Override + public synchronized void onApexEvent(final ApexEvent apexEvent) { + LOGGER.debug("result is:" + apexEvent); + + // Check the result event is correct + checkResult(apexEvent); + + // Calculate the performance of the Apex engine service on this policy execution run and + // accumulate the total statistics + final Date testStartTime = new Date((Long) apexEvent.get("TestTimestamp")); + final Date testEndTime = new Date(); + final long testTime = testEndTime.getTime() - testStartTime.getTime(); + LOGGER.debug("policy execution time: " + testTime + "ms"); + synchronized (statsStartDate) { + actionEventsReceivedCount++; + totalActionEventsReceivedCount++; + accumulatedExecutionTime += testTime; + } + lastEventReceived = apexEvent; + } + + /** + * Check that a reply event from the Apex engine is valid. + * + * @param result the result event from the Apex engine + */ + private void checkResult(final ApexEvent result) { + assert result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"); + + // CHECKSTYLE:OFF: checkstyle:magicNumber + assert result.get("TestSlogan").equals("This is a test slogan"); + assert result.get("TestMatchCase").equals(new Byte((byte) 123)); + assert result.get("TestTemperature").equals(34.5445667); + assert ((byte) result.get("TestMatchCaseSelected") >= 0 && (byte) result.get("TestMatchCaseSelected") <= 3); + assert ((byte) result.get("TestEstablishCaseSelected") >= 0 + && (byte) result.get("TestEstablishCaseSelected") <= 3); + assert ((byte) result.get("TestDecideCaseSelected") >= 0 + && (byte) result.get("TestDecideCaseSelected") <= 3); + assert ((byte) result.get("TestActCaseSelected") >= 0 && (byte) result.get("TestActCaseSelected") <= 3); + // CHECKSTYLE:ON: checkstyle:magicNumber + } + } +} diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json b/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json index d85630456..354638a6d 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/policymodels/JMSTestModel.json @@ -342,7 +342,7 @@ "taskLogic": { "key": "TaskLogic", "logicFlavour": "JAVASCRIPT", - "logic": "var outFieldType = Java.type(\"org.onap.policy.apex.apps.uservice.test.adapt.jms.TestPing\");\nvar outValue = new outFieldType();\n\nvar inValue = executor.inFields.get(\"TestPing\");\n\nexecutor.logger.info(inValue);\n\noutValue.setPingTime(inValue.getPingTime());\noutValue.setPongTime(new Date().getTime());\noutValue.setName(inValue.getName() + \"_out\");\n\noutValue.setDescription(\ninValue.getDescription() +\n\". So Romeo would, were he not Romeo call'd,\" +\n\" retain that dear perfection which he owes, without that title.\");\n\nexecutor.logger.info(outValue);\nexecutor.outFields.put(\"TestPing\", outValue)\n\nvar returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);" + "logic": "var outFieldType = Java.type(\"org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestPing\");\nvar outValue = new outFieldType();\n\nvar inValue = executor.inFields.get(\"TestPing\");\n\nexecutor.logger.info(inValue);\n\noutValue.setPingTime(inValue.getPingTime());\noutValue.setPongTime(new Date().getTime());\noutValue.setName(inValue.getName() + \"_out\");\n\noutValue.setDescription(\ninValue.getDescription() +\n\". So Romeo would, were he not Romeo call'd,\" +\n\" retain that dear perfection which he owes, without that title.\");\n\nexecutor.logger.info(outValue);\nexecutor.outFields.put(\"TestPing\", outValue)\n\nvar returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);" } } } @@ -366,7 +366,7 @@ "name": "TestPingIncomingEvent", "version": "0.0.1" }, - "nameSpace": "org.onap.policy.apex.apps.uservice.test.adapt.jms", + "nameSpace": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms", "source": "JMS", "target": "Apex", "parameter": { @@ -396,7 +396,7 @@ "name": "TestPingOutgoingEvent", "version": "0.0.1" }, - "nameSpace": "org.onap.policy.apex.apps.uservice.test.adapt.jms", + "nameSpace": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms", "source": "Apex", "target": "JMS", "parameter": { @@ -446,7 +446,7 @@ "version": "0.0.1" }, "schemaFlavour": "Java", - "schemaDefinition": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestPing" + "schemaDefinition": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestPing" } } ] diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json index 0d55d8a7d..f8479969b 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSJsonEvent.json @@ -20,7 +20,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", @@ -41,7 +41,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json index 228f8ec60..8fea3346b 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/JMS2JMSObjectEvent.json @@ -20,7 +20,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", @@ -40,7 +40,7 @@ "carrierTechnology": "JMS", "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { - "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", + "initialContextFactory": "org.onap.policy.apex.testsuites.integration.uservice.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", "providerURL": "remote://localhost:5445", "securityPrincipal": "guest", diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexBaseBenchMarkTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexBaseBenchMarkTest.java deleted file mode 100644 index 43211bc73..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexBaseBenchMarkTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.policy.apex.service.engine.benchmark; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.ExecutorParameters; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters; -import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; -import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters; -import org.onap.policy.apex.plugins.executor.jruby.JrubyExecutorParameters; -import org.onap.policy.apex.plugins.executor.jython.JythonExecutorParameters; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.runtime.ApexEventListener; -import org.onap.policy.apex.service.engine.runtime.ApexServiceModelUpdateTest; -import org.onap.policy.apex.service.engine.runtime.EngineService; -import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; -import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class ApexBaseBenchMarkTest { - private static final long STOP_TIME_OUT = TimeUnit.SECONDS.toMillis(30); - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceModelUpdateTest.class); - private static final long MAX_START_WAIT = TimeUnit.SECONDS.toMillis(10); - private final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0"); - private final String model; - private final int threads; - private final ApexEventListener listener; - private EngineService service; - private EngineServiceEventInterface engineServiceEventInterface; - - - public ApexBaseBenchMarkTest(final String model, final int threads, final ApexEventListener listener) { - this.model = model; - this.threads = threads; - this.listener = listener; - } - - public void setUp() throws Exception { - final EngineServiceParameters parameters = new EngineServiceParameters(); - parameters.setInstanceCount(threads); - parameters.setName(engineServiceKey.getName()); - parameters.setVersion(engineServiceKey.getVersion()); - parameters.setId(100); - - final EngineParameters engineParameters = parameters.getEngineParameters(); - final Map executorParameterMap = engineParameters.getExecutorParameterMap(); - executorParameterMap.put("MVEL", new MvelExecutorParameters()); - executorParameterMap.put("JAVASCRIPT", new JavascriptExecutorParameters()); - executorParameterMap.put("JYTHON", new JythonExecutorParameters()); - executorParameterMap.put("JAVA", new JavaExecutorParameters()); - executorParameterMap.put("JRUBY", new JrubyExecutorParameters()); - - final ContextParameters contextParameters = engineParameters.getContextParameters(); - final SchemaParameters schemaParameters = contextParameters.getSchemaParameters(); - schemaParameters.getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters()); - schemaParameters.getSchemaHelperParameterMap().put("Java", new JavaSchemaHelperParameters()); - service = EngineServiceImpl.create(parameters); - - service = EngineServiceImpl.create(parameters); - service.registerActionListener("listener", listener); - service.updateModel(parameters.getEngineKey(), model, true); - - LOGGER.info("Starting EngineService ... "); - service.startAll(); - - final long starttime = System.currentTimeMillis(); - while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { - ThreadUtilities.sleep(50); - } - if (!service.isStarted()) { - LOGGER.error("Apex Service {} failed to start after {} ms", service.getKey(), MAX_START_WAIT); - new ApexException("Unable to start engine service "); - } - - engineServiceEventInterface = service.getEngineServiceEventInterface(); - } - - public void sendEvents(final List events) { - for (final ApexEvent event : events) { - engineServiceEventInterface.sendEvent(event); - } - } - - public void sendEvent(final ApexEvent event) { - engineServiceEventInterface.sendEvent(event); - } - - - public EngineService getService() { - return service; - } - - public void destroy() throws Exception { - if (service != null) { - LOGGER.info("Stopping EngineService ... "); - service.stop(); - final long currentTimeInMillSec = System.currentTimeMillis(); - while (!service.isStopped()) { - if (System.currentTimeMillis() - currentTimeInMillSec > STOP_TIME_OUT) { - LOGGER.warn("Timed Out EngineService status: ", service.isStopped()); - break; - } - ThreadUtilities.sleep(500); - } - service = null; - } - } - -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexEngineBenchmark.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexEngineBenchmark.java deleted file mode 100644 index d7a4ef800..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/ApexEngineBenchmark.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.benchmark; - -import static org.junit.Assert.assertEquals; - -import java.util.concurrent.TimeUnit; - -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.utils.Utils; -import org.onap.policy.apex.test.common.model.EvalDomainModelFactory; -import org.python.icu.impl.Assert; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class ApexEngineBenchmark. - */ -public class ApexEngineBenchmark { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEngineBenchmark.class); - - private static final String TARGET = "apex"; - private static final String SOURCE = "test"; - private static final String NAME = "Event0000"; - private static final String VERSION = "0.0.1"; - private static final String PACKAGE = "org.onap.policy.apex.domains.sample.events"; - - private static final long TIME_OUT_IN_MILLISEC = TimeUnit.MINUTES.toMillis(1); - - private String apexECAModelString; - private String apexOODAModelString; - - @Before - public void setUp() throws Exception { - apexECAModelString = Utils.getModelString(new EvalDomainModelFactory().getECAPolicyModel()); - apexOODAModelString = Utils.getModelString(new EvalDomainModelFactory().getOODAPolicyModel()); - } - - @Test - public void testBenchmark_SingletonWorker() throws Exception { - executeTest(apexECAModelString, 100, 1, 20); - executeTest(apexOODAModelString, 100, 1, 20); - } - - @Test - public void testBenchmark_3ThreadWorker() throws Exception { - executeTest(apexECAModelString, 1000, 3, 10); - executeTest(apexOODAModelString, 100, 3, 10); - } - - @Test - public void testBenchmark_10ThreadWorker() throws Exception { - executeTest(apexECAModelString, 2000, 10, 10); - executeTest(apexOODAModelString, 2000, 10, 10); - } - - @Test - public void testBenchmark_50ThreadWorker() throws Exception { - executeTest(apexECAModelString, 3000, 50, 10); - executeTest(apexOODAModelString, 3000, 50, 10); - } - - @Test - public void TestE_AvailableProcessorsThreadWorker() throws Exception { - final int cores = Runtime.getRuntime().availableProcessors(); - executeTest(apexECAModelString, 3000, cores, 10); - executeTest(apexOODAModelString, 3000, cores, 10); - } - - private void executeTest(final String policyModel, final int eventsCount, final int threads, final int loop) - throws Exception { - - LOGGER.info("Running Test with Event count: {}, Instance count: {} and loop: {}", eventsCount, threads, loop); - final TestApexEventListener apexEventListener = new TestApexEventListener(); - - final ApexBaseBenchMarkTest apexBaseBenchMarkTest = - new ApexBaseBenchMarkTest(policyModel, threads, apexEventListener); - - try { - apexBaseBenchMarkTest.setUp(); - for (int i = 0; i < loop; i++) { - sendEvents(apexBaseBenchMarkTest, eventsCount); - final long currentTimeInMillSec = System.currentTimeMillis(); - while (apexEventListener.getEventReceived() < eventsCount) { - if (System.currentTimeMillis() - currentTimeInMillSec > TIME_OUT_IN_MILLISEC) { - LOGGER.warn("Wait timed out ... "); - break; - } - ThreadUtilities.sleep(500); - } - assertEquals(eventsCount, apexEventListener.getEventReceived()); - apexEventListener.printResult(); - apexEventListener.reset(); - } - } catch (final Exception exception) { - Assert.fail(exception); - } finally { - apexBaseBenchMarkTest.destroy(); - LOGGER.info("Finished Running Test with Event count: {}, Instance count: {} and loop: {}", eventsCount, - threads, loop); - } - } - - public void sendEvents(final ApexBaseBenchMarkTest apexBaseBenchMarkTest, final int eventsCount) throws Exception { - for (int eventNum = 0; eventNum < eventsCount; eventNum++) { - final long currentTimeMillis = System.currentTimeMillis(); - final ApexEvent event = new ApexEvent(NAME, VERSION, PACKAGE, SOURCE, TARGET); - event.put("TestTemperature", eventNum); - event.put("FirstEventTimestamp", currentTimeMillis); - event.put("SentTimestamp", currentTimeMillis); - event.put("EventNumber", eventNum); - apexBaseBenchMarkTest.sendEvent(event); - } - } -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/TestApexEventListener.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/TestApexEventListener.java deleted file mode 100644 index b2de8f072..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/benchmark/TestApexEventListener.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.policy.apex.service.engine.benchmark; - -import static org.junit.Assert.assertNull; - -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicLong; - -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.runtime.ApexEventListener; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class TestApexEventListener implements ApexEventListener { - - private static final String SENT_TIMESTAMP = "SentTimestamp"; - private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestApexEventListener.class); - private static final String RECVD_TIMESTAMP = "RecvdTimestamp"; - private Queue queue; - - private final AtomicLong eventReceived = new AtomicLong(); - - public TestApexEventListener() { - this.queue = new ConcurrentLinkedQueue(); - } - - @Override - public void onApexEvent(final ApexEvent apexEvent) { - apexEvent.put(RECVD_TIMESTAMP, System.currentTimeMillis()); - eventReceived.incrementAndGet(); - queue.add(apexEvent); - } - - public void printResult() { - if (!queue.isEmpty()) { - long maxTimeInMilliSeconds = 0; - long minTimeInMilliSeconds = Long.MAX_VALUE; - final long numEvents = queue.size(); - long totalTimeInMilliSeconds = 0; - for (final ApexEvent apexEvent : queue) { - assertNull(apexEvent.getExceptionMessage()); - final Long endTimeInMilliSeconds = (Long) apexEvent.get(RECVD_TIMESTAMP); - final Long startTimeInMilliSeconds = (Long) apexEvent.get(SENT_TIMESTAMP); - final long timeTaken = endTimeInMilliSeconds - startTimeInMilliSeconds; - totalTimeInMilliSeconds += timeTaken; - if (timeTaken > maxTimeInMilliSeconds) { - maxTimeInMilliSeconds = timeTaken; - } - if (timeTaken < minTimeInMilliSeconds) { - minTimeInMilliSeconds = timeTaken; - } - } - LOGGER.info("Average Time Taken to process {} events: {} ms", numEvents, - (totalTimeInMilliSeconds / numEvents)); - LOGGER.info("Max Time Taken: {} ms", maxTimeInMilliSeconds); - LOGGER.info("Min Time Taken: {} ms", minTimeInMilliSeconds); - } - } - - public void reset() { - this.queue = new ConcurrentLinkedQueue(); - eventReceived.set(0);; - } - - public Queue getQueue() { - return queue; - } - - public long getEventReceived() { - return eventReceived.get(); - } - -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/BaseTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/BaseTest.java deleted file mode 100644 index d38107daf..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/BaseTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.policy.apex.service.engine.main; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.concurrent.TimeUnit; - -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.utilities.TextFileUtils; - -public class BaseTest { - protected final static long TIME_OUT_IN_MS = TimeUnit.SECONDS.toMillis(10); - - protected long getFileLength(final String file, final long expectedFileSize) throws IOException { - return getFileLength(10, file, expectedFileSize); - } - - protected long getFileLength(final int loopTime, final String file, final long expectedFileSize) - throws IOException { - long length = 0; - for (int i = 0; i < loopTime; i++) { - final String fileString = TextFileUtils.getTextFileAsString(file).replaceAll("\\s+", ""); - length = fileString.length(); - if (length > 0 && length >= expectedFileSize) { - break; - } - ThreadUtilities.sleep(500); - } - return length; - } - - protected void waitForOutFiles(final File... files) { - final long timeInMillis = System.currentTimeMillis(); - while (!isFilesExist(files)) { - if (System.currentTimeMillis() - timeInMillis > TIME_OUT_IN_MS) { - break; - } - ThreadUtilities.sleep(500); - } - - } - - private void assertFilesExists(final File... files) { - for (final File file : files) { - assertTrue("Test failed, the output " + file + "event file was not created", file.exists()); - } - } - - private void deleteFiles(final File... files) throws IOException { - for (final File file : files) { - Files.deleteIfExists(file.toPath()); - } - } - - private boolean isFilesExist(final File[] files) { - for (final File file : files) { - if (!file.exists()) { - return false; - } - } - return true; - } - - protected File[] toFile(final String[] filesPath) { - if (filesPath == null || filesPath.length == 0) { - return new File[] {}; - } - final File[] files = new File[filesPath.length]; - - for (int index = 0; index < filesPath.length; index++) { - files[index] = new File(filesPath[index]); - } - - return files; - } - - protected void testFileEvents(final String[] args, final String[] expectedFilesPath, final long expectedFileSize) - throws Exception { - final ApexMain apexMain = new ApexMain(args); - - final File[] expectedFiles = toFile(expectedFilesPath); - try { - - waitForOutFiles(expectedFiles); - assertFilesExists(expectedFiles); - - for (final String filePath : expectedFilesPath) { - assertEquals(expectedFileSize, getFileLength(filePath, expectedFileSize)); - } - - apexMain.shutdown(); - - } finally { - deleteFiles(expectedFiles); - } - } - -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMIMO.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMIMO.java deleted file mode 100644 index 714deba30..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMIMO.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.main; - -import org.junit.Test; - -public class TestAsyncEventMIMO extends BaseTest { - - @Test - public void testJsonFileAsyncMIMO() throws Exception { - final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventAsyncMIMO.json"}; - final String[] outFilePaths = {"src/test/resources/events/EventsOutMulti0.json", - "src/test/resources/events/EventsOutMulti1.json", "src/test/resources/events/EventsOutMulti2.json"}; - - testFileEvents(args, outFilePaths, 48956 * 3); - } - -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMISO.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMISO.java deleted file mode 100644 index c5e7f4d9c..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventMISO.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.main; - -import org.junit.Test; - -public class TestAsyncEventMISO extends BaseTest { - - @Test - public void testJsonFileAsyncMISO() throws Exception { - final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventAsyncMISO.json"}; - - testFileEvents(args, new String[] {"src/test/resources/events/EventsOutSingle.json"}, 48956 * 3); - } -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSIMO.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSIMO.java deleted file mode 100644 index 0f570679a..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSIMO.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.main; - -import org.junit.Test; - -public class TestAsyncEventSIMO extends BaseTest { - - @Test - public void testJsonFileAsyncSIMO() throws Exception { - final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventAsyncSIMO.json"}; - final String[] outFilePaths = {"src/test/resources/events/EventsOutMulti0.json", - "src/test/resources/events/EventsOutMulti1.json", "src/test/resources/events/EventsOutMulti2.json"}; - - testFileEvents(args, outFilePaths, 48956); - } - -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSISO.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSISO.java deleted file mode 100644 index 4152e20c9..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestAsyncEventSISO.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.main; - -import org.junit.Test; - -public class TestAsyncEventSISO extends BaseTest { - - @Test - public void testJsonFileAsyncSISO() throws Exception { - final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventAsyncSISO.json"}; - - testFileEvents(args, new String[] {"src/test/resources/events/EventsOutSingle.json"}, 48956); - } -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventMIMO.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventMIMO.java deleted file mode 100644 index ad1a9810a..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventMIMO.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.main; - -import org.junit.Test; - -public class TestSyncEventMIMO extends BaseTest { - - @Test - public void testJsonFileAsyncMIMO() throws Exception { - final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventSyncMIMO.json"}; - final String[] outFilePaths = {"src/test/resources/events/EventsOutMulti0.json", - "src/test/resources/events/EventsOutMulti1.json", "src/test/resources/events/EventsOutMulti2.json"}; - - testFileEvents(args, outFilePaths, 48956 * 3); - } - -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventSISO.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventSISO.java deleted file mode 100644 index 395c2fe0b..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/main/TestSyncEventSISO.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.main; - -import org.junit.Test; - -public class TestSyncEventSISO extends BaseTest { - - @Test - public void testJsonFileAsyncSISO() throws Exception { - final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventSyncSISO.json"}; - - testFileEvents(args, new String[] {"src/test/resources/events/EventsOutSingle.json"}, 48956); - } -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceModelUpdateTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceModelUpdateTest.java deleted file mode 100644 index aa95e73b3..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceModelUpdateTest.java +++ /dev/null @@ -1,363 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.runtime; - -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.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; -import org.onap.policy.apex.service.engine.utils.Utils; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - - -/** - * The Class ApexServiceTest. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexServiceModelUpdateTest { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceModelUpdateTest.class); - - private final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0"); - private final EngineServiceParameters parameters = new EngineServiceParameters(); - private EngineService service = null; - private TestListener listener = null; - private int actionEventsReceived = 0; - - private AxPolicyModel apexSamplePolicyModel = null; - private String apexSampleModelString; - - /** - * Sets up the test by creating an engine and reading in the test policy. - * - * @throws ApexException if something goes wron - * @throws IOException - */ - @Before - public void setUp() throws ApexException, IOException { - // create engine with 3 threads - parameters.setInstanceCount(3); - parameters.setName(engineServiceKey.getName()); - parameters.setVersion(engineServiceKey.getVersion()); - parameters.setId(100); - parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - service = EngineServiceImpl.create(parameters); - - LOGGER.debug("Running TestApexEngine. . ."); - - apexSamplePolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(apexSamplePolicyModel); - - apexSampleModelString = Utils.getModelString(apexSamplePolicyModel); - - // create engine - listener = new TestListener(); - service.registerActionListener("MyListener", listener); - } - - /** - * Tear down the the test infrastructure. - * - * @throws ApexException if there is an error - */ - @After - public void tearDown() throws Exception { - if (service != null) { - service.stop(); - } - service = null; - } - - /** - * Test start with no model. - */ - @Test - public void testNoModelStart() { - try { - service.startAll(); - fail("Engine should not start with no model"); - } catch (final Exception e) { - e.printStackTrace(); - assertEquals("start()<-Machine-1_process-1_engine-1-0:0.0.0,STOPPED, cannot start engine, " - + "engine has not been initialized, its model is not loaded", e.getMessage()); - } - } - - /** - * Test model update with string model without force. - * - * @throws ApexException if there is an error - */ - @Test - public void testModelUpdateStringNewNoForce() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexSampleModelString, false); - service.startAll(); - assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); - } - - /** - * Test model update with string model with force. - * - * @throws ApexException if there is an error - */ - @Test - public void testModelUpdateStringNewForce() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexSampleModelString, true); - service.startAll(); - assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); - } - - /** - * Test model update with a new string model without force. - * - * @throws ApexException if there is an error - */ - @Test - public void testModelUpdateStringNewNewNoForce() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexSampleModelString, false); - service.startAll(); - assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); - - sendEvents(); - - service.updateModel(parameters.getEngineKey(), apexSampleModelString, false); - assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); - - sendEvents(); - } - - /** - * Test incompatible model update with a model object without force. - * - * @throws ApexException if there is an error - */ - @Test - public void testModelUpdateIncoNoForce() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false); - service.startAll(); - assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); - - // Different model name, incompatible - final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); - incoPolicyModel0.getKey().setName("INCOMPATIBLE"); - - try { - service.updateModel(parameters.getEngineKey(), incoPolicyModel0, false); - fail("model update should fail on incompatible model without force being true"); - } catch (final Exception e) { - System.err.println(e.getMessage()); - assertEquals( - "apex model update failed, supplied model with key \"INCOMPATIBLE:0.0.1\" is not a compatible " - + "model update from the existing engine model with key \"SamplePolicyModelMVEL:0.0.1\"", - e.getMessage()); - } - - // Still on old model - sendEvents(); - - // Different major version, incompatible - final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); - incoPolicyModel1.getKey().setVersion("1.0.1"); - - try { - service.updateModel(parameters.getEngineKey(), incoPolicyModel1, false); - fail("model update should fail on incompatible model without force being true"); - } catch (final Exception e) { - System.err.println(e.getMessage()); - e.printStackTrace(); - assertEquals( - "apex model update failed, supplied model with key \"SamplePolicyModelMVEL:1.0.1\" is not a compatible " - + "model update from the existing engine model with key \"SamplePolicyModelMVEL:0.0.1\"", - e.getMessage()); - } - - // Still on old model - sendEvents(); - - // Different minor version, compatible - final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); - coPolicyModel0.getKey().setVersion("0.1.0"); - service.updateModel(parameters.getEngineKey(), coPolicyModel0, false); - - // On new compatible model - sendEvents(); - - // Different patch version, compatible - final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); - coPolicyModel1.getKey().setVersion("0.0.2"); - service.updateModel(parameters.getEngineKey(), coPolicyModel1, false); - - // On new compatible model - sendEvents(); - - } - - /** - * Test incompatible model update with a model object with force. - * - * @throws ApexException if there is an error - */ - @Test - public void testModelUpdateIncoForce() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false); - service.startAll(); - assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); - - // Different model name, incompatible - final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); - incoPolicyModel0.getKey().setName("INCOMPATIBLE"); - service.updateModel(parameters.getEngineKey(), incoPolicyModel0, true); - - // On updated model - sendEvents(); - - // Different major version, incompatible - final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); - incoPolicyModel1.getKey().setVersion("1.0.1"); - service.updateModel(parameters.getEngineKey(), incoPolicyModel1, true); - - // On updated model - sendEvents(); - - // Different minor version, compatible - final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); - coPolicyModel0.getKey().setVersion("0.1.0"); - service.updateModel(parameters.getEngineKey(), coPolicyModel0, true); - - // On new compatible model - sendEvents(); - - // Different patch version, compatible - final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); - coPolicyModel1.getKey().setVersion("0.0.2"); - service.updateModel(parameters.getEngineKey(), coPolicyModel1, true); - - // On new compatible model - sendEvents(); - - } - - /** - * Utility method to send some events into the test engine. - * - * @throws ApexEventException if there is an error - */ - private void sendEvents() throws ApexEventException { - final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface(); - - // Send some events - final Date testStartTime = new Date(); - final Map eventDataMap = new HashMap(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", (byte) 123); - eventDataMap.put("TestTimestamp", testStartTime.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final ApexEvent event = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event.putAll(eventDataMap); - engineServiceEventInterface.sendEvent(event); - - final ApexEvent event2 = - new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event2.putAll(eventDataMap); - engineServiceEventInterface.sendEvent(event2); - - // Wait for results - while (actionEventsReceived < 2) { - ThreadUtilities.sleep(100); - } - ThreadUtilities.sleep(500); - } - - /** - * The listener interface for receiving test events. The class that is interested in processing - * a test event implements this interface, and the object created with that class is registered - * with a component using the component's addTestListener method. When the test - * event occurs, that object's appropriate method is invoked. - * - * @see TestEvent - */ - private final class TestListener implements ApexEventListener { - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy - * .apex.service.engine.event.ApexEvent) - */ - @Override - public synchronized void onApexEvent(final ApexEvent event) { - LOGGER.debug("result 1 is:" + event); - checkResult(event); - actionEventsReceived++; - - final Date testStartTime = new Date((Long) event.get("TestTimestamp")); - final Date testEndTime = new Date(); - - LOGGER.info("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms"); - } - - /** - * Check result. - * - * @param result the result - */ - private void checkResult(final ApexEvent result) { - assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104")); - - assertTrue(result.get("TestSlogan").equals("This is a test slogan")); - assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123))); - assertTrue(result.get("TestTemperature").equals(34.5445667)); - assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0 - && ((byte) result.get("TestMatchCaseSelected") <= 3)); - assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0 - && ((byte) result.get("TestEstablishCaseSelected") <= 3)); - assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0 - && ((byte) result.get("TestDecideCaseSelected") <= 3)); - assertTrue( - ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3)); - } - } -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceTest.java deleted file mode 100644 index c178cd9aa..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/runtime/ApexServiceTest.java +++ /dev/null @@ -1,474 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.engine.runtime; - -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.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; -import org.onap.policy.apex.service.engine.utils.Utils; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; -import org.onap.policy.apex.test.common.model.SampleDomainModelFactory; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class ApexServiceTest. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexServiceTest { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceTest.class); - - private static final long MAX_STOP_WAIT = 5000; // 5 sec - private static final long MAX_START_WAIT = 5000; // 5 sec - private static final long MAX_RECV_WAIT = 5000; // 5 sec - - private static final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0"); - private static final EngineServiceParameters parameters = new EngineServiceParameters(); - private static EngineService service = null; - private static TestListener listener = null; - private static AxPolicyModel apexPolicyModel = null; - private static int actionEventsReceived = 0; - - private static String apexModelString; - - private boolean waitFlag = true; - - /** - * Sets the up. - * - * @throws Exception the exception - */ - @BeforeClass - public static void setUp() throws Exception { - // create engine with 3 threads - parameters.setInstanceCount(3); - parameters.setName(engineServiceKey.getName()); - parameters.setVersion(engineServiceKey.getVersion()); - parameters.setId(100); - parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - service = EngineServiceImpl.create(parameters); - - - LOGGER.debug("Running TestApexEngine. . ."); - - apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); - assertNotNull(apexPolicyModel); - - apexModelString = Utils.getModelString(apexPolicyModel); - - // create engine - listener = new TestListener(); - service.registerActionListener("Listener", listener); - } - - /** - * Update the engine then test the engine with 2 sample events. - * - * @throws ApexException if there is a problem - */ - @Test - public void testExecutionSet1() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexModelString, true); - // Start the service - service.startAll(); - final long starttime = System.currentTimeMillis(); - for (final AxArtifactKey engineKey : service.getEngineKeys()) { - LOGGER.info("{}", service.getStatus(engineKey)); - } - while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStarted()) { - fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); - } - - final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface(); - - // Send some events - final Date testStartTime = new Date(); - final Map eventDataMap = new HashMap(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", (byte) 123); - eventDataMap.put("TestTimestamp", testStartTime.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final ApexEvent event = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event.setExecutionId(System.nanoTime()); - event.putAll(eventDataMap); - engineServiceEventInterface.sendEvent(event); - - final ApexEvent event2 = - new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event2.setExecutionId(System.nanoTime()); - event2.putAll(eventDataMap); - engineServiceEventInterface.sendEvent(event2); - - // Wait for results - final long recvtime = System.currentTimeMillis(); - while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) { - ThreadUtilities.sleep(100); - } - ThreadUtilities.sleep(500); - assertEquals(2, actionEventsReceived); - actionEventsReceived = 0; - - - // Stop all engines on this engine service - final long stoptime = System.currentTimeMillis(); - service.stop(); - while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStopped()) { - fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); - } - } - - /** - * Update the engine then test the engine with 2 sample events. - * - * @throws ApexException if there is a problem - */ - @Test - public void testExecutionSet1Sync() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexModelString, true); - // Start the service - service.startAll(); - final long starttime = System.currentTimeMillis(); - for (final AxArtifactKey engineKey : service.getEngineKeys()) { - LOGGER.info("{}", service.getStatus(engineKey)); - } - while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStarted()) { - fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); - } - - // Send some events - final Date testStartTime = new Date(); - final Map eventDataMap = new HashMap(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", (byte) 123); - eventDataMap.put("TestTimestamp", testStartTime.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final ApexEvent event1 = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event1.putAll(eventDataMap); - event1.setExecutionId(System.nanoTime()); - - final ApexEventListener myEventListener1 = new ApexEventListener() { - @Override - public void onApexEvent(final ApexEvent responseEvent) { - assertNotNull("Synchronous sendEventWait failed", responseEvent); - assertEquals(event1.getExecutionId(), responseEvent.getExecutionId()); - waitFlag = false; - } - }; - - waitFlag = true; - service.registerActionListener("Listener1", myEventListener1); - service.getEngineServiceEventInterface().sendEvent(event1); - - while (waitFlag) { - ThreadUtilities.sleep(100); - } - - final ApexEvent event2 = - new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event2.setExecutionId(System.nanoTime()); - event2.putAll(eventDataMap); - - final ApexEventListener myEventListener2 = new ApexEventListener() { - @Override - public void onApexEvent(final ApexEvent responseEvent) { - assertNotNull("Synchronous sendEventWait failed", responseEvent); - assertEquals(event2.getExecutionId(), responseEvent.getExecutionId()); - assertEquals(2, actionEventsReceived); - waitFlag = false; - } - }; - - waitFlag = true; - service.deregisterActionListener("Listener1"); - service.registerActionListener("Listener2", myEventListener2); - service.getEngineServiceEventInterface().sendEvent(event2); - - while (waitFlag) { - ThreadUtilities.sleep(100); - } - service.deregisterActionListener("Listener2"); - - actionEventsReceived = 0; - - // Stop all engines on this engine service - final long stoptime = System.currentTimeMillis(); - service.stop(); - while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStopped()) { - fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); - } - } - - /** - * Update the engine then test the engine with 2 sample events - again. - * - * @throws ApexException if there is a problem - */ - @Test - public void testExecutionSet2() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexModelString, true); - // Start the service - service.startAll(); - final long starttime = System.currentTimeMillis(); - for (final AxArtifactKey engineKey : service.getEngineKeys()) { - LOGGER.info("{}", service.getStatus(engineKey)); - } - while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStarted()) { - fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); - } - - final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface(); - - // Send some events - final Date testStartTime = new Date(); - final Map eventDataMap = new HashMap(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", (byte) 123); - eventDataMap.put("TestTimestamp", testStartTime.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final ApexEvent event = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event.setExecutionId(System.nanoTime()); - event.putAll(eventDataMap); - engineServiceEventInterface.sendEvent(event); - - final ApexEvent event2 = - new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event2.setExecutionId(System.nanoTime()); - event2.putAll(eventDataMap); - engineServiceEventInterface.sendEvent(event2); - - // Wait for results - final long recvtime = System.currentTimeMillis(); - while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) { - ThreadUtilities.sleep(100); - } - ThreadUtilities.sleep(500); - assertEquals(2, actionEventsReceived); - actionEventsReceived = 0; - - // Stop all engines on this engine service - final long stoptime = System.currentTimeMillis(); - service.stop(); - while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStopped()) { - fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); - } - } - - /** - * Update the engine then test the engine with 2 sample events - again. - * - * @throws ApexException if there is a problem - */ - @Test - public void testExecutionSet2Sync() throws ApexException { - service.updateModel(parameters.getEngineKey(), apexModelString, true); - // Start the service - service.startAll(); - final long starttime = System.currentTimeMillis(); - for (final AxArtifactKey engineKey : service.getEngineKeys()) { - LOGGER.info("{}", service.getStatus(engineKey)); - } - while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStarted()) { - fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); - } - - // Send some events - final Date testStartTime = new Date(); - final Map eventDataMap = new HashMap(); - eventDataMap.put("TestSlogan", "This is a test slogan"); - eventDataMap.put("TestMatchCase", (byte) 123); - eventDataMap.put("TestTimestamp", testStartTime.getTime()); - eventDataMap.put("TestTemperature", 34.5445667); - - final ApexEvent event1 = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event1.putAll(eventDataMap); - - final ApexEventListener myEventListener1 = new ApexEventListener() { - @Override - public void onApexEvent(final ApexEvent responseEvent) { - assertNotNull("Synchronous sendEventWait failed", responseEvent); - assertEquals(event1.getExecutionId(), responseEvent.getExecutionId()); - waitFlag = false; - } - }; - - waitFlag = true; - service.registerActionListener("Listener1", myEventListener1); - service.getEngineServiceEventInterface().sendEvent(event1); - - while (waitFlag) { - ThreadUtilities.sleep(100); - } - - final ApexEvent event2 = - new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event2.putAll(eventDataMap); - - final ApexEventListener myEventListener2 = new ApexEventListener() { - @Override - public void onApexEvent(final ApexEvent responseEvent) { - assertNotNull("Synchronous sendEventWait failed", responseEvent); - assertEquals(event2.getExecutionId(), responseEvent.getExecutionId()); - waitFlag = false; - } - }; - - waitFlag = true; - service.registerActionListener("Listener2", myEventListener2); - service.deregisterActionListener("Listener1"); - service.getEngineServiceEventInterface().sendEvent(event2); - - while (waitFlag) { - ThreadUtilities.sleep(100); - } - - service.deregisterActionListener("Listener2"); - - assertEquals(2, actionEventsReceived); - - actionEventsReceived = 0; - - // Stop all engines on this engine service - final long stoptime = System.currentTimeMillis(); - service.stop(); - while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStopped()) { - fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); - } - } - - /** - * Tear down the the test infrastructure. - * - * @throws ApexException if there is an error - */ - @AfterClass - public static void tearDown() throws Exception { - // Stop all engines on this engine service - final long stoptime = System.currentTimeMillis(); - service.stop(); - while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { - ThreadUtilities.sleep(200); - } - if (!service.isStopped()) { - fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); - } - service = null; - } - - /** - * The listener interface for receiving test events. The class that is interested in processing - * a test event implements this interface, and the object created with that class is registered - * with a component using the component's addTestListener method. When the test - * event occurs, that object's appropriate method is invoked. - * - * @see TestEvent - */ - private static final class TestListener implements ApexEventListener { - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy - * .apex.service.engine.event.ApexEvent) - */ - @Override - public synchronized void onApexEvent(final ApexEvent event) { - LOGGER.debug("result 1 is:" + event); - checkResult(event); - actionEventsReceived++; - - final Date testStartTime = new Date((Long) event.get("TestTimestamp")); - final Date testEndTime = new Date(); - - LOGGER.info("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms"); - } - - /** - * Check result. - * - * @param result the result - */ - private void checkResult(final ApexEvent result) { - assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104")); - - assertTrue(result.get("TestSlogan").equals("This is a test slogan")); - assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123))); - assertTrue(result.get("TestTemperature").equals(34.5445667)); - assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0 - && ((byte) result.get("TestMatchCaseSelected") <= 3)); - assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0 - && ((byte) result.get("TestEstablishCaseSelected") <= 3)); - assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0 - && ((byte) result.get("TestDecideCaseSelected") <= 3)); - assertTrue( - ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3)); - } - } -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/utils/Utils.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/utils/Utils.java deleted file mode 100644 index cfc787d64..000000000 --- a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/service/engine/utils/Utils.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.policy.apex.service.engine.utils; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class Utils { - - private Utils() {} - - public static String getModelString(final AxPolicyModel ecaPolicyModel) throws ApexModelException, IOException { - try (final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream()) { - new ApexModelWriter(AxPolicyModel.class).write(ecaPolicyModel, baOutputStream); - return baOutputStream.toString(); - } - } - -} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexBaseBenchMarkTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexBaseBenchMarkTest.java new file mode 100644 index 000000000..fdefd5583 --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexBaseBenchMarkTest.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.benchmark; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.ExecutorParameters; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters; +import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; +import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters; +import org.onap.policy.apex.plugins.executor.jruby.JrubyExecutorParameters; +import org.onap.policy.apex.plugins.executor.jython.JythonExecutorParameters; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.runtime.ApexEventListener; +import org.onap.policy.apex.service.engine.runtime.EngineService; +import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; +import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.onap.policy.apex.testsuites.performance.benchmark.engine.runtime.ApexServiceModelUpdateTest; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class ApexBaseBenchMarkTest. + */ +public class ApexBaseBenchMarkTest { + private static final long STOP_TIME_OUT = TimeUnit.SECONDS.toMillis(30); + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceModelUpdateTest.class); + private static final long MAX_START_WAIT = TimeUnit.SECONDS.toMillis(10); + private final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0"); + private final String model; + private final int threads; + private final ApexEventListener listener; + private EngineService service; + private EngineServiceEventInterface engineServiceEventInterface; + + + /** + * Instantiates a new apex base bench mark test. + * + * @param model the model + * @param threads the threads + * @param listener the listener + */ + public ApexBaseBenchMarkTest(final String model, final int threads, final ApexEventListener listener) { + this.model = model; + this.threads = threads; + this.listener = listener; + } + + /** + * Sets the up. + * + * @throws Exception the exception + */ + public void setUp() throws Exception { + final EngineServiceParameters parameters = new EngineServiceParameters(); + parameters.setInstanceCount(threads); + parameters.setName(engineServiceKey.getName()); + parameters.setVersion(engineServiceKey.getVersion()); + parameters.setId(100); + + final EngineParameters engineParameters = parameters.getEngineParameters(); + final Map executorParameterMap = engineParameters.getExecutorParameterMap(); + executorParameterMap.put("MVEL", new MvelExecutorParameters()); + executorParameterMap.put("JAVASCRIPT", new JavascriptExecutorParameters()); + executorParameterMap.put("JYTHON", new JythonExecutorParameters()); + executorParameterMap.put("JAVA", new JavaExecutorParameters()); + executorParameterMap.put("JRUBY", new JrubyExecutorParameters()); + + final ContextParameters contextParameters = engineParameters.getContextParameters(); + final SchemaParameters schemaParameters = contextParameters.getSchemaParameters(); + schemaParameters.getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters()); + schemaParameters.getSchemaHelperParameterMap().put("Java", new JavaSchemaHelperParameters()); + service = EngineServiceImpl.create(parameters); + + service = EngineServiceImpl.create(parameters); + service.registerActionListener("listener", listener); + service.updateModel(parameters.getEngineKey(), model, true); + + LOGGER.info("Starting EngineService ... "); + service.startAll(); + + final long starttime = System.currentTimeMillis(); + while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { + ThreadUtilities.sleep(50); + } + if (!service.isStarted()) { + LOGGER.error("Apex Service {} failed to start after {} ms", service.getKey(), MAX_START_WAIT); + new ApexException("Unable to start engine service "); + } + + engineServiceEventInterface = service.getEngineServiceEventInterface(); + } + + /** + * Send events. + * + * @param events the events + */ + public void sendEvents(final List events) { + for (final ApexEvent event : events) { + engineServiceEventInterface.sendEvent(event); + } + } + + /** + * Send event. + * + * @param event the event + */ + public void sendEvent(final ApexEvent event) { + engineServiceEventInterface.sendEvent(event); + } + + + /** + * Gets the service. + * + * @return the service + */ + public EngineService getService() { + return service; + } + + /** + * Destroy. + * + * @throws Exception the exception + */ + public void destroy() throws Exception { + if (service != null) { + LOGGER.info("Stopping EngineService ... "); + service.stop(); + final long currentTimeInMillSec = System.currentTimeMillis(); + while (!service.isStopped()) { + if (System.currentTimeMillis() - currentTimeInMillSec > STOP_TIME_OUT) { + LOGGER.warn("Timed Out EngineService status: ", service.isStopped()); + break; + } + ThreadUtilities.sleep(500); + } + service = null; + } + } + +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexEngineBenchmark.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexEngineBenchmark.java new file mode 100644 index 000000000..fa2a9934c --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/ApexEngineBenchmark.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.benchmark; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.testsuites.integration.common.model.EvalDomainModelFactory; +import org.onap.policy.apex.testsuites.performance.benchmark.engine.utils.Utils; +import org.python.icu.impl.Assert; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class ApexEngineBenchmark. + */ +public class ApexEngineBenchmark { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEngineBenchmark.class); + + private static final String TARGET = "apex"; + private static final String SOURCE = "test"; + private static final String NAME = "Event0000"; + private static final String VERSION = "0.0.1"; + private static final String PACKAGE = "org.onap.policy.apex.domains.sample.events"; + + private static final long TIME_OUT_IN_MILLISEC = TimeUnit.MINUTES.toMillis(1); + + private String apexEcaModelString; + private String apexOodaModelString; + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @Before + public void setUp() throws Exception { + apexEcaModelString = Utils.getModelString(new EvalDomainModelFactory().getEcaPolicyModel()); + apexOodaModelString = Utils.getModelString(new EvalDomainModelFactory().getOodaPolicyModel()); + } + + /** + * Test benchmark singleton worker. + * + * @throws Exception the exception + */ + @Test + public void testBenchmark_SingletonWorker() throws Exception { + executeTest(apexEcaModelString, 100, 1, 20); + executeTest(apexOodaModelString, 100, 1, 20); + } + + /** + * Test benchmark 3 thread worker. + * + * @throws Exception the exception + */ + @Test + public void testBenchmark_3ThreadWorker() throws Exception { + executeTest(apexEcaModelString, 1000, 3, 10); + executeTest(apexOodaModelString, 100, 3, 10); + } + + /** + * Test benchmark 10 thread worker. + * + * @throws Exception the exception + */ + @Test + public void testBenchmark_10ThreadWorker() throws Exception { + executeTest(apexEcaModelString, 2000, 10, 10); + executeTest(apexOodaModelString, 2000, 10, 10); + } + + /** + * Test benchmark 50 thread worker. + * + * @throws Exception the exception + */ + @Test + public void testBenchmark_50ThreadWorker() throws Exception { + executeTest(apexEcaModelString, 3000, 50, 10); + executeTest(apexOodaModelString, 3000, 50, 10); + } + + /** + * Test available processors thread worker. + * + * @throws Exception the exception + */ + @Test + public void testAvailableProcessorsThreadWorker() throws Exception { + final int cores = Runtime.getRuntime().availableProcessors(); + executeTest(apexEcaModelString, 3000, cores, 10); + executeTest(apexOodaModelString, 3000, cores, 10); + } + + /** + * Execute test. + * + * @param policyModel the policy model + * @param eventsCount the events count + * @param threads the threads + * @param loop the loop + * @throws Exception the exception + */ + private void executeTest(final String policyModel, final int eventsCount, final int threads, final int loop) + throws Exception { + + LOGGER.info("Running Test with Event count: {}, Instance count: {} and loop: {}", eventsCount, threads, loop); + final TestApexEventListener apexEventListener = new TestApexEventListener(); + + final ApexBaseBenchMarkTest apexBaseBenchMarkTest = + new ApexBaseBenchMarkTest(policyModel, threads, apexEventListener); + + try { + apexBaseBenchMarkTest.setUp(); + for (int i = 0; i < loop; i++) { + sendEvents(apexBaseBenchMarkTest, eventsCount); + final long currentTimeInMillSec = System.currentTimeMillis(); + while (apexEventListener.getEventReceived() < eventsCount) { + if (System.currentTimeMillis() - currentTimeInMillSec > TIME_OUT_IN_MILLISEC) { + LOGGER.warn("Wait timed out ... "); + break; + } + ThreadUtilities.sleep(500); + } + assertEquals(eventsCount, apexEventListener.getEventReceived()); + apexEventListener.printResult(); + apexEventListener.reset(); + } + } catch (final Exception exception) { + Assert.fail(exception); + } finally { + apexBaseBenchMarkTest.destroy(); + LOGGER.info("Finished Running Test with Event count: {}, Instance count: {} and loop: {}", eventsCount, + threads, loop); + } + } + + /** + * Send events. + * + * @param apexBaseBenchMarkTest the apex base bench mark test + * @param eventsCount the events count + * @throws Exception the exception + */ + public void sendEvents(final ApexBaseBenchMarkTest apexBaseBenchMarkTest, final int eventsCount) throws Exception { + for (int eventNum = 0; eventNum < eventsCount; eventNum++) { + final long currentTimeMillis = System.currentTimeMillis(); + final ApexEvent event = new ApexEvent(NAME, VERSION, PACKAGE, SOURCE, TARGET); + event.put("TestTemperature", eventNum); + event.put("FirstEventTimestamp", currentTimeMillis); + event.put("SentTimestamp", currentTimeMillis); + event.put("EventNumber", eventNum); + apexBaseBenchMarkTest.sendEvent(event); + } + } +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/TestApexEventListener.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/TestApexEventListener.java new file mode 100644 index 000000000..2b6c89de7 --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/benchmark/TestApexEventListener.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.benchmark; + +import static org.junit.Assert.assertNull; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicLong; + +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.runtime.ApexEventListener; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The listener interface for receiving testApexEvent events. + * The class that is interested in processing a testApexEvent + * event implements this interface, and the object created + * with that class is registered with a component using the + * component's addTestApexEventListener method. When + * the testApexEvent event occurs, that object's appropriate + * method is invoked. + * + * @see TestApexEventEvent + */ +public class TestApexEventListener implements ApexEventListener { + + private static final String SENT_TIMESTAMP = "SentTimestamp"; + private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestApexEventListener.class); + private static final String RECVD_TIMESTAMP = "RecvdTimestamp"; + private Queue queue; + + private final AtomicLong eventReceived = new AtomicLong(); + + /** + * Instantiates a new test apex event listener. + */ + public TestApexEventListener() { + this.queue = new ConcurrentLinkedQueue(); + } + + /* (non-Javadoc) + * @see org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEventApexEvent) + */ + @Override + public void onApexEvent(final ApexEvent apexEvent) { + apexEvent.put(RECVD_TIMESTAMP, System.currentTimeMillis()); + eventReceived.incrementAndGet(); + queue.add(apexEvent); + } + + /** + * Prints the result. + */ + public void printResult() { + if (!queue.isEmpty()) { + long maxTimeInMilliSeconds = 0; + long minTimeInMilliSeconds = Long.MAX_VALUE; + final long numEvents = queue.size(); + long totalTimeInMilliSeconds = 0; + for (final ApexEvent apexEvent : queue) { + assertNull(apexEvent.getExceptionMessage()); + final Long endTimeInMilliSeconds = (Long) apexEvent.get(RECVD_TIMESTAMP); + final Long startTimeInMilliSeconds = (Long) apexEvent.get(SENT_TIMESTAMP); + final long timeTaken = endTimeInMilliSeconds - startTimeInMilliSeconds; + totalTimeInMilliSeconds += timeTaken; + if (timeTaken > maxTimeInMilliSeconds) { + maxTimeInMilliSeconds = timeTaken; + } + if (timeTaken < minTimeInMilliSeconds) { + minTimeInMilliSeconds = timeTaken; + } + } + LOGGER.info("Average Time Taken to process {} events: {} ms", numEvents, + (totalTimeInMilliSeconds / numEvents)); + LOGGER.info("Max Time Taken: {} ms", maxTimeInMilliSeconds); + LOGGER.info("Min Time Taken: {} ms", minTimeInMilliSeconds); + } + } + + /** + * Reset. + */ + public void reset() { + this.queue = new ConcurrentLinkedQueue(); + eventReceived.set(0);; + } + + /** + * Gets the queue. + * + * @return the queue + */ + public Queue getQueue() { + return queue; + } + + /** + * Gets the event received. + * + * @return the event received + */ + public long getEventReceived() { + return eventReceived.get(); + } + +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/BaseTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/BaseTest.java new file mode 100644 index 000000000..52bdb056b --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/BaseTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.main; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.concurrent.TimeUnit; + +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.main.ApexMain; + +public class BaseTest { + protected static final long TIME_OUT_IN_MS = TimeUnit.SECONDS.toMillis(10); + + protected long getFileLength(final String file, final long expectedFileSize) throws IOException { + return getFileLength(10, file, expectedFileSize); + } + + protected long getFileLength(final int loopTime, final String file, final long expectedFileSize) + throws IOException { + long length = 0; + for (int i = 0; i < loopTime; i++) { + final String fileString = TextFileUtils.getTextFileAsString(file).replaceAll("\\s+", ""); + length = fileString.length(); + if (length > 0 && length >= expectedFileSize) { + break; + } + ThreadUtilities.sleep(500); + } + return length; + } + + protected void waitForOutFiles(final File... files) { + final long timeInMillis = System.currentTimeMillis(); + while (!isFilesExist(files)) { + if (System.currentTimeMillis() - timeInMillis > TIME_OUT_IN_MS) { + break; + } + ThreadUtilities.sleep(500); + } + + } + + private void assertFilesExists(final File... files) { + for (final File file : files) { + assertTrue("Test failed, the output " + file + "event file was not created", file.exists()); + } + } + + private void deleteFiles(final File... files) throws IOException { + for (final File file : files) { + Files.deleteIfExists(file.toPath()); + } + } + + private boolean isFilesExist(final File[] files) { + for (final File file : files) { + if (!file.exists()) { + return false; + } + } + return true; + } + + protected File[] toFile(final String[] filesPath) { + if (filesPath == null || filesPath.length == 0) { + return new File[] {}; + } + final File[] files = new File[filesPath.length]; + + for (int index = 0; index < filesPath.length; index++) { + files[index] = new File(filesPath[index]); + } + + return files; + } + + protected void testFileEvents(final String[] args, final String[] expectedFilesPath, final long expectedFileSize) + throws Exception { + final ApexMain apexMain = new ApexMain(args); + + final File[] expectedFiles = toFile(expectedFilesPath); + try { + + waitForOutFiles(expectedFiles); + assertFilesExists(expectedFiles); + + for (final String filePath : expectedFilesPath) { + assertEquals(expectedFileSize, getFileLength(filePath, expectedFileSize)); + } + + apexMain.shutdown(); + + } finally { + deleteFiles(expectedFiles); + } + } + +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMimo.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMimo.java new file mode 100644 index 000000000..195840c6d --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMimo.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.main; + +import org.junit.Test; + +public class TestAsyncEventMimo extends BaseTest { + + @Test + public void testJsonFileAsyncMimo() throws Exception { + final String[] args = { + "-c", + "src/test/resources/parameters/File2FileJsonEventAsyncMIMO.json" + }; + + final String[] outFilePaths = { + "src/test/resources/events/EventsOutMulti0.json", + "src/test/resources/events/EventsOutMulti1.json", + "src/test/resources/events/EventsOutMulti2.json" + }; + + testFileEvents(args, outFilePaths, 48956 * 3); + } + +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMiso.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMiso.java new file mode 100644 index 000000000..2e364647b --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventMiso.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.main; + +import org.junit.Test; + +public class TestAsyncEventMiso extends BaseTest { + + @Test + public void testJsonFileAsyncMiso() throws Exception { + final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventAsyncMISO.json"}; + + testFileEvents(args, new String[] {"src/test/resources/events/EventsOutSingle.json"}, 48956 * 3); + } +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSimo.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSimo.java new file mode 100644 index 000000000..0fb191c49 --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSimo.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.main; + +import org.junit.Test; + +public class TestAsyncEventSimo extends BaseTest { + + @Test + public void testJsonFileAsyncSimo() throws Exception { + final String[] args = { + "-c", + "src/test/resources/parameters/File2FileJsonEventAsyncSIMO.json" + }; + + final String[] outFilePaths = { + "src/test/resources/events/EventsOutMulti0.json", + "src/test/resources/events/EventsOutMulti1.json", + "src/test/resources/events/EventsOutMulti2.json" + }; + + testFileEvents(args, outFilePaths, 48956); + } + +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSiso.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSiso.java new file mode 100644 index 000000000..a89e630bc --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestAsyncEventSiso.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.main; + +import org.junit.Test; + +public class TestAsyncEventSiso extends BaseTest { + + @Test + public void testJsonFileAsyncSiso() throws Exception { + final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventAsyncSISO.json"}; + + testFileEvents(args, new String[] {"src/test/resources/events/EventsOutSingle.json"}, 48956); + } +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventMimo.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventMimo.java new file mode 100644 index 000000000..8b35e5dd8 --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventMimo.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.main; + +import org.junit.Test; + +public class TestSyncEventMimo extends BaseTest { + + @Test + public void testJsonFileAsyncMimo() throws Exception { + final String[] args = { + "-c", + "src/test/resources/parameters/File2FileJsonEventSyncMIMO.json" + }; + + final String[] outFilePaths = { + "src/test/resources/events/EventsOutMulti0.json", + "src/test/resources/events/EventsOutMulti1.json", + "src/test/resources/events/EventsOutMulti2.json" + }; + + testFileEvents(args, outFilePaths, 48956 * 3); + } + +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventSiso.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventSiso.java new file mode 100644 index 000000000..891ad7198 --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/main/TestSyncEventSiso.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.main; + +import org.junit.Test; + +public class TestSyncEventSiso extends BaseTest { + + @Test + public void testJsonFileAsyncSiso() throws Exception { + final String[] args = {"-c", "src/test/resources/parameters/File2FileJsonEventSyncSISO.json"}; + + testFileEvents(args, new String[] {"src/test/resources/events/EventsOutSingle.json"}, 48956); + } +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceModelUpdateTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceModelUpdateTest.java new file mode 100644 index 000000000..cf930150e --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceModelUpdateTest.java @@ -0,0 +1,362 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.runtime; + +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.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.runtime.ApexEventListener; +import org.onap.policy.apex.service.engine.runtime.EngineService; +import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; +import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.onap.policy.apex.testsuites.performance.benchmark.engine.utils.Utils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class ApexServiceTest. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexServiceModelUpdateTest { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceModelUpdateTest.class); + + private final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0"); + private final EngineServiceParameters parameters = new EngineServiceParameters(); + private EngineService service = null; + private TestListener listener = null; + private int actionEventsReceived = 0; + + private AxPolicyModel apexSamplePolicyModel = null; + private String apexSampleModelString; + + /** + * Sets up the test by creating an engine and reading in the test policy. + * + * @throws ApexException if something goes wrong + * @throws IOException on IO exceptions + */ + @Before + public void setUp() throws ApexException, IOException { + // create engine with 3 threads + parameters.setInstanceCount(3); + parameters.setName(engineServiceKey.getName()); + parameters.setVersion(engineServiceKey.getVersion()); + parameters.setId(100); + parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + service = EngineServiceImpl.create(parameters); + + LOGGER.debug("Running TestApexEngine. . ."); + + apexSamplePolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(apexSamplePolicyModel); + + apexSampleModelString = Utils.getModelString(apexSamplePolicyModel); + + // create engine + listener = new TestListener(); + service.registerActionListener("MyListener", listener); + } + + /** + * Tear down the the test infrastructure. + * + * @throws ApexException if there is an error + */ + @After + public void tearDown() throws Exception { + if (service != null) { + service.stop(); + } + service = null; + } + + /** + * Test start with no model. + */ + @Test + public void testNoModelStart() { + try { + service.startAll(); + fail("Engine should not start with no model"); + } catch (final Exception e) { + e.printStackTrace(); + assertEquals("start()<-Machine-1_process-1_engine-1-0:0.0.0,STOPPED, cannot start engine, " + + "engine has not been initialized, its model is not loaded", e.getMessage()); + } + } + + /** + * Test model update with string model without force. + * + * @throws ApexException if there is an error + */ + @Test + public void testModelUpdateStringNewNoForce() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexSampleModelString, false); + service.startAll(); + assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); + } + + /** + * Test model update with string model with force. + * + * @throws ApexException if there is an error + */ + @Test + public void testModelUpdateStringNewForce() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexSampleModelString, true); + service.startAll(); + assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); + } + + /** + * Test model update with a new string model without force. + * + * @throws ApexException if there is an error + */ + @Test + public void testModelUpdateStringNewNewNoForce() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexSampleModelString, false); + service.startAll(); + assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); + + sendEvents(); + + service.updateModel(parameters.getEngineKey(), apexSampleModelString, false); + assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); + + sendEvents(); + } + + /** + * Test incompatible model update with a model object without force. + * + * @throws ApexException if there is an error + */ + @Test + public void testModelUpdateIncoNoForce() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false); + service.startAll(); + assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); + + // Different model name, incompatible + final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); + incoPolicyModel0.getKey().setName("INCOMPATIBLE"); + + try { + service.updateModel(parameters.getEngineKey(), incoPolicyModel0, false); + fail("model update should fail on incompatible model without force being true"); + } catch (final Exception e) { + System.err.println(e.getMessage()); + assertEquals("apex model update failed, supplied model with key \"INCOMPATIBLE:0.0.1\" is not a compatible " + + "model update from the existing engine model with key \"SamplePolicyModelMVEL:0.0.1\"", + e.getMessage()); + } + + // Still on old model + sendEvents(); + + // Different major version, incompatible + final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); + incoPolicyModel1.getKey().setVersion("1.0.1"); + + try { + service.updateModel(parameters.getEngineKey(), incoPolicyModel1, false); + fail("model update should fail on incompatible model without force being true"); + } catch (final Exception e) { + System.err.println(e.getMessage()); + e.printStackTrace(); + assertEquals("apex model update failed, supplied model with key \"SamplePolicyModelMVEL:1.0.1\" is not " + + "a compatible model update from the existing engine model with key " + + "\"SamplePolicyModelMVEL:0.0.1\"", e.getMessage()); + } + + // Still on old model + sendEvents(); + + // Different minor version, compatible + final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); + coPolicyModel0.getKey().setVersion("0.1.0"); + service.updateModel(parameters.getEngineKey(), coPolicyModel0, false); + + // On new compatible model + sendEvents(); + + // Different patch version, compatible + final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); + coPolicyModel1.getKey().setVersion("0.0.2"); + service.updateModel(parameters.getEngineKey(), coPolicyModel1, false); + + // On new compatible model + sendEvents(); + + } + + /** + * Test incompatible model update with a model object with force. + * + * @throws ApexException if there is an error + */ + @Test + public void testModelUpdateIncoForce() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false); + service.startAll(); + assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey()); + + // Different model name, incompatible + final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); + incoPolicyModel0.getKey().setName("INCOMPATIBLE"); + service.updateModel(parameters.getEngineKey(), incoPolicyModel0, true); + + // On updated model + sendEvents(); + + // Different major version, incompatible + final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); + incoPolicyModel1.getKey().setVersion("1.0.1"); + service.updateModel(parameters.getEngineKey(), incoPolicyModel1, true); + + // On updated model + sendEvents(); + + // Different minor version, compatible + final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel); + coPolicyModel0.getKey().setVersion("0.1.0"); + service.updateModel(parameters.getEngineKey(), coPolicyModel0, true); + + // On new compatible model + sendEvents(); + + // Different patch version, compatible + final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel); + coPolicyModel1.getKey().setVersion("0.0.2"); + service.updateModel(parameters.getEngineKey(), coPolicyModel1, true); + + // On new compatible model + sendEvents(); + + } + + /** + * Utility method to send some events into the test engine. + * + * @throws ApexEventException if there is an error + */ + private void sendEvents() throws ApexEventException { + final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface(); + + // Send some events + final Date testStartTime = new Date(); + final Map eventDataMap = new HashMap(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", (byte) 123); + eventDataMap.put("TestTimestamp", testStartTime.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", + "test", "apex"); + event.putAll(eventDataMap); + engineServiceEventInterface.sendEvent(event); + + final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", + "test", "apex"); + event2.putAll(eventDataMap); + engineServiceEventInterface.sendEvent(event2); + + // Wait for results + while (actionEventsReceived < 2) { + ThreadUtilities.sleep(100); + } + ThreadUtilities.sleep(500); + } + + /** + * The listener interface for receiving test events. The class that is interested in processing a test event + * implements this interface, and the object created with that class is registered with a component using the + * component's addTestListener method. When the test event occurs, that object's appropriate method is + * invoked. + * + * @see TestEvent + */ + private final class TestListener implements ApexEventListener { + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy + * .apex.service.engine.event.ApexEvent) + */ + @Override + public synchronized void onApexEvent(final ApexEvent event) { + LOGGER.debug("result 1 is:" + event); + checkResult(event); + actionEventsReceived++; + + final Date testStartTime = new Date((Long) event.get("TestTimestamp")); + final Date testEndTime = new Date(); + + LOGGER.info("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms"); + } + + /** + * Check result. + * + * @param result the result + */ + private void checkResult(final ApexEvent result) { + assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104")); + + assertTrue(result.get("TestSlogan").equals("This is a test slogan")); + assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123))); + assertTrue(result.get("TestTemperature").equals(34.5445667)); + assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0 + && ((byte) result.get("TestMatchCaseSelected") <= 3)); + assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0 + && ((byte) result.get("TestEstablishCaseSelected") <= 3)); + assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0 + && ((byte) result.get("TestDecideCaseSelected") <= 3)); + assertTrue(((byte) result.get("TestActCaseSelected")) >= 0 + && ((byte) result.get("TestActCaseSelected") <= 3)); + } + } +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceTest.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceTest.java new file mode 100644 index 000000000..e66d1b791 --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/runtime/ApexServiceTest.java @@ -0,0 +1,477 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.runtime; + +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.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.runtime.ApexEventListener; +import org.onap.policy.apex.service.engine.runtime.EngineService; +import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; +import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory; +import org.onap.policy.apex.testsuites.performance.benchmark.engine.utils.Utils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class ApexServiceTest. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexServiceTest { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceTest.class); + + private static final long MAX_STOP_WAIT = 5000; // 5 sec + private static final long MAX_START_WAIT = 5000; // 5 sec + private static final long MAX_RECV_WAIT = 5000; // 5 sec + + private static final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0"); + private static final EngineServiceParameters parameters = new EngineServiceParameters(); + private static EngineService service = null; + private static TestListener listener = null; + private static AxPolicyModel apexPolicyModel = null; + private static int actionEventsReceived = 0; + + private static String apexModelString; + + private boolean waitFlag = true; + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setUp() throws Exception { + // create engine with 3 threads + parameters.setInstanceCount(3); + parameters.setName(engineServiceKey.getName()); + parameters.setVersion(engineServiceKey.getVersion()); + parameters.setId(100); + parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + service = EngineServiceImpl.create(parameters); + + + LOGGER.debug("Running TestApexEngine. . ."); + + apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL"); + assertNotNull(apexPolicyModel); + + apexModelString = Utils.getModelString(apexPolicyModel); + + // create engine + listener = new TestListener(); + service.registerActionListener("Listener", listener); + } + + /** + * Update the engine then test the engine with 2 sample events. + * + * @throws ApexException if there is a problem + */ + @Test + public void testExecutionSet1() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexModelString, true); + // Start the service + service.startAll(); + final long starttime = System.currentTimeMillis(); + for (final AxArtifactKey engineKey : service.getEngineKeys()) { + LOGGER.info("{}", service.getStatus(engineKey)); + } + while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStarted()) { + fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); + } + + final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface(); + + // Send some events + final Date testStartTime = new Date(); + final Map eventDataMap = new HashMap(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", (byte) 123); + eventDataMap.put("TestTimestamp", testStartTime.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final ApexEvent event = + new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event.setExecutionId(System.nanoTime()); + event.putAll(eventDataMap); + engineServiceEventInterface.sendEvent(event); + + final ApexEvent event2 = + new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event2.setExecutionId(System.nanoTime()); + event2.putAll(eventDataMap); + engineServiceEventInterface.sendEvent(event2); + + // Wait for results + final long recvtime = System.currentTimeMillis(); + while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) { + ThreadUtilities.sleep(100); + } + ThreadUtilities.sleep(500); + assertEquals(2, actionEventsReceived); + actionEventsReceived = 0; + + + // Stop all engines on this engine service + final long stoptime = System.currentTimeMillis(); + service.stop(); + while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStopped()) { + fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); + } + } + + /** + * Update the engine then test the engine with 2 sample events. + * + * @throws ApexException if there is a problem + */ + @Test + public void testExecutionSet1Sync() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexModelString, true); + // Start the service + service.startAll(); + final long starttime = System.currentTimeMillis(); + for (final AxArtifactKey engineKey : service.getEngineKeys()) { + LOGGER.info("{}", service.getStatus(engineKey)); + } + while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStarted()) { + fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); + } + + // Send some events + final Date testStartTime = new Date(); + final Map eventDataMap = new HashMap(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", (byte) 123); + eventDataMap.put("TestTimestamp", testStartTime.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final ApexEvent event1 = + new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event1.putAll(eventDataMap); + event1.setExecutionId(System.nanoTime()); + + final ApexEventListener myEventListener1 = new ApexEventListener() { + @Override + public void onApexEvent(final ApexEvent responseEvent) { + assertNotNull("Synchronous sendEventWait failed", responseEvent); + assertEquals(event1.getExecutionId(), responseEvent.getExecutionId()); + waitFlag = false; + } + }; + + waitFlag = true; + service.registerActionListener("Listener1", myEventListener1); + service.getEngineServiceEventInterface().sendEvent(event1); + + while (waitFlag) { + ThreadUtilities.sleep(100); + } + + final ApexEvent event2 = + new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event2.setExecutionId(System.nanoTime()); + event2.putAll(eventDataMap); + + final ApexEventListener myEventListener2 = new ApexEventListener() { + @Override + public void onApexEvent(final ApexEvent responseEvent) { + assertNotNull("Synchronous sendEventWait failed", responseEvent); + assertEquals(event2.getExecutionId(), responseEvent.getExecutionId()); + assertEquals(2, actionEventsReceived); + waitFlag = false; + } + }; + + waitFlag = true; + service.deregisterActionListener("Listener1"); + service.registerActionListener("Listener2", myEventListener2); + service.getEngineServiceEventInterface().sendEvent(event2); + + while (waitFlag) { + ThreadUtilities.sleep(100); + } + service.deregisterActionListener("Listener2"); + + actionEventsReceived = 0; + + // Stop all engines on this engine service + final long stoptime = System.currentTimeMillis(); + service.stop(); + while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStopped()) { + fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); + } + } + + /** + * Update the engine then test the engine with 2 sample events - again. + * + * @throws ApexException if there is a problem + */ + @Test + public void testExecutionSet2() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexModelString, true); + // Start the service + service.startAll(); + final long starttime = System.currentTimeMillis(); + for (final AxArtifactKey engineKey : service.getEngineKeys()) { + LOGGER.info("{}", service.getStatus(engineKey)); + } + while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStarted()) { + fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); + } + + final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface(); + + // Send some events + final Date testStartTime = new Date(); + final Map eventDataMap = new HashMap(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", (byte) 123); + eventDataMap.put("TestTimestamp", testStartTime.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final ApexEvent event = + new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event.setExecutionId(System.nanoTime()); + event.putAll(eventDataMap); + engineServiceEventInterface.sendEvent(event); + + final ApexEvent event2 = + new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event2.setExecutionId(System.nanoTime()); + event2.putAll(eventDataMap); + engineServiceEventInterface.sendEvent(event2); + + // Wait for results + final long recvtime = System.currentTimeMillis(); + while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) { + ThreadUtilities.sleep(100); + } + ThreadUtilities.sleep(500); + assertEquals(2, actionEventsReceived); + actionEventsReceived = 0; + + // Stop all engines on this engine service + final long stoptime = System.currentTimeMillis(); + service.stop(); + while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStopped()) { + fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); + } + } + + /** + * Update the engine then test the engine with 2 sample events - again. + * + * @throws ApexException if there is a problem + */ + @Test + public void testExecutionSet2Sync() throws ApexException { + service.updateModel(parameters.getEngineKey(), apexModelString, true); + // Start the service + service.startAll(); + final long starttime = System.currentTimeMillis(); + for (final AxArtifactKey engineKey : service.getEngineKeys()) { + LOGGER.info("{}", service.getStatus(engineKey)); + } + while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStarted()) { + fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms"); + } + + // Send some events + final Date testStartTime = new Date(); + final Map eventDataMap = new HashMap(); + eventDataMap.put("TestSlogan", "This is a test slogan"); + eventDataMap.put("TestMatchCase", (byte) 123); + eventDataMap.put("TestTimestamp", testStartTime.getTime()); + eventDataMap.put("TestTemperature", 34.5445667); + + final ApexEvent event1 = + new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event1.putAll(eventDataMap); + + final ApexEventListener myEventListener1 = new ApexEventListener() { + @Override + public void onApexEvent(final ApexEvent responseEvent) { + assertNotNull("Synchronous sendEventWait failed", responseEvent); + assertEquals(event1.getExecutionId(), responseEvent.getExecutionId()); + waitFlag = false; + } + }; + + waitFlag = true; + service.registerActionListener("Listener1", myEventListener1); + service.getEngineServiceEventInterface().sendEvent(event1); + + while (waitFlag) { + ThreadUtilities.sleep(100); + } + + final ApexEvent event2 = + new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + event2.putAll(eventDataMap); + + final ApexEventListener myEventListener2 = new ApexEventListener() { + @Override + public void onApexEvent(final ApexEvent responseEvent) { + assertNotNull("Synchronous sendEventWait failed", responseEvent); + assertEquals(event2.getExecutionId(), responseEvent.getExecutionId()); + waitFlag = false; + } + }; + + waitFlag = true; + service.registerActionListener("Listener2", myEventListener2); + service.deregisterActionListener("Listener1"); + service.getEngineServiceEventInterface().sendEvent(event2); + + while (waitFlag) { + ThreadUtilities.sleep(100); + } + + service.deregisterActionListener("Listener2"); + + assertEquals(2, actionEventsReceived); + + actionEventsReceived = 0; + + // Stop all engines on this engine service + final long stoptime = System.currentTimeMillis(); + service.stop(); + while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStopped()) { + fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); + } + } + + /** + * Tear down the the test infrastructure. + * + * @throws ApexException if there is an error + */ + @AfterClass + public static void tearDown() throws Exception { + // Stop all engines on this engine service + final long stoptime = System.currentTimeMillis(); + service.stop(); + while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) { + ThreadUtilities.sleep(200); + } + if (!service.isStopped()) { + fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms"); + } + service = null; + } + + /** + * The listener interface for receiving test events. The class that is interested in processing + * a test event implements this interface, and the object created with that class is registered + * with a component using the component's addTestListener method. When the test + * event occurs, that object's appropriate method is invoked. + * + * @see TestEvent + */ + private static final class TestListener implements ApexEventListener { + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy + * .apex.service.engine.event.ApexEvent) + */ + @Override + public synchronized void onApexEvent(final ApexEvent event) { + LOGGER.debug("result 1 is:" + event); + checkResult(event); + actionEventsReceived++; + + final Date testStartTime = new Date((Long) event.get("TestTimestamp")); + final Date testEndTime = new Date(); + + LOGGER.info("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms"); + } + + /** + * Check result. + * + * @param result the result + */ + private void checkResult(final ApexEvent result) { + assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104")); + + assertTrue(result.get("TestSlogan").equals("This is a test slogan")); + assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123))); + assertTrue(result.get("TestTemperature").equals(34.5445667)); + assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0 + && ((byte) result.get("TestMatchCaseSelected") <= 3)); + assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0 + && ((byte) result.get("TestEstablishCaseSelected") <= 3)); + assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0 + && ((byte) result.get("TestDecideCaseSelected") <= 3)); + assertTrue( + ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3)); + } + } +} diff --git a/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/utils/Utils.java b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/utils/Utils.java new file mode 100644 index 000000000..0d239a8ef --- /dev/null +++ b/testsuites/performance/performance-benchmark-test/src/test/java/org/onap/policy/apex/testsuites/performance/benchmark/engine/utils/Utils.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.benchmark.engine.utils; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +/** + * The Class Utils. + */ +public class Utils { + + /** + * Instantiates a new utils. + */ + private Utils() {} + + /** + * Gets the model string. + * + * @param ecaPolicyModel the eca policy model + * @return the model string + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public static String getModelString(final AxPolicyModel ecaPolicyModel) throws ApexModelException, IOException { + try (final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream()) { + new ApexModelWriter(AxPolicyModel.class).write(ecaPolicyModel, baOutputStream); + return baOutputStream.toString(); + } + } + +} diff --git a/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/ConcurrentContextMetrics.java b/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/ConcurrentContextMetrics.java deleted file mode 100644 index 3d257f89a..000000000 --- a/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/ConcurrentContextMetrics.java +++ /dev/null @@ -1,322 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.context.metrics; - -import static org.onap.policy.apex.context.parameters.DistributorParameters.DEFAULT_DISTRIBUTOR_PLUGIN_CLASS; -import static org.onap.policy.apex.context.parameters.LockManagerParameters.DEFAULT_LOCK_MANAGER_PLUGIN_CLASS; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Map; -import java.util.Map.Entry; - -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.DistributorParameters; -import org.onap.policy.apex.context.test.concepts.TestContextLongItem; -import org.onap.policy.apex.context.test.locking.ConcurrentContext; -import org.onap.policy.apex.context.test.utils.ConfigrationProvider; -import org.onap.policy.apex.context.test.utils.ConfigrationProviderImpl; -import org.onap.policy.apex.context.test.utils.ZooKeeperServerServiceProvider; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.plugins.context.distribution.hazelcast.HazelcastContextDistributor; -import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanContextDistributor; -import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanDistributorParameters; -import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManager; -import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManagerParameters; -import org.onap.policy.apex.plugins.context.locking.hazelcast.HazelcastLockManager; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class concurrentContextMetrics tests concurrent use of context. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ConcurrentContextMetrics { - private static final int NUM_ARGS = 9; - private static final int ARG_LABEL = 0; - private static final int ARG_JVM_COUNT = 1; - private static final int ARG_THREAD_COUNT = 2; - private static final int ARG_ITERATIONS = 3; - private static final int ARG_ARRAY_SIZE = 4; - private static final int ARG_LOCK_TYPE = 5; - private static final int ARG_ZOOKEEPER_ADDRESS = 6; - private static final int ARG_ZOOKEEPER_PORT = 7; - private static final int ARG_ZOOKEEPER_DIRECTORY = 8; - - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ConcurrentContextMetrics.class); - - private String zookeeperAddress = null; - private final ConfigrationProvider configrationProvider; - private final File zookeeperDirectory; - private final int zookeeperPort; - - /** - * The main method. - * - * @param args the args - * @throws Exception the exception - */ - public static void main(final String[] args) throws Exception { - if (args.length != NUM_ARGS) { - System.err.println("Args: " + Arrays.toString(args)); - System.err.println( - "usage: testLabel jvmCount threadCount threadLoops longArraySize lockType zookeeperAddress zookeeperPort zookeeperDirectory"); - return; - } - - final ConfigrationProvider configrationProvider = - new ConfigrationProviderImpl(args[ARG_LABEL], Integer.valueOf(args[ARG_JVM_COUNT]), - Integer.valueOf(args[ARG_THREAD_COUNT]), Integer.valueOf(args[ARG_ITERATIONS]), - Integer.valueOf(args[ARG_ARRAY_SIZE]), Integer.valueOf(args[ARG_LOCK_TYPE])); - - final ConcurrentContextMetrics concurrentContextMetrics = new ConcurrentContextMetrics(configrationProvider, - args[ARG_ZOOKEEPER_ADDRESS], Integer.valueOf(args[ARG_ZOOKEEPER_PORT]), args[ARG_ZOOKEEPER_DIRECTORY]); - - concurrentContextMetrics.concurrentContextMetricsJVMLocal(); - concurrentContextMetrics.concurrentContextMetricsCurator(); - concurrentContextMetrics.concurrentContextMetricsHazelcast(); - concurrentContextMetrics.concurrentContextMetricsHazelcastMultiJVMHazelcastLock(); - concurrentContextMetrics.concurrentContextMetricsInfinispanMultiJVMHazelcastlock(); - concurrentContextMetrics.concurrentContextMetricsInfinispanMultiJVMCuratorLock(); - concurrentContextMetrics.concurrentContextMetricsHazelcastMultiJVMCuratorLock(); - } - - /** - * The Constructor. - * - * @param configrationProvider - * @param zookeeperAddress - * @param zookeeperPort - * @param zookeeperDirectory - */ - public ConcurrentContextMetrics(final ConfigrationProvider configrationProvider, final String zookeeperAddress, - final int zookeeperPort, final String zookeeperDirectory) { - this.configrationProvider = configrationProvider; - this.zookeeperAddress = zookeeperAddress; - this.zookeeperPort = zookeeperPort; - this.zookeeperDirectory = new File(zookeeperDirectory); - } - - /** - * Concurrent context metrics JVM local. - * - * @throws ApexModelException the apex model exception - * @throws IOException the IO exception - * @throws ApexException the apex exception - */ - private void concurrentContextMetricsJVMLocal() throws ApexModelException, IOException, ApexException { - if (configrationProvider.getJvmCount() != 1) { - return; - } - - LOGGER.debug("Running concurrentContextMetricsJVMLocalVarSet metrics . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); - contextParameters.getLockManagerParameters().setPluginClass(DEFAULT_LOCK_MANAGER_PLUGIN_CLASS); - runConcurrentContextMetrics("JVMLocal"); - - LOGGER.debug("Ran concurrentContextMetricsJVMLocalVarSet metrics"); - } - - /** - * Concurrent context metrics hazelcast. - * - * @throws IOException the IO exception - * @throws ApexException the apex exception - */ - private void concurrentContextMetricsHazelcast() throws IOException, ApexException { - if (configrationProvider.getJvmCount() != 1) { - return; - } - - LOGGER.debug("Running concurrentContextMetricsHazelcast metrics . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); - contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); - runConcurrentContextMetrics("Hazelcast"); - - LOGGER.debug("Ran concurrentContextMetricsHazelcast metrics"); - } - - /** - * Concurrent context metrics curator. - * - * @throws IOException the IO exception - * @throws ApexException the apex exception - */ - private void concurrentContextMetricsCurator() throws IOException, ApexException { - if (configrationProvider.getJvmCount() != 1) { - return; - } - - LOGGER.debug("Running concurrentContextMetricsCurator metrics . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); - - final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); - curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); - contextParameters.setLockManagerParameters(curatorParameters); - curatorParameters.setZookeeperAddress(zookeeperAddress); - - runConcurrentContextMetrics("Curator"); - - LOGGER.debug("Ran concurrentContextMetricsCurator metrics"); - } - - /** - * Concurrent context metrics hazelcast multi JVM hazelcast lock. - * - * @throws IOException the IO exception - * @throws ApexException the apex exception - */ - private void concurrentContextMetricsHazelcastMultiJVMHazelcastLock() throws IOException, ApexException { - LOGGER.debug("Running concurrentContextMetricsHazelcastMultiJVMHazelcastLock metrics . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); - distributorParameters.setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); - contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); - runConcurrentContextMetrics("HazelcastMultiJVMHazelcastLock"); - - LOGGER.debug("Ran concurrentContextMetricsHazelcastMultiJVMHazelcastLock metrics"); - } - - /** - * Concurrent context metrics infinispan multi JVM hazelcastlock. - * - * @throws IOException the IO exception - * @throws ApexException the apex exception - */ - private void concurrentContextMetricsInfinispanMultiJVMHazelcastlock() throws IOException, ApexException { - LOGGER.debug("Running concurrentContextMetricsInfinispanMultiJVMHazelcastlock metrics . . ."); - - final ContextParameters contextParameters = new ContextParameters(); - final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); - distributorParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); - contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); - - final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); - contextParameters.setDistributorParameters(infinispanParameters); - - runConcurrentContextMetrics("InfinispanMultiJVMHazelcastlock"); - - LOGGER.debug("Ran concurrentContextMetricsInfinispanMultiJVMHazelcastlock metrics"); - } - - /** - * Concurrent context metrics infinispan multi JVM curator lock. - * - * @throws IOException the IO exception - * @throws ApexException the apex exception - * @throws InterruptedException - */ - private void concurrentContextMetricsInfinispanMultiJVMCuratorLock() - throws IOException, ApexException, InterruptedException { - - LOGGER.debug("Running concurrentContextMetricsInfinispanMultiJVMCuratorLock metrics . . ."); - - final ZooKeeperServerServiceProvider zooKeeperServerServiceProvider = - new ZooKeeperServerServiceProvider(zookeeperDirectory, zookeeperAddress, zookeeperPort); - try { - zooKeeperServerServiceProvider.startZookeeperServer(); - final ContextParameters contextParameters = new ContextParameters(); - final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); - distributorParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); - - final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); - curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); - contextParameters.setLockManagerParameters(curatorParameters); - curatorParameters.setZookeeperAddress(zookeeperAddress); - - final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); - contextParameters.setDistributorParameters(infinispanParameters); - - runConcurrentContextMetrics("InfinispanMultiJVMCuratorLock"); - } finally { - zooKeeperServerServiceProvider.stopZookeeperServer(); - } - LOGGER.debug("Ran concurrentContextMetricsInfinispanMultiJVMCuratorLock metrics"); - } - - /** - * Concurrent context metrics hazelcast multi JVM curator lock. - * - * @throws IOException the IO exception - * @throws ApexException the apex exception - * @throws InterruptedException - */ - private void concurrentContextMetricsHazelcastMultiJVMCuratorLock() - throws IOException, ApexException, InterruptedException { - LOGGER.debug("Running concurrentContextMetricsHazelcastMultiJVMCuratorLock metrics . . ."); - - final ZooKeeperServerServiceProvider zooKeeperServerServiceProvider = - new ZooKeeperServerServiceProvider(zookeeperDirectory, zookeeperAddress, zookeeperPort); - - try { - zooKeeperServerServiceProvider.startZookeeperServer(); - final ContextParameters contextParameters = new ContextParameters(); - final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); - distributorParameters.setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); - - final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); - curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); - contextParameters.setLockManagerParameters(curatorParameters); - curatorParameters.setZookeeperAddress(zookeeperAddress); - - runConcurrentContextMetrics("HazelcastMultiJVMCuratorLock"); - } finally { - zooKeeperServerServiceProvider.stopZookeeperServer(); - } - LOGGER.debug("Ran concurrentContextMetricsHazelcastMultiJVMCuratorLock metrics"); - } - - /** - * Run concurrent context metrics. - * - * @param testName the test name - * @throws IOException the IO exception - * @throws ApexException the apex exception - */ - private void runConcurrentContextMetrics(final String testName) throws IOException, ApexException { - final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); - - LOGGER.info("Running {} ...", testName); - final Map result = concurrentContext.testConcurrentContext(); - - long total = 0; - for (final Entry entry : result.entrySet()) { - LOGGER.trace("Album key: {}, value: {}", entry.getKey(), entry.getValue()); - total += entry.getValue().getLongValue(); - } - LOGGER.info("Album total value after execution: {}", total); - - LOGGER.info("Completed {} ...", testName); - } - - -} diff --git a/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/package-info.java b/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/package-info.java deleted file mode 100644 index 5e916b6db..000000000 --- a/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/plugins/context/metrics/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Used to get metrics on the performance of Context Album performance for various types of - * distribution and locking mechanisms in APEX. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.policy.apex.plugins.context.metrics; diff --git a/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/ConcurrentContextMetrics.java b/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/ConcurrentContextMetrics.java new file mode 100644 index 000000000..c4e4de480 --- /dev/null +++ b/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/ConcurrentContextMetrics.java @@ -0,0 +1,323 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.context.metrics; + +import static org.onap.policy.apex.context.parameters.DistributorParameters.DEFAULT_DISTRIBUTOR_PLUGIN_CLASS; +import static org.onap.policy.apex.context.parameters.LockManagerParameters.DEFAULT_LOCK_MANAGER_PLUGIN_CLASS; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Map; +import java.util.Map.Entry; + +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.DistributorParameters; +import org.onap.policy.apex.context.test.concepts.TestContextLongItem; +import org.onap.policy.apex.context.test.locking.ConcurrentContext; +import org.onap.policy.apex.context.test.utils.ConfigrationProvider; +import org.onap.policy.apex.context.test.utils.ConfigrationProviderImpl; +import org.onap.policy.apex.context.test.utils.ZooKeeperServerServiceProvider; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.plugins.context.distribution.hazelcast.HazelcastContextDistributor; +import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanContextDistributor; +import org.onap.policy.apex.plugins.context.distribution.infinispan.InfinispanDistributorParameters; +import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManager; +import org.onap.policy.apex.plugins.context.locking.curator.CuratorLockManagerParameters; +import org.onap.policy.apex.plugins.context.locking.hazelcast.HazelcastLockManager; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class concurrentContextMetrics tests concurrent use of context. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ConcurrentContextMetrics { + private static final int NUM_ARGS = 9; + private static final int ARG_LABEL = 0; + private static final int ARG_JVM_COUNT = 1; + private static final int ARG_THREAD_COUNT = 2; + private static final int ARG_ITERATIONS = 3; + private static final int ARG_ARRAY_SIZE = 4; + private static final int ARG_LOCK_TYPE = 5; + private static final int ARG_ZOOKEEPER_ADDRESS = 6; + private static final int ARG_ZOOKEEPER_PORT = 7; + private static final int ARG_ZOOKEEPER_DIRECTORY = 8; + + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ConcurrentContextMetrics.class); + + private String zookeeperAddress = null; + private final ConfigrationProvider configrationProvider; + private final File zookeeperDirectory; + private final int zookeeperPort; + + /** + * The main method. + * + * @param args the args + * @throws Exception the exception + */ + public static void main(final String[] args) throws Exception { + if (args.length != NUM_ARGS) { + String errorMessage = "Args: " + Arrays.toString(args) + + "\nusage: testLabel jvmCount threadCount threadLoops longArraySize lockType " + + "zookeeperAddress zookeeperPort zookeeperDirectory"; + LOGGER.info(errorMessage); + return; + } + + final ConfigrationProvider configrationProvider = new ConfigrationProviderImpl(args[ARG_LABEL], + Integer.valueOf(args[ARG_JVM_COUNT]), Integer.valueOf(args[ARG_THREAD_COUNT]), + Integer.valueOf(args[ARG_ITERATIONS]), Integer.valueOf(args[ARG_ARRAY_SIZE]), + Integer.valueOf(args[ARG_LOCK_TYPE])); + + final ConcurrentContextMetrics concurrentContextMetrics = new ConcurrentContextMetrics(configrationProvider, + args[ARG_ZOOKEEPER_ADDRESS], Integer.valueOf(args[ARG_ZOOKEEPER_PORT]), + args[ARG_ZOOKEEPER_DIRECTORY]); + + concurrentContextMetrics.concurrentContextMetricsJvmLocal(); + concurrentContextMetrics.concurrentContextMetricsCurator(); + concurrentContextMetrics.concurrentContextMetricsHazelcast(); + concurrentContextMetrics.concurrentContextMetricsHazelcastMultiJvmHazelcastLock(); + concurrentContextMetrics.concurrentContextMetricsInfinispanMultiJvmHazelcastlock(); + concurrentContextMetrics.concurrentContextMetricsInfinispanMultiJvmCuratorLock(); + concurrentContextMetrics.concurrentContextMetricsHazelcastMultiJvmCuratorLock(); + } + + /** + * Construct a concurrent context object. + * + * @param configrationProvider Configuration for the context metrics + * @param zookeeperAddress Zookeeper address + * @param zookeeperPort Zookeeper port + * @param zookeeperDirectory Zookeeper directory + */ + public ConcurrentContextMetrics(final ConfigrationProvider configrationProvider, final String zookeeperAddress, + final int zookeeperPort, final String zookeeperDirectory) { + this.configrationProvider = configrationProvider; + this.zookeeperAddress = zookeeperAddress; + this.zookeeperPort = zookeeperPort; + this.zookeeperDirectory = new File(zookeeperDirectory); + } + + /** + * Concurrent context metrics JVM local. + * + * @throws ApexModelException the apex model exception + * @throws IOException the IO exception + * @throws ApexException the apex exception + */ + private void concurrentContextMetricsJvmLocal() throws IOException, ApexException { + if (configrationProvider.getJvmCount() != 1) { + return; + } + + LOGGER.debug("Running concurrentContextMetricsJVMLocalVarSet metrics . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); + contextParameters.getLockManagerParameters().setPluginClass(DEFAULT_LOCK_MANAGER_PLUGIN_CLASS); + runConcurrentContextMetrics("JVMLocal"); + + LOGGER.debug("Ran concurrentContextMetricsJVMLocalVarSet metrics"); + } + + /** + * Concurrent context metrics hazelcast. + * + * @throws IOException the IO exception + * @throws ApexException the apex exception + */ + private void concurrentContextMetricsHazelcast() throws IOException, ApexException { + if (configrationProvider.getJvmCount() != 1) { + return; + } + + LOGGER.debug("Running concurrentContextMetricsHazelcast metrics . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); + contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); + runConcurrentContextMetrics("Hazelcast"); + + LOGGER.debug("Ran concurrentContextMetricsHazelcast metrics"); + } + + /** + * Concurrent context metrics curator. + * + * @throws IOException the IO exception + * @throws ApexException the apex exception + */ + private void concurrentContextMetricsCurator() throws IOException, ApexException { + if (configrationProvider.getJvmCount() != 1) { + return; + } + + LOGGER.debug("Running concurrentContextMetricsCurator metrics . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + contextParameters.getDistributorParameters().setPluginClass(DEFAULT_DISTRIBUTOR_PLUGIN_CLASS); + + final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); + curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); + contextParameters.setLockManagerParameters(curatorParameters); + curatorParameters.setZookeeperAddress(zookeeperAddress); + + runConcurrentContextMetrics("Curator"); + + LOGGER.debug("Ran concurrentContextMetricsCurator metrics"); + } + + /** + * Concurrent context metrics hazelcast multi JVM hazelcast lock. + * + * @throws IOException the IO exception + * @throws ApexException the apex exception + */ + private void concurrentContextMetricsHazelcastMultiJvmHazelcastLock() throws IOException, ApexException { + LOGGER.debug("Running concurrentContextMetricsHazelcastMultiJVMHazelcastLock metrics . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); + distributorParameters.setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); + contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); + runConcurrentContextMetrics("HazelcastMultiJVMHazelcastLock"); + + LOGGER.debug("Ran concurrentContextMetricsHazelcastMultiJVMHazelcastLock metrics"); + } + + /** + * Concurrent context metrics infinispan multi JVM hazelcastlock. + * + * @throws IOException the IO exception + * @throws ApexException the apex exception + */ + private void concurrentContextMetricsInfinispanMultiJvmHazelcastlock() throws IOException, ApexException { + LOGGER.debug("Running concurrentContextMetricsInfinispanMultiJVMHazelcastlock metrics . . ."); + + final ContextParameters contextParameters = new ContextParameters(); + final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); + distributorParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); + contextParameters.getLockManagerParameters().setPluginClass(HazelcastLockManager.class.getCanonicalName()); + + final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); + contextParameters.setDistributorParameters(infinispanParameters); + + runConcurrentContextMetrics("InfinispanMultiJVMHazelcastlock"); + + LOGGER.debug("Ran concurrentContextMetricsInfinispanMultiJVMHazelcastlock metrics"); + } + + /** + * Concurrent context metrics infinispan multi JVM curator lock. + * + * @throws IOException the IO exception + * @throws ApexException the apex exception + * @throws InterruptedException on interrupts + */ + private void concurrentContextMetricsInfinispanMultiJvmCuratorLock() + throws IOException, ApexException, InterruptedException { + + LOGGER.debug("Running concurrentContextMetricsInfinispanMultiJVMCuratorLock metrics . . ."); + + final ZooKeeperServerServiceProvider zooKeeperServerServiceProvider = new ZooKeeperServerServiceProvider( + zookeeperDirectory, zookeeperAddress, zookeeperPort); + try { + zooKeeperServerServiceProvider.startZookeeperServer(); + final ContextParameters contextParameters = new ContextParameters(); + final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); + distributorParameters.setPluginClass(InfinispanContextDistributor.class.getCanonicalName()); + + final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); + curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); + contextParameters.setLockManagerParameters(curatorParameters); + curatorParameters.setZookeeperAddress(zookeeperAddress); + + final InfinispanDistributorParameters infinispanParameters = new InfinispanDistributorParameters(); + contextParameters.setDistributorParameters(infinispanParameters); + + runConcurrentContextMetrics("InfinispanMultiJVMCuratorLock"); + } finally { + zooKeeperServerServiceProvider.stopZookeeperServer(); + } + LOGGER.debug("Ran concurrentContextMetricsInfinispanMultiJVMCuratorLock metrics"); + } + + /** + * Concurrent context metrics hazelcast multi JVM curator lock. + * + * @throws IOException the IO exception + * @throws ApexException the apex exception + * @throws InterruptedException on interrupts + */ + private void concurrentContextMetricsHazelcastMultiJvmCuratorLock() + throws IOException, ApexException, InterruptedException { + LOGGER.debug("Running concurrentContextMetricsHazelcastMultiJVMCuratorLock metrics . . ."); + + final ZooKeeperServerServiceProvider zooKeeperServerServiceProvider = new ZooKeeperServerServiceProvider( + zookeeperDirectory, zookeeperAddress, zookeeperPort); + + try { + zooKeeperServerServiceProvider.startZookeeperServer(); + final ContextParameters contextParameters = new ContextParameters(); + final DistributorParameters distributorParameters = contextParameters.getDistributorParameters(); + distributorParameters.setPluginClass(HazelcastContextDistributor.class.getCanonicalName()); + + final CuratorLockManagerParameters curatorParameters = new CuratorLockManagerParameters(); + curatorParameters.setPluginClass(CuratorLockManager.class.getCanonicalName()); + contextParameters.setLockManagerParameters(curatorParameters); + curatorParameters.setZookeeperAddress(zookeeperAddress); + + runConcurrentContextMetrics("HazelcastMultiJVMCuratorLock"); + } finally { + zooKeeperServerServiceProvider.stopZookeeperServer(); + } + LOGGER.debug("Ran concurrentContextMetricsHazelcastMultiJVMCuratorLock metrics"); + } + + /** + * Run concurrent context metrics. + * + * @param testName the test name + * @throws IOException the IO exception + * @throws ApexException the apex exception + */ + private void runConcurrentContextMetrics(final String testName) throws IOException, ApexException { + final ConcurrentContext concurrentContext = new ConcurrentContext(configrationProvider); + + LOGGER.info("Running {} ...", testName); + final Map result = concurrentContext.testConcurrentContext(); + + long total = 0; + for (final Entry entry : result.entrySet()) { + LOGGER.trace("Album key: {}, value: {}", entry.getKey(), entry.getValue()); + total += entry.getValue().getLongValue(); + } + LOGGER.info("Album total value after execution: {}", total); + + LOGGER.info("Completed {} ...", testName); + } + +} diff --git a/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/package-info.java b/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/package-info.java new file mode 100644 index 000000000..9bb84d76b --- /dev/null +++ b/testsuites/performance/performance-context-metrics/src/main/java/org/onap/policy/apex/testsuites/performance/context/metrics/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Used to get metrics on the performance of Context Album performance for various types of + * distribution and locking mechanisms in APEX. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +package org.onap.policy.apex.testsuites.performance.context.metrics; diff --git a/testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/plugins/context/metrics/TestMetrics.java b/testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/plugins/context/metrics/TestMetrics.java deleted file mode 100644 index 04b756417..000000000 --- a/testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/plugins/context/metrics/TestMetrics.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.plugins.context.metrics; - -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.TreeSet; - -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.onap.policy.apex.context.test.utils.NetworkUtils; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class TestMetrics { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestMetrics.class); - private static final String HAZELCAST_CONFIG = "hazelcast.config"; - - private static final String JAVA_NET_PREFER_IPV4_STACK = "java.net.preferIPv4Stack"; - private static final String HAZELCAST_XML_FILE = "src/test/resources/hazelcast/hazelcast.xml"; - - @Rule - public final TemporaryFolder folder = new TemporaryFolder(); - - @BeforeClass - public static void configure() throws Exception { - System.setProperty(JAVA_NET_PREFER_IPV4_STACK, "true"); - final String hazelCastfileLocation = ResourceUtils.getFilePath4Resource(HAZELCAST_XML_FILE); - System.setProperty(HAZELCAST_CONFIG, hazelCastfileLocation); - - final TreeSet ipAddressSet = NetworkUtils.getIPv4NonLoopAddresses(); - - if (ipAddressSet.size() == 0) { - throw new Exception("cound not find real IP address for test"); - } - LOGGER.info("For Infinispan, setting jgroups.tcp.address to: {}", ipAddressSet.first()); - System.setProperty("jgroups.tcp.address", ipAddressSet.first()); - - } - - @Test - public void getSingleJVMMetrics() throws IOException { - final File zookeeperDirectory = folder.newFolder("zookeeperDirectory"); - final String[] args = {"singleJVMTestNL", "1", "32", "1000", "65536", "0", "localhost", "62181", - zookeeperDirectory.getAbsolutePath()}; - - LOGGER.info("Starting with args: {}", Arrays.toString(args)); - try { - ConcurrentContextMetrics.main(args); - } catch (final Exception exception) { - LOGGER.error("Unexpected error", exception); - fail("Metrics test failed"); - } - } -} diff --git a/testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/testsuites/performance/context/metrics/TestMetrics.java b/testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/testsuites/performance/context/metrics/TestMetrics.java new file mode 100644 index 000000000..6414fa81a --- /dev/null +++ b/testsuites/performance/performance-context-metrics/src/test/java/org/onap/policy/apex/testsuites/performance/context/metrics/TestMetrics.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.performance.context.metrics; + +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.TreeSet; + +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.onap.policy.apex.context.test.utils.NetworkUtils; +import org.onap.policy.apex.testsuites.performance.context.metrics.ConcurrentContextMetrics; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestMetrics. + */ +public class TestMetrics { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestMetrics.class); + private static final String HAZELCAST_CONFIG = "hazelcast.config"; + + private static final String JAVA_NET_PREFER_IPV4_STACK = "java.net.preferIPv4Stack"; + private static final String HAZELCAST_XML_FILE = "src/test/resources/hazelcast/hazelcast.xml"; + + @Rule + public final TemporaryFolder folder = new TemporaryFolder(); + + /** + * Configure. + * + * @throws Exception the exception + */ + @BeforeClass + public static void configure() throws Exception { + System.setProperty(JAVA_NET_PREFER_IPV4_STACK, "true"); + final String hazelCastfileLocation = ResourceUtils.getFilePath4Resource(HAZELCAST_XML_FILE); + System.setProperty(HAZELCAST_CONFIG, hazelCastfileLocation); + + final TreeSet ipAddressSet = NetworkUtils.getIPv4NonLoopAddresses(); + + if (ipAddressSet.size() == 0) { + throw new Exception("cound not find real IP address for test"); + } + LOGGER.info("For Infinispan, setting jgroups.tcp.address to: {}", ipAddressSet.first()); + System.setProperty("jgroups.tcp.address", ipAddressSet.first()); + + } + + /** + * Gets the single jvm metrics. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void getSingleJvmMetrics() throws IOException { + final File zookeeperDirectory = folder.newFolder("zookeeperDirectory"); + final String[] args = {"singleJVMTestNL", "1", "32", "1000", "65536", "0", "localhost", "62181", + zookeeperDirectory.getAbsolutePath()}; + + LOGGER.info("Starting with args: {}", Arrays.toString(args)); + try { + ConcurrentContextMetrics.main(args); + } catch (final Exception exception) { + LOGGER.error("Unexpected error", exception); + fail("Metrics test failed"); + } + } +} diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/KeyInfoGetter.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/KeyInfoGetter.java index f7dfe8456..73bb1269d 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/KeyInfoGetter.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/KeyInfoGetter.java @@ -116,7 +116,7 @@ public class KeyInfoGetter { * @param key the key to process * @return local name of the parent, null if key was null */ - public String getPLName(final AxReferenceKey key) { + public String getPlName(final AxReferenceKey key) { if (key == null) { return null; } @@ -129,7 +129,7 @@ public class KeyInfoGetter { * @param key the key to extract version from * @return UUID of the key, null if key was null */ - public String getUUID(final AxArtifactKey key) { + public String getUuid(final AxArtifactKey key) { final AxKeyInfo ki = model.getKeyInformation().get(key); if (ki == null || ki.getUuid() == null) { return null; @@ -148,6 +148,6 @@ public class KeyInfoGetter { if (ki == null || ki.getDescription() == null) { return null; } - return ki.getDescription().toString(); + return ki.getDescription(); } } diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/SchemaUtils.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/SchemaUtils.java index 545d15eeb..14f84bb44 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/SchemaUtils.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/SchemaUtils.java @@ -129,11 +129,6 @@ public final class SchemaUtils { + " of type " + parameter.getSchema().getId() + " using Schema type " + schemaname, e); } if (alreadyseen != null) { - // logger.warn("parameter "+ parameter.getKey().getLocalName() + " of type " + parameter.getSchema().getID() - // + " tries to redfine AVRO type - // "+schemaname+", but it was previously defined. This parameter will use the previously defined version - // because AVRO does not support redefinition - // of types that have already been defined"); parameterSchema = alreadyseen; } diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java index 88ada24f6..e6002208c 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java @@ -55,6 +55,8 @@ import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter; import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic; import org.onap.policy.apex.tools.common.OutputFile; import org.onap.policy.apex.tools.model.generator.KeyInfoGetter; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; import org.stringtemplate.v4.ST; /** @@ -63,6 +65,8 @@ import org.stringtemplate.v4.ST; * @author Sven van der Meer (sven.van.der.meer@ericsson.com) */ public class Model2Cli { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2Cli.class); /** Application name, used as prompt. */ private final String appName; @@ -111,7 +115,8 @@ public class Model2Cli { final ApexApiResult result = model.loadFromFile(modelFile); if (result.isNok()) { - System.err.println(appName + ": " + result.getMessage()); + String message = appName + ": " + result.getMessage(); + LOGGER.error(message); return -1; } @@ -122,7 +127,8 @@ public class Model2Cli { final AxValidationResult val = new AxValidationResult(); policyModel.validate(val); if (!val.isOk()) { - System.err.println("Cannot translate the model. The model is not valid: \n" + val.toString()); + String message = "Cannot translate the model. The model is not valid: \n" + val.toString(); + LOGGER.error(message); return -1; } } @@ -132,13 +138,13 @@ public class Model2Cli { // Order is important. 0: model, 1: context schemas, 2: tasks, 3: events, 4: ContextAlbums, 5: Policies // 0: model final AxArtifactKey pmkey = policyModel.getKey(); - codeGen.addModelParams(kig.getName(pmkey), kig.getVersion(pmkey), kig.getUUID(pmkey), kig.getDesc(pmkey)); + codeGen.addModelParams(kig.getName(pmkey), kig.getVersion(pmkey), kig.getUuid(pmkey), kig.getDesc(pmkey)); // 1: Context Schemas for (final AxContextSchema s : policyModel.getSchemas().getSchemasMap().values()) { final AxArtifactKey key = s.getKey(); - codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUUID(key), kig.getDesc(key), + codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), s.getSchemaFlavour(), s.getSchema()); } @@ -151,7 +157,7 @@ public class Model2Cli { final List parameters = getParametersForTask(codeGen, t); final List contextRefs = getCtxtRefsForTask(codeGen, t); - codeGen.addTaskDeclaration(kig.getName(key), kig.getVersion(key), kig.getUUID(key), kig.getDesc(key), + codeGen.addTaskDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), infields, outfields, logic, parameters, contextRefs); } @@ -160,7 +166,7 @@ public class Model2Cli { final AxArtifactKey key = e.getKey(); final List fields = getParametersForEvent(codeGen, e); - codeGen.addEventDeclaration(kig.getName(key), kig.getVersion(key), kig.getUUID(key), kig.getDesc(key), + codeGen.addEventDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), e.getNameSpace(), e.getSource(), e.getTarget(), fields); } @@ -168,7 +174,7 @@ public class Model2Cli { for (final AxContextAlbum a : policyModel.getAlbums().getAlbumsMap().values()) { final AxArtifactKey key = a.getKey(); - codeGen.addContextAlbumDeclaration(kig.getName(key), kig.getVersion(key), kig.getUUID(key), + codeGen.addContextAlbumDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), a.getScope(), a.isWritable(), kig.getName(a.getItemSchema()), kig.getVersion(a.getItemSchema())); } @@ -177,26 +183,27 @@ public class Model2Cli { for (final AxPolicy p : policyModel.getPolicies().getPolicyMap().values()) { final AxArtifactKey key = p.getKey(); final List states = getStatesForPolicy(codeGen, p); - codeGen.addPolicyDefinition(kig.getName(key), kig.getVersion(key), kig.getUUID(key), kig.getDesc(key), + codeGen.addPolicyDefinition(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), p.getTemplate(), p.getFirstState(), states); } final String out = codeGen.getModel().render(); if (outFile != null) { + String message = "Error writing output to file " + outFile; try { final Writer w = outFile.toWriter(); if (w == null) { - System.err.println("Error writing output to file " + outFile); + LOGGER.error(message); return -1; } w.write(out); w.close(); } catch (final IOException e) { - System.err.println("Error writing output to file " + outFile + ": " + e.getMessage()); + LOGGER.error(message, e); return -1; } } else { - System.err.println(out); + LOGGER.error(out); } return 0; } @@ -275,10 +282,7 @@ public class Model2Cli { final AxArtifactKey tkey = task.getKey(); final AxTaskLogic tl = task.getTaskLogic(); - final ST val = - cg.createTaskDefLogic(kig.getName(tkey), kig.getVersion(tkey), tl.getLogicFlavour(), tl.getLogic()); - - return val; + return cg.createTaskDefLogic(kig.getName(tkey), kig.getVersion(tkey), tl.getLogicFlavour(), tl.getLogic()); } /** @@ -338,7 +342,7 @@ public class Model2Cli { final List outputs = getStateOutputsForState(cg, st); final List finalizerLogics = getFinalizersForState(cg, st); final List tasks = getTaskRefsForState(cg, st); - final List tsLogic = getTSLForState(cg, st); + final List tsLogic = getTslForState(cg, st); final List ctxRefs = getCtxtRefsForState(cg, st); final ST val = cg.createPolicyStateDef(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey), @@ -400,7 +404,7 @@ public class Model2Cli { * @param st the state * @return the TSL for state (if any) in a list */ - private List getTSLForState(final CodeGeneratorCliEditor cg, final AxState st) { + private List getTslForState(final CodeGeneratorCliEditor cg, final AxState st) { final AxReferenceKey skey = st.getKey(); if (st.checkSetTaskSelectionLogic()) { final AxTaskSelectionLogic tsl = st.getTaskSelectionLogic(); diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java index 0bc9a27f8..6acbbbc02 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java @@ -41,6 +41,8 @@ import org.onap.policy.apex.model.policymodel.concepts.AxState; import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput; import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters; import org.onap.policy.apex.tools.model.generator.SchemaUtils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STGroupFile; @@ -51,6 +53,14 @@ import org.stringtemplate.v4.STGroupFile; * @author Sven van der Meer (sven.van.der.meer@ericsson.com) */ public class Model2JsonEventSchema { + // Logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2JsonEventSchema.class); + + // Recurring string constants + private static final String TARGET = "target"; + private static final String SOURCE = "source"; + private static final String VERSION = "version"; + private static final String NAME_SPACE = "nameSpace"; /** Application name, used as prompt. */ private final String appName; @@ -150,7 +160,8 @@ public class Model2JsonEventSchema { final ApexApiResult result = model.loadFromFile(modelFile); if (result.isNok()) { - System.err.println(appName + ": " + result.getMessage()); + String message = appName + ": " + result.getMessage(); + LOGGER.error(message); return -1; } @@ -200,7 +211,7 @@ public class Model2JsonEventSchema { } break; default: - System.err.println(appName + ": unknown type <" + type + ">, cannot proceed"); + LOGGER.error("{}: unknown type <{}>, cannot proceed", appName, type); return -1; } @@ -215,20 +226,20 @@ public class Model2JsonEventSchema { for (final AxEvent event : events) { final ST stEvent = stg.getInstanceOf("event"); stEvent.add("name", event.getKey().getName()); - stEvent.add("nameSpace", event.getNameSpace()); - stEvent.add("version", event.getKey().getVersion()); - stEvent.add("source", event.getSource()); - stEvent.add("target", event.getTarget()); + stEvent.add(NAME_SPACE, event.getNameSpace()); + stEvent.add(VERSION, event.getKey().getVersion()); + stEvent.add(SOURCE, event.getSource()); + stEvent.add(TARGET, event.getTarget()); final Schema avro = SchemaUtils.getEventSchema(event); for (final Field field : avro.getFields()) { // filter magic names switch (field.name()) { case "name": - case "nameSpace": - case "version": - case "source": - case "target": + case NAME_SPACE: + case VERSION: + case SOURCE: + case TARGET: break; default: stEvent.add("fields", this.setField(field, stg)); @@ -236,7 +247,8 @@ public class Model2JsonEventSchema { } stEvents.add("event", stEvent); } - System.err.println(stEvents.render()); + String renderMessage = stEvents.render(); + LOGGER.error(renderMessage); return 0; } @@ -251,10 +263,10 @@ public class Model2JsonEventSchema { final ST st = stg.getInstanceOf("field"); switch (field.name()) { case "name": - case "nameSpace": - case "version": - case "source": - case "target": + case NAME_SPACE: + case VERSION: + case SOURCE: + case TARGET: break; default: st.add("name", field.name()); diff --git a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java index 810c74da5..bb38a37a0 100644 --- a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java +++ b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java @@ -112,7 +112,7 @@ public class SimpleConsole extends WebSocketClient { * @throws NotYetConnectedException if not connected to server when sending events * @throws IOException on an IO problem on standard in */ - public void runClient() throws NotYetConnectedException, IOException { + public void runClient() throws IOException { final Thread thread = new Thread() { @Override public void run() { -- cgit 1.2.3-korg