From 4cfa2e2d98f6877d54da304ef17f096284430908 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Thu, 13 Sep 2018 15:25:32 +0100 Subject: Sonar/Checkstyle in service/plugins Sonar and Checkstyle changes in plugins and services, and knock on changes Issue-ID: POLICY-1034 Change-Id: Iff7df74e54fce2c661dcc2fae75ae93d4cacfe5b Signed-off-by: liamfallon --- .../policy/apex/auth/clicodegen/CGCliEditor.java | 570 ----------------- .../auth/clicodegen/CodeGeneratorCliEditor.java | 570 +++++++++++++++++ .../apex/auth/clicodegen/TestGeneration.java | 138 ++++ .../onap/policy/apex/auth/clicodegen/TestSTG.java | 138 ---- .../apex/auth/clieditor/ApexCLIEditorMain.java | 195 ------ .../auth/clieditor/ApexCommandLineEditorMain.java | 198 ++++++ .../apex/auth/clieditor/ApexModelHandler.java | 60 +- .../policy/apex/auth/clieditor/CLIArgument.java | 144 ----- .../apex/auth/clieditor/CLIArgumentValue.java | 91 --- .../policy/apex/auth/clieditor/CLICommand.java | 240 ------- .../policy/apex/auth/clieditor/CLICommands.java | 42 -- .../policy/apex/auth/clieditor/CLIEditorLoop.java | 543 ---------------- .../policy/apex/auth/clieditor/CLIException.java | 49 -- .../policy/apex/auth/clieditor/CLILineParser.java | 323 ---------- .../apex/auth/clieditor/CLIParameterParser.java | 159 ----- .../policy/apex/auth/clieditor/CLIParameters.java | 573 ----------------- .../apex/auth/clieditor/CommandLineArgument.java | 144 +++++ .../auth/clieditor/CommandLineArgumentValue.java | 91 +++ .../apex/auth/clieditor/CommandLineCommand.java | 240 +++++++ .../apex/auth/clieditor/CommandLineCommands.java | 42 ++ .../apex/auth/clieditor/CommandLineEditorLoop.java | 544 ++++++++++++++++ .../apex/auth/clieditor/CommandLineException.java | 49 ++ .../auth/clieditor/CommandLineParameterParser.java | 161 +++++ .../apex/auth/clieditor/CommandLineParameters.java | 576 +++++++++++++++++ .../apex/auth/clieditor/CommandLineParser.java | 323 ++++++++++ .../policy/apex/auth/clieditor/KeywordNode.java | 12 +- .../auth/clieditor/TestCLIEditorEventsContext.java | 161 ----- .../apex/auth/clieditor/TestCLIEditorOptions.java | 277 -------- .../auth/clieditor/TestCLIEditorScripting.java | 132 ---- .../TestCommandLineEditorEventsContext.java | 171 +++++ .../clieditor/TestCommandLineEditorOptions.java | 277 ++++++++ .../clieditor/TestCommandLineEditorScripting.java | 132 ++++ .../apex/auth/clieditor/TestContextAlbums.java | 18 +- .../policy/apex/auth/clieditor/TestFileMacro.java | 18 +- .../policy/apex/auth/clieditor/TestLogicBlock.java | 32 +- client/client-deployment/pom.xml | 3 - client/client-editor/pom.xml | 3 - client/client-full/pom.xml | 2 - client/client-monitoring/pom.xml | 3 - .../impl/distribution/AbstractDistributor.java | 4 +- .../TestPersistentContextInstantiation.java | 8 +- .../core/deployment/ApexDeploymentException.java | 6 +- .../messaging/MessagingException.java | 6 +- .../threading/ApplicationThreadFactory.java | 6 +- .../apex/core/infrastructure/xml/XPathReader.java | 6 +- .../onap/policy/apex/core/protocols/Action.java | 2 +- .../onap/policy/apex/core/protocols/Message.java | 8 +- .../core/protocols/engdep/messages/Response.java | 10 +- examples/examples-aadm/pom.xml | 2 +- .../apex/examples/aadm/concepts/ENodeBStatus.java | 8 +- .../apex/examples/aadm/concepts/IMSIStatus.java | 175 ----- .../examples/aadm/concepts/IPAddressStatus.java | 79 --- .../apex/examples/aadm/concepts/ImsiStatus.java | 175 +++++ .../examples/aadm/concepts/IpAddressStatus.java | 79 +++ .../aadm/model/AADMDomainModelFactory.java | 703 --------------------- .../examples/aadm/model/AADMDomainModelSaver.java | 57 -- .../aadm/model/AadmDomainModelFactory.java | 703 +++++++++++++++++++++ .../examples/aadm/model/AadmDomainModelSaver.java | 57 ++ .../config/AADM/Stdin2StdoutJsonEvent.json | 2 +- .../examples/config/AADM/Stdin2StdoutXmlEvent.json | 6 +- .../model/mvel/AADMDoSProvenActTask_TaskLogic.mvel | 14 +- .../mvel/AADMDoSSuggestionActTask_TaskLogic.mvel | 28 +- .../aadm/model/mvel/AADMMatchTask_TaskLogic.mvel | 20 +- .../mvel/AADMPolicy_Act_TaskSelectionLogic.mvel | 8 +- .../aadm/model/mvel/PeriodicActTask_TaskLogic.mvel | 6 +- .../aadm/model/mvel/SAPCActTask_TaskLogic.mvel | 8 +- .../policy/apex/examples/aadm/TestAADMModel.java | 85 --- .../apex/examples/aadm/TestAADMModelCreator.java | 57 -- .../policy/apex/examples/aadm/TestAADMUseCase.java | 455 ------------- .../policy/apex/examples/aadm/TestAadmDbWrite.java | 2 +- .../policy/apex/examples/aadm/TestAadmModel.java | 85 +++ .../apex/examples/aadm/TestAadmModelCreator.java | 57 ++ .../policy/apex/examples/aadm/TestAadmUseCase.java | 459 ++++++++++++++ .../adaptive/TestAnomalyDetectionTslUseCase.java | 27 +- .../examples/adaptive/TestAutoLearnTslUseCase.java | 28 +- examples/examples-decisionmaker/pom.xml | 2 +- examples/examples-myfirstpolicy/pom.xml | 2 +- .../myfirstpolicy/model/MFPDomainModelFactory.java | 86 --- .../myfirstpolicy/model/MFPDomainModelSaver.java | 62 -- .../myfirstpolicy/model/MfpDomainModelFactory.java | 86 +++ .../myfirstpolicy/model/MfpDomainModelSaver.java | 62 ++ .../1/MyFirstPolicyConfigFile2StdoutJsonEvent.json | 2 +- .../MyFirstPolicyConfigStdin2StdoutJsonEvent.json | 2 +- .../1/MyFirstPolicyConfigWs2WsServerJsonEvent.json | 6 +- .../2/MyFirstPolicyConfigFile2StdoutJsonEvent.json | 2 +- .../MyFirstPolicyConfigStdin2StdoutJsonEvent.json | 2 +- .../2/MyFirstPolicyConfigWs2WsServerJsonEvent.json | 6 +- .../apex/examples/myfirstpolicy/TestMfpLogic.java | 8 +- .../examples/myfirstpolicy/TestMfpModelCli.java | 6 +- .../myfirstpolicy/TestMfpModelCreator.java | 6 +- .../examples/myfirstpolicy/TestMfpUseCase.java | 16 +- examples/examples-onap-vcpe/pom.xml | 2 +- .../apex/domains/onap/vcpe/AAIAndGuardSim.java | 59 -- .../domains/onap/vcpe/AAIAndGuardSimEndpoint.java | 137 ---- .../apex/domains/onap/vcpe/AaiAndGuardSim.java | 76 +++ .../domains/onap/vcpe/AaiAndGuardSimEndpoint.java | 183 ++++++ .../pcvs/model/PcvsDomainModelFactory.java | 4 +- examples/examples-periodic/pom.xml | 2 +- .../src/main/package/scripts/apexApps.bat | 2 +- .../src/main/package/scripts/apexApps.sh | 2 +- .../hazelcast/HazelcastContextDistributor.java | 18 +- .../hazelcast/HazelcastContextDistributorTest.java | 31 + .../infinispan/InfinispanContextDistributor.java | 31 +- .../InfinispanDistributorParameters.java | 12 +- .../distribution/infinispan/InfinispanManager.java | 8 +- .../InfinispanContextDistributorTest.java | 38 ++ .../context/locking/curator/CuratorLockFacade.java | 9 +- .../locking/curator/CuratorLockManager.java | 7 +- .../curator/CuratorReentrantReadWriteLock.java | 8 +- .../context/locking/hazelcast/HazelcastLock.java | 14 +- .../locking/hazelcast/HazelcastLockManager.java | 6 +- .../context/schema/avro/AvroBytesObjectMapper.java | 6 +- .../schema/avro/AvroDirectObjectMapper.java | 14 +- .../schema/avro/AvroObjectMapperFactory.java | 13 +- .../context/schema/avro/AvroSchemaHelper.java | 47 +- .../avro/AvroSchemaKeyTranslationUtilities.java | 4 +- .../schema/avro/AvroStringObjectMapper.java | 2 +- .../context/schema/avro/TestAvroSchemaAAI.java | 93 --- .../context/schema/avro/TestAvroSchemaAai.java | 111 ++++ .../context/schema/avro/TestAvroSchemaArray.java | 38 +- .../context/schema/avro/TestAvroSchemaEnum.java | 33 +- .../context/schema/avro/TestAvroSchemaFixed.java | 61 +- .../avro/TestAvroSchemaHelperBadSchemas.java | 16 +- .../schema/avro/TestAvroSchemaHelperMarshal.java | 139 ++-- .../schema/avro/TestAvroSchemaHelperUnmarshal.java | 117 ++-- .../context/schema/avro/TestAvroSchemaMap.java | 42 +- .../context/schema/avro/TestAvroSchemaRecord.java | 64 +- .../context/schema/avro/TestAvroSchemaUnion.java | 40 +- .../context/schema/avro/TestHealthCheckSchema.java | 47 +- .../plugins/event/carrier/jms/ApexJMSConsumer.java | 280 -------- .../plugins/event/carrier/jms/ApexJMSProducer.java | 287 --------- .../plugins/event/carrier/jms/ApexJmsConsumer.java | 280 ++++++++ .../plugins/event/carrier/jms/ApexJmsProducer.java | 292 +++++++++ .../jms/JMSCarrierTechnologyParameters.java | 375 ----------- .../jms/JmsCarrierTechnologyParameters.java | 375 +++++++++++ .../event/carrier/kafka/ApexKafkaConsumer.java | 10 +- .../event/carrier/kafka/ApexKafkaProducer.java | 13 +- .../kafka/KAFKACarrierTechnologyParameters.java | 419 ------------ .../kafka/KafkaCarrierTechnologyParameters.java | 419 ++++++++++++ .../carrier/restclient/ApexRestClientConsumer.java | 16 +- .../carrier/restclient/ApexRestClientProducer.java | 33 +- .../RESTClientCarrierTechnologyParameters.java | 135 ---- .../RestClientCarrierTechnologyParameters.java | 135 ++++ .../carrier/restrequestor/ApexRestRequest.java | 35 + .../restrequestor/ApexRestRequestorConsumer.java | 68 +- .../restrequestor/ApexRestRequestorProducer.java | 6 +- .../RESTRequestorCarrierTechnologyParameters.java | 125 ---- .../RestRequestorCarrierTechnologyParameters.java | 125 ++++ .../adapt/restrequestor/TestRESTRequestor.java | 291 --------- .../adapt/restrequestor/TestRestRequestor.java | 363 +++++++++++ .../restrequestor/TestRestRequestorEndpoint.java | 56 ++ .../prodcons/File2RESTRequest2FileDelete.json | 6 +- .../prodcons/File2RESTRequest2FileGet.json | 6 +- .../File2RESTRequest2FileGetConsumerAlone.json | 6 +- .../prodcons/File2RESTRequest2FileGetMulti.json | 10 +- .../File2RESTRequest2FileGetProducerAlone.json | 4 +- .../prodcons/File2RESTRequest2FilePost.json | 6 +- .../prodcons/File2RESTRequest2FilePut.json | 6 +- .../carrier/restserver/ApexRestServerConsumer.java | 28 +- .../carrier/restserver/ApexRestServerProducer.java | 18 +- .../RESTServerCarrierTechnologyParameters.java | 136 ---- .../RestServerCarrierTechnologyParameters.java | 136 ++++ .../carrier/restserver/RestServerEndpoint.java | 20 +- .../carrier/websocket/ApexWebSocketConsumer.java | 11 +- .../carrier/websocket/ApexWebSocketProducer.java | 31 +- .../WEBSOCKETCarrierTechnologyParameters.java | 116 ---- .../WebSocketCarrierTechnologyParameters.java | 116 ++++ .../protocol/jms/Apex2JMSObjectEventConverter.java | 151 ----- .../protocol/jms/Apex2JMSTextEventConverter.java | 102 --- .../protocol/jms/Apex2JmsObjectEventConverter.java | 153 +++++ .../protocol/jms/Apex2JmsTextEventConverter.java | 95 +++ .../jms/JMSObjectEventProtocolParameters.java | 127 ---- .../jms/JMSTextEventProtocolParameters.java | 56 -- .../jms/JmsObjectEventProtocolParameters.java | 127 ++++ .../jms/JmsTextEventProtocolParameters.java | 56 ++ .../event/protocol/xml/Apex2XMLEventConverter.java | 206 ------ .../event/protocol/xml/Apex2XmlEventConverter.java | 208 ++++++ .../protocol/xml/XMLEventProtocolParameters.java | 53 -- .../protocol/xml/XmlEventProtocolParameters.java | 53 ++ .../event/protocol/xml/TestXMLEventHandler.java | 147 ----- .../protocol/xml/TestXMLTaggedEventConsumer.java | 336 ---------- .../event/protocol/xml/TestXmlEventHandler.java | 147 +++++ .../protocol/xml/TestXmlTaggedEventConsumer.java | 446 +++++++++++++ .../event/protocol/xml/XMLEventGenerator.java | 104 --- .../event/protocol/xml/XmlEventGenerator.java | 125 ++++ .../protocol/yaml/Apex2YamlEventConverter.java | 79 +-- .../protocol/yaml/YamlEventProtocolParameters.java | 2 +- .../event/protocol/yaml/TestYamlEventProtocol.java | 83 ++- .../protocol/yaml/TestYamlPluginStability.java | 26 +- .../executor/java/JavaStateFinalizerExecutor.java | 8 +- .../plugins/executor/java/JavaTaskExecutor.java | 8 +- .../executor/java/JavaTaskSelectExecutor.java | 8 +- .../JavascriptStateFinalizerExecutor.java | 6 +- .../javascript/JavascriptTaskExecutor.java | 6 +- .../javascript/JavascriptTaskSelectExecutor.java | 41 +- .../jruby/JrubyStateFinalizerExecutor.java | 6 +- .../plugins/executor/jruby/JrubyTaskExecutor.java | 6 +- .../executor/jruby/JrubyTaskSelectExecutor.java | 6 +- .../jython/JythonStateFinalizerExecutor.java | 6 +- .../executor/jython/JythonTaskExecutor.java | 6 +- .../executor/jython/JythonTaskSelectExecutor.java | 16 +- .../executor/mvel/MVELExecutorParameters.java | 42 -- .../executor/mvel/MvelExecutorParameters.java | 42 ++ .../executor/mvel/MvelStateFinalizerExecutor.java | 6 +- .../plugins/executor/mvel/MvelTaskExecutor.java | 6 +- .../executor/mvel/MvelTaskSelectExecutor.java | 6 +- .../engine/engdep/EngDepMessageListener.java | 96 ++- .../engine/engdep/EngDepMessagingService.java | 7 +- .../apex/service/engine/event/ApexEvent.java | 42 +- .../engine/event/ApexPeriodicEventGenerator.java | 8 +- .../engine/event/SynchronousEventCache.java | 41 +- .../engine/event/impl/EventConsumerFactory.java | 5 - .../engine/event/impl/EventProducerFactory.java | 5 - .../impl/enevent/ApexEvent2EnEventConverter.java | 19 +- .../FILECarrierTechnologyParameters.java | 217 ------- .../FileCarrierTechnologyParameters.java | 212 +++++++ .../consumer/ApexFileEventConsumer.java | 61 +- .../CharacterDelimitedTextBlockReader.java | 35 +- .../consumer/HeaderDelimitedTextBlockReader.java | 2 +- .../producer/ApexFileEventProducer.java | 10 +- .../Apex2JSONEventConverter.java | 438 ------------- .../Apex2JsonEventConverter.java | 440 +++++++++++++ .../JSONEventProtocolParameters.java | 187 ------ .../JsonEventProtocolParameters.java | 187 ++++++ .../engine/main/ApexCommandLineArguments.java | 23 +- .../service/engine/main/ApexEventMarshaller.java | 8 +- .../service/engine/main/ApexEventUnmarshaller.java | 60 +- .../policy/apex/service/engine/main/ApexMain.java | 8 - .../apex/service/engine/runtime/EngineService.java | 2 +- .../engine/runtime/impl/EngineServiceImpl.java | 166 ++--- .../service/engine/runtime/impl/EngineWorker.java | 74 ++- .../service/parameters/ApexParameterHandler.java | 35 +- .../apex/service/parameters/ApexParameters.java | 42 +- .../CarrierTechnologyParameters.java | 15 +- .../CarrierTechnologyParametersJSONAdapter.java | 177 ------ .../CarrierTechnologyParametersJsonAdapter.java | 184 ++++++ .../engineservice/EngineServiceParameters.java | 11 +- .../EngineServiceParametersJSONAdapter.java | 283 --------- .../EngineServiceParametersJsonAdapter.java | 283 +++++++++ .../eventhandler/EventHandlerParameters.java | 43 +- .../EventProtocolParametersJSONAdapter.java | 173 ----- .../EventProtocolParametersJsonAdapter.java | 177 ++++++ .../service/engine/event/JSONEventGenerator.java | 444 ------------- .../service/engine/event/JsonEventGenerator.java | 540 ++++++++++++++++ .../service/engine/event/TestJSONEventHandler.java | 328 ---------- .../engine/event/TestJSONTaggedEventConsumer.java | 131 ---- .../service/engine/event/TestJsonEventHandler.java | 358 +++++++++++ .../engine/event/TestJsonTaggedEventConsumer.java | 131 ++++ .../engine/parameters/ContextParameterTests.java | 19 +- .../service/engine/parameters/ParameterTests.java | 29 +- .../engine/parameters/ProducerConsumerTests.java | 36 +- .../engine/parameters/SyncParameterTests.java | 11 +- .../SuperDooperCarrierTechnologyParameters.java | 53 +- .../SuperDooperDistributorParameters.java | 4 +- ...SuperTokenDelimitedEventProtocolParameters.java | 4 +- .../parameters/prodConsBadCTParClass.json | 2 +- .../parameters/prodConsBadEPParClass.json | 2 +- .../test/resources/parameters/prodConsNoCT.json | 2 +- .../test/resources/parameters/prodConsNoEP.json | 2 +- .../test/script/engine/TestApexEngineMVEL.java | 92 --- .../test/script/engine/TestApexEngineMvel.java | 92 +++ .../test/script/event/TestEventInstantiation.java | 4 +- .../handling/TestContextUpdateDifferentModels.java | 4 +- .../script/handling/TestContextUpdateModel.java | 4 +- .../uservice/test/adapt/kafka/TestKafka2Kafka.java | 37 +- .../websocket/WebSocketEventProducerClient.java | 30 + .../websocket/WebSocketEventProducerServer.java | 29 + .../websocket/WebSocketEventSubscriberClient.java | 24 + .../websocket/WebSocketEventSubscriberServer.java | 23 + .../test/context/EventAlbumContextTest.java | 6 +- .../uservice/test/engdep/EngDepMessagingTest.java | 4 +- .../prodcons/File2FileFilteredInJsonEvent.json | 2 +- .../prodcons/File2FileFilteredInOutJsonEvent.json | 2 +- .../prodcons/File2FileFilteredOutJsonEvent.json | 2 +- .../resources/prodcons/File2FileJsonEvent.json | 2 +- .../test/resources/prodcons/File2FileXmlEvent.json | 6 +- .../prodcons/File2RESTJsonEventBadHTTPMethod.json | 4 +- .../prodcons/File2RESTJsonEventBadURL.json | 4 +- .../prodcons/File2RESTJsonEventNoURL.json | 4 +- .../resources/prodcons/File2RESTJsonEventPost.json | 4 +- .../File2RESTJsonEventPostBadResponse.json | 4 +- .../resources/prodcons/File2RESTJsonEventPut.json | 4 +- .../test/resources/prodcons/JMS2JMSJsonEvent.json | 10 +- .../resources/prodcons/JMS2JMSObjectEvent.json | 8 +- .../resources/prodcons/Kafka2KafkaJsonEvent.json | 6 +- .../resources/prodcons/Kafka2KafkaXmlEvent.json | 10 +- .../prodcons/LBPolicy_ExecModel_file2kafka.json | 4 +- .../prodcons/REST2FileJsonEmptyEvents.json | 4 +- .../resources/prodcons/REST2FileJsonEvent.json | 4 +- .../prodcons/REST2FileJsonEventBadHTTPMethod.json | 4 +- .../prodcons/REST2FileJsonEventBadResponse.json | 4 +- .../prodcons/REST2FileJsonEventBadURL.json | 4 +- .../prodcons/REST2FileJsonEventNoURL.json | 4 +- .../resources/prodcons/RESTServerJsonEvent.json | 6 +- .../RESTServerJsonEventConsumerNotSync.json | 6 +- ...ESTServerJsonEventConsumerStandaloneNoHost.json | 6 +- ...ESTServerJsonEventConsumerStandaloneNoPort.json | 6 +- .../prodcons/RESTServerJsonEventContextAvro.json | 6 +- .../prodcons/RESTServerJsonEventContextJava.json | 6 +- .../prodcons/RESTServerJsonEventDivideByZero.json | 6 +- .../prodcons/RESTServerJsonEventMultiIn.json | 10 +- .../prodcons/RESTServerJsonEventProducerHost.json | 6 +- .../RESTServerJsonEventProducerNotSync.json | 6 +- .../prodcons/RESTServerJsonEventProducerPort.json | 6 +- .../RESTServerJsonEventProducerStandalone.json | 6 +- .../resources/prodcons/Ws2WsClientJsonEvent.json | 6 +- .../resources/prodcons/Ws2WsClientXMLEvent.json | 10 +- .../resources/prodcons/Ws2WsServerJsonEvent.json | 6 +- .../resources/prodcons/Ws2WsServerXMLEvent.json | 10 +- .../engine/benchmark/ApexBaseBenchMarkTest.java | 4 +- .../engine/runtime/ApexServiceModelUpdateTest.java | 4 +- .../service/engine/runtime/ApexServiceTest.java | 30 +- .../tools/model/generator/model2cli/Model2Cli.java | 28 +- 313 files changed, 14189 insertions(+), 12984 deletions(-) delete mode 100644 auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CGCliEditor.java create mode 100644 auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditor.java create mode 100644 auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestGeneration.java delete mode 100644 auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestSTG.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCLIEditorMain.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCommandLineEditorMain.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgument.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgumentValue.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommand.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommands.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIEditorLoop.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIException.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLILineParser.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameterParser.java delete mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameters.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgumentValue.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommands.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineException.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameters.java create mode 100644 auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParser.java delete mode 100644 auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorEventsContext.java delete mode 100644 auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorOptions.java delete mode 100644 auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorScripting.java create mode 100644 auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorEventsContext.java create mode 100644 auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorOptions.java create mode 100644 auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorScripting.java delete mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IMSIStatus.java delete mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IPAddressStatus.java create mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ImsiStatus.java create mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IpAddressStatus.java delete mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AADMDomainModelFactory.java delete mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AADMDomainModelSaver.java create mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelFactory.java create mode 100644 examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelSaver.java delete mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModel.java delete mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModelCreator.java delete mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMUseCase.java create mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java create mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModelCreator.java create mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java delete mode 100644 examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelFactory.java delete mode 100644 examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelSaver.java create mode 100644 examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelFactory.java create mode 100644 examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelSaver.java delete mode 100644 examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSim.java delete mode 100644 examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSimEndpoint.java create mode 100644 examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java create mode 100644 examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.java delete mode 100644 plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAAI.java create mode 100644 plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAai.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSConsumer.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSProducer.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsConsumer.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsProducer.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JMSCarrierTechnologyParameters.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KAFKACarrierTechnologyParameters.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RESTClientCarrierTechnologyParameters.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RestClientCarrierTechnologyParameters.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RESTRequestorCarrierTechnologyParameters.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParameters.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRESTRequestor.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestor.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RESTServerCarrierTechnologyParameters.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerCarrierTechnologyParameters.java delete mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WEBSOCKETCarrierTechnologyParameters.java create mode 100644 plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WebSocketCarrierTechnologyParameters.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSObjectEventConverter.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSTextEventConverter.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsObjectEventConverter.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsTextEventConverter.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSObjectEventProtocolParameters.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSTextEventProtocolParameters.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsObjectEventProtocolParameters.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsTextEventProtocolParameters.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XMLEventConverter.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XmlEventConverter.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventProtocolParameters.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlEventProtocolParameters.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXMLEventHandler.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXMLTaggedEventConsumer.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlEventHandler.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlTaggedEventConsumer.java delete mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventGenerator.java create mode 100644 plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlEventGenerator.java delete mode 100644 plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MVELExecutorParameters.java create mode 100644 plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelExecutorParameters.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParameters.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JsonEventProtocolParameters.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJsonAdapter.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJsonAdapter.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJsonAdapter.java delete mode 100644 services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JSONEventGenerator.java create mode 100644 services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventGenerator.java delete mode 100644 services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONEventHandler.java delete mode 100644 services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONTaggedEventConsumer.java create mode 100644 services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java create mode 100644 services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonTaggedEventConsumer.java delete mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMVEL.java create mode 100644 testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMvel.java diff --git a/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CGCliEditor.java b/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CGCliEditor.java deleted file mode 100644 index 30e883aae..000000000 --- a/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CGCliEditor.java +++ /dev/null @@ -1,570 +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.auth.clicodegen; - -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.ALBUM_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.ALBUM_VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.CONTEXT_REFS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.CTX_REFS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DECLARATION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFAULT_TASK; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFAULT_TASK_VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFAULT_VALUE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFINITIONS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DESCRIPTION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.EVENT_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.EVENT_VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELDS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELD_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELD_SCHEMA; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELD_SCHEMA_VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FINALIZER_LOGICS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FINALIZER_LOGIC_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIRST_STATE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FLAVOUR; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.INFIELDS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.LOGIC; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.LOGIC_FLAVOUR; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.NAME_SPACE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.NEXT_STATE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OPTIONAL; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTFIELDS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTPUTS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTPUT_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTPUT_TYPE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.PARAMS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.PAR_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.POLICY_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCHEMA; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCHEMA_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCHEMA_VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCOPE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SOURCE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.STATES; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.STATE_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TARGET; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASKS; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASK_LOCAL_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASK_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASK_VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TEMPLATE; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TRIGGER_NAME; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TRIGGER_VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TS_LOGIC; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.UUID; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.VERSION; -import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.WRITABLE; - -import java.util.List; - -import org.stringtemplate.v4.ST; -import org.stringtemplate.v4.STGroupFile; - -/** - * Code generator generating expressions for the APEX CLI Editor. - * - * @author Sven van der Meer (sven.van.der.meer@ericsson.com) - */ -public class CGCliEditor { - - // CHECKSTYLE:OFF: ParameterNumber - - /** The name of the STG file for the code generator. */ - public static final String STG_FILE = "org/onap/policy/apex/auth/clicodegen/cli-editor.stg"; - - /** The String Template Group, taken from the context. */ - private final STGroupFile stg; - - /** The ST for the model, loaded from the STG. */ - private final ST model; - - /** A default name space, set from specification. */ - private String defaultNamespace; - - /** - * Creates a new code generator. - */ - public CGCliEditor() { - stg = new STGroupFile(STG_FILE); - stg.registerRenderer(String.class, new CgStringRenderer(), true); - model = stg.getInstanceOf("policyModel"); - } - - /** - * Adds model parameters to the template. - * - * @param name the name of the mode, must not be blank - * @param version a version, can be null - * @param uuid a UUID, can be null - * @param description a description, must not be blank - */ - public void addModelParams(final String name, final String version, final String uuid, final String description) { - if (name == null || name.isEmpty()) { - throw new IllegalArgumentException("model name should not be blank"); - } - if (description == null || description.isEmpty()) { - throw new IllegalArgumentException("model description should not be blank"); - } - - model.add(NAME, name); - model.add(VERSION, version); - model.add(UUID, uuid); - model.add(DESCRIPTION, description); - } - - /** - * Returns the model. - * - * @return the model - */ - public ST getModel() { - return model; - } - - /** - * Sets the default name space. - * - * @param nameSpace new name space, ignored if blank - */ - public void setDefaultNamespace(final String nameSpace) { - if (nameSpace != null && !nameSpace.isEmpty()) { - defaultNamespace = nameSpace; - } - } - - /** - * Adds a new schema declaration to the model. - * - * @param name the name of the schema - * @param version the version of the declaration - * @param uuid the UUID for the declaration - * @param description a description of the schema - * @param flavour the flavour of the schema declaration, e.g. Java or Avro - * @param schema the actual schema declaration, either a string or as LS schema LE - */ - public void addSchemaDeclaration(final String name, final String version, final String uuid, - final String description, final String flavour, final String schema) { - final ST st = stg.getInstanceOf("schemaDecl"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(UUID, uuid); - st.add(DESCRIPTION, description); - st.add(FLAVOUR, flavour); - st.add(SCHEMA, schema); - model.add(DECLARATION, st); - } - - /** - * Adds a new context album declaration to the model. - * - * @param name the name of the context album - * @param version the version of the context album - * @param uuid a UUID for the declaration - * @param description a description for the context album - * @param scope the scope - * @param writable a flag for writable context - * @param schemaName the name of the schema - * @param schemaVersion the version of the declaration - */ - public void addContextAlbumDeclaration(final String name, final String version, final String uuid, - final String description, final String scope, final boolean writable, final String schemaName, - final String schemaVersion) { - final ST st = stg.getInstanceOf("ctxAlbumDecl"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(UUID, uuid); - st.add(DESCRIPTION, description); - st.add(SCOPE, scope); - st.add(WRITABLE, writable); - st.add(SCHEMA_NAME, schemaName); - st.add(SCHEMA_VERSION, schemaVersion); - model.add(DECLARATION, st); - } - - /** - * Creates a new event field definition which belongs to an event. - * - * @param eventName the event name - * @param version the event version - * @param fieldName the name for the field in the event - * @param fieldSchema the schema of the field - * @param fieldSchemaVersion the version of the schema - * @param optional a flag for optional fields - * @return a CLI command for event field definition - */ - public ST createEventFieldDefinition(final String eventName, final String version, final String fieldName, - final String fieldSchema, final String fieldSchemaVersion, final boolean optional) { - final ST st = stg.getInstanceOf("eventDefField"); - st.add(EVENT_NAME, eventName); - st.add(VERSION, version); - st.add(FIELD_NAME, fieldName); - st.add(FIELD_SCHEMA, fieldSchema); - st.add(FIELD_SCHEMA_VERSION, fieldSchemaVersion); - st.add(OPTIONAL, optional); - return st; - } - - /** - * Creates a new task logic definition which belongs to a task. - * - * @param taskName the name of the task - * @param version the task version - * @param flavour the flavour, e.g. JAVA or JAVASCRIPT - * @param logic the actual logic (use either a string or a multi-line with - * LS some code LE - * @return a CLI command for task definition, logic - */ - public ST createTaskDefLogic(final String taskName, final String version, final String flavour, - final String logic) { - final ST st = stg.getInstanceOf("taskDefLogic"); - st.add(TASK_NAME, taskName); - st.add(VERSION, version); - st.add(FLAVOUR, flavour); - st.add(LOGIC, logic); - return st; - } - - /** - * Adds a new event declaration to the model. - * - * @param name the event name - * @param version the event version - * @param uuid a UUID for the definition - * @param description a description of the event - * @param nameSpace the name space for the event - * @param source a source sending the event - * @param target a target receiving the event - * @param fields any event fields - */ - public void addEventDeclaration(final String name, final String version, final String uuid, - final String description, final String nameSpace, final String source, final String target, - final List fields) { - final ST st = stg.getInstanceOf("eventDecl"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(UUID, uuid); - st.add(DESCRIPTION, description); - st.add(SOURCE, source); - st.add(TARGET, target); - st.add(FIELDS, fields); - - if (nameSpace != null) { - st.add(NAME_SPACE, nameSpace); - } else if (defaultNamespace != null) { - st.add(NAME_SPACE, defaultNamespace); - } - - model.add(DECLARATION, st); - } - - /** - * Adds a new task declaration to the model. - * - * @param name the name of the task - * @param version the version of the task - * @param uuid a UUID for the definition - * @param description a description of the task - * @param infields all infields for the task - * @param outfields all outfields for the task - * @param logic the logic for the task - * @param parameters any task parameter - * @param contextRefs any context reference - */ - public void addTaskDeclaration(final String name, final String version, final String uuid, final String description, - final List infields, final List outfields, final ST logic, final List parameters, - final List contextRefs) { - final ST st = stg.getInstanceOf("taskDecl"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(UUID, uuid); - st.add(DESCRIPTION, description); - st.add(INFIELDS, infields); - st.add(OUTFIELDS, outfields); - st.add(LOGIC, logic); - st.add(PARAMS, parameters); - st.add(CONTEXT_REFS, contextRefs); - model.add(DECLARATION, st); - } - - /** - * Adds a new policy definition to the model. - * - * @param name the name of the policy - * @param version the version of the policy - * @param uuid a UUID for the definition - * @param description a description of the policy - * @param template the template type for this policy - * @param firstState the first state of the policy - * @param states all policy states - */ - public void addPolicyDefinition(final String name, final String version, final String uuid, - final String description, final String template, final String firstState, final List states) { - final ST st = stg.getInstanceOf("policyDef"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(UUID, uuid); - st.add(DESCRIPTION, description); - st.add(TEMPLATE, template); - st.add(FIRST_STATE, firstState); - st.add(STATES, states); - model.add(DEFINITIONS, st); - } - - /** - * Creates a new task infield definition. - * - * @param taskName the name of the task - * @param version the version of the task - * @param fieldName the name of the infield - * @param fieldSchema the schema for the infield - * @param fieldSchemaVersion the version of the schema - * @return a CLI command for task infield definition - */ - public ST createTaskDefinitionInfields(final String taskName, final String version, final String fieldName, - final String fieldSchema, final String fieldSchemaVersion) { - final ST st = stg.getInstanceOf("taskDefInputFields"); - st.add(TASK_NAME, taskName); - st.add(VERSION, version); - st.add(FIELD_NAME, fieldName); - st.add(FIELD_SCHEMA, fieldSchema); - st.add(FIELD_SCHEMA_VERSION, fieldSchemaVersion); - return st; - } - - /** - * Creates a new task outfield definition. - * - * @param taskName the name of the task - * @param version the version of the task - * @param fieldName the name of the outfield - * @param fieldSchema the schema for the outfield - * @param fieldSchemaVersion the version of the schema - * @return a CLI command for task outfield definition - */ - public ST createTaskDefinitionOutfields(final String taskName, final String version, final String fieldName, - final String fieldSchema, final String fieldSchemaVersion) { - final ST st = stg.getInstanceOf("taskDefOutputFields"); - st.add(TASK_NAME, taskName); - st.add(VERSION, version); - st.add(FIELD_NAME, fieldName); - st.add(FIELD_SCHEMA, fieldSchema); - st.add(FIELD_SCHEMA_VERSION, fieldSchemaVersion); - return st; - } - - /** - * Creates a new task parameter definition belonging to a task. - * - * @param name the name of the task - * @param version the version of the task - * @param parName the parameter name - * @param defaultValue a default value for the parameter - * @return a CLI command for a task parameter definition - */ - public ST createTaskDefinitionParameters(final String name, final String version, final String parName, - final String defaultValue) { - final ST st = stg.getInstanceOf("taskDefParameter"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(PAR_NAME, parName); - st.add(DEFAULT_VALUE, defaultValue); - return st; - } - - /** - * Creates a new task definition context reference which belongs to a task. - * - * @param name the name of the task - * @param version the version of the task - * @param albumName the name of the context album - * @param albumVersion the version of the context album - * @return a CLI command for a task context reference definition - */ - public ST createTaskDefinitionContextRef(final String name, final String version, final String albumName, - final String albumVersion) { - final ST st = stg.getInstanceOf("taskDefCtxRef"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(ALBUM_NAME, albumName); - st.add(ALBUM_VERSION, albumVersion); - return st; - } - - /** - * Creates a new policy state task definition for a task which belongs to a state which belongs - * to a policy. - * - * @param policyName the name of the policy - * @param version the version of the policy - * @param stateName the name of the new state - * @param taskLocalName the local (in policy and state) name of the task - * @param taskName the identifier of the task (previously defined as a task) - * @param taskVersion the version of the task definition - * @param outputType the output type - * @param outputName the output name - * @return a CLI command for a policy state task definition - */ - public ST createPolicyStateTask(final String policyName, final String version, final String stateName, - final String taskLocalName, final String taskName, final String taskVersion, final String outputType, - final String outputName) { - final ST st = stg.getInstanceOf("policyStateTask"); - st.add(POLICY_NAME, policyName); - st.add(VERSION, version); - st.add(STATE_NAME, stateName); - st.add(TASK_LOCAL_NAME, taskLocalName); - st.add(TASK_NAME, taskName); - st.add(TASK_VERSION, taskVersion); - st.add(OUTPUT_TYPE, outputType); - st.add(OUTPUT_NAME, outputName); - return st; - } - - /** - * Creates a new policy state output definition for a state which belongs to a policy. - * - * @param policyName the name of the policy - * @param version the version of the policy - * @param stateName the name of the new state - * @param outputName the name of the new output - * @param eventName the event name for the output - * @param eventVersion the version of the event for the output - * @param nextState the next state if any - * @return a CLI command for a state output definition - */ - public ST createPolicyStateOutput(final String policyName, final String version, final String stateName, - final String outputName, final String eventName, final String eventVersion, final String nextState) { - final ST st = stg.getInstanceOf("policyStateOutput"); - st.add(POLICY_NAME, policyName); - st.add(VERSION, version); - st.add(STATE_NAME, stateName); - st.add(OUTPUT_NAME, outputName); - st.add(EVENT_NAME, eventName); - st.add(EVENT_VERSION, eventVersion); - st.add(NEXT_STATE, nextState); - return st; - } - - /** - * Creates a new policy state definition for a state which belongs to a policy. - * - * @param policyName the name of the policy - * @param version the version of the policy - * @param stateName the name of the new state - * @param triggerName the name of the trigger event - * @param triggerVersion the version of the trigger event - * @param defaultTask the identifier of the default task - * @param defaultTaskVersion the version of the default task - * @param outputs the output definitions of the state - * @param tasks the task definition of the state - * @param tsLogic the task selection logic of the state - * @param finalizerLogics the finalizer logics for the state - * @param ctxRefs any context reference for the state - * @return a CLI command for a policy state definition - */ - public ST createPolicyStateDef(final String policyName, final String version, final String stateName, - final String triggerName, final String triggerVersion, final String defaultTask, - final String defaultTaskVersion, final List outputs, final List tasks, final List tsLogic, - final List finalizerLogics, final List ctxRefs) { - final ST st = stg.getInstanceOf("policyStateDef"); - st.add(POLICY_NAME, policyName); - st.add(VERSION, version); - st.add(STATE_NAME, stateName); - st.add(TRIGGER_NAME, triggerName); - st.add(TRIGGER_VERSION, triggerVersion); - st.add(DEFAULT_TASK, defaultTask); - st.add(DEFAULT_TASK_VERSION, defaultTaskVersion); - st.add(OUTPUTS, outputs); - st.add(TASKS, tasks); - st.add(TS_LOGIC, tsLogic); - st.add(FINALIZER_LOGICS, finalizerLogics); - st.add(CTX_REFS, ctxRefs); - return st; - } - - /** - * Creates a new task selection logic definition for a state which belongs to a policy. - * - * @param name the name of the policy - * @param version the version of the policy - * @param stateName the name of the state - * @param logicFlavour the flavour, e.g. JAVA or JAVASCRIPT - * @param logic the actual logic (use either a string or a multi-line with - * LS some code LE - * @return a CLI command for task selection logic definition - */ - public ST createPolicyStateDefTaskSelLogic(final String name, final String version, final String stateName, - final String logicFlavour, final String logic) { - final ST st = stg.getInstanceOf("policyStateTaskSelectionLogic"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(STATE_NAME, stateName); - st.add(LOGIC_FLAVOUR, logicFlavour); - st.add(LOGIC, logic); - return st; - } - - /** - * Creates a new state finalizer definition for a state which belongs to a policy. - * - * @param name the name of the policy - * @param version the version of the policy - * @param stateName the name of the state - * @param finalizerLogicName name of the finalizer logic - * @param logicFlavour the flavour, e.g. JAVA or JAVASCRIPT - * @param logic the actual logic (use either a string or a multi-line with - * LS some code LE - * @return a CLI command for finalizer definition - */ - public ST createPolicyStateDefFinalizerLogic(final String name, final String version, final String stateName, - final String finalizerLogicName, final String logicFlavour, final String logic) { - final ST st = stg.getInstanceOf("policyStateFinalizerLogic"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(STATE_NAME, stateName); - st.add(FINALIZER_LOGIC_NAME, finalizerLogicName); - st.add(LOGIC_FLAVOUR, logicFlavour); - st.add(LOGIC, logic); - return st; - } - - /** - * Creates a new policy state context reference for a state which belongs to a policy. - * - * @param name the name of the policy - * @param version the version of the policy - * @param stateName the name of the state - * @param albumName the name of the album - * @param albumVersion the version of the album - * @return a CLI command for state context reference - */ - public ST createPolicyStateDefContextRef(final String name, final String version, final String stateName, - final String albumName, final String albumVersion) { - final ST st = stg.getInstanceOf("policyStateContextRef"); - st.add(NAME, name); - st.add(VERSION, version); - st.add(STATE_NAME, stateName); - st.add(ALBUM_NAME, albumName); - st.add(ALBUM_VERSION, albumVersion); - return st; - } - -} diff --git a/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditor.java b/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditor.java new file mode 100644 index 000000000..75ac1fe03 --- /dev/null +++ b/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditor.java @@ -0,0 +1,570 @@ +/*- + * ============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.auth.clicodegen; + +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.ALBUM_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.ALBUM_VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.CONTEXT_REFS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.CTX_REFS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DECLARATION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFAULT_TASK; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFAULT_TASK_VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFAULT_VALUE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DEFINITIONS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.DESCRIPTION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.EVENT_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.EVENT_VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELDS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELD_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELD_SCHEMA; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIELD_SCHEMA_VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FINALIZER_LOGICS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FINALIZER_LOGIC_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FIRST_STATE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.FLAVOUR; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.INFIELDS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.LOGIC; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.LOGIC_FLAVOUR; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.NAME_SPACE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.NEXT_STATE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OPTIONAL; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTFIELDS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTPUTS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTPUT_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.OUTPUT_TYPE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.PARAMS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.PAR_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.POLICY_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCHEMA; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCHEMA_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCHEMA_VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SCOPE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.SOURCE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.STATES; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.STATE_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TARGET; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASKS; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASK_LOCAL_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASK_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TASK_VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TEMPLATE; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TRIGGER_NAME; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TRIGGER_VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.TS_LOGIC; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.UUID; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.VERSION; +import static org.onap.policy.apex.auth.clicodegen.CliEditorContants.WRITABLE; + +import java.util.List; + +import org.stringtemplate.v4.ST; +import org.stringtemplate.v4.STGroupFile; + +/** + * Code generator generating expressions for the APEX CLI Editor. + * + * @author Sven van der Meer (sven.van.der.meer@ericsson.com) + */ +public class CodeGeneratorCliEditor { + + // CHECKSTYLE:OFF: ParameterNumber + + /** The name of the STG file for the code generator. */ + public static final String STG_FILE = "org/onap/policy/apex/auth/clicodegen/cli-editor.stg"; + + /** The String Template Group, taken from the context. */ + private final STGroupFile stg; + + /** The ST for the model, loaded from the STG. */ + private final ST model; + + /** A default name space, set from specification. */ + private String defaultNamespace; + + /** + * Creates a new code generator. + */ + public CodeGeneratorCliEditor() { + stg = new STGroupFile(STG_FILE); + stg.registerRenderer(String.class, new CgStringRenderer(), true); + model = stg.getInstanceOf("policyModel"); + } + + /** + * Adds model parameters to the template. + * + * @param name the name of the mode, must not be blank + * @param version a version, can be null + * @param uuid a UUID, can be null + * @param description a description, must not be blank + */ + public void addModelParams(final String name, final String version, final String uuid, final String description) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("model name should not be blank"); + } + if (description == null || description.isEmpty()) { + throw new IllegalArgumentException("model description should not be blank"); + } + + model.add(NAME, name); + model.add(VERSION, version); + model.add(UUID, uuid); + model.add(DESCRIPTION, description); + } + + /** + * Returns the model. + * + * @return the model + */ + public ST getModel() { + return model; + } + + /** + * Sets the default name space. + * + * @param nameSpace new name space, ignored if blank + */ + public void setDefaultNamespace(final String nameSpace) { + if (nameSpace != null && !nameSpace.isEmpty()) { + defaultNamespace = nameSpace; + } + } + + /** + * Adds a new schema declaration to the model. + * + * @param name the name of the schema + * @param version the version of the declaration + * @param uuid the UUID for the declaration + * @param description a description of the schema + * @param flavour the flavour of the schema declaration, e.g. Java or Avro + * @param schema the actual schema declaration, either a string or as LS schema LE + */ + public void addSchemaDeclaration(final String name, final String version, final String uuid, + final String description, final String flavour, final String schema) { + final ST st = stg.getInstanceOf("schemaDecl"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(UUID, uuid); + st.add(DESCRIPTION, description); + st.add(FLAVOUR, flavour); + st.add(SCHEMA, schema); + model.add(DECLARATION, st); + } + + /** + * Adds a new context album declaration to the model. + * + * @param name the name of the context album + * @param version the version of the context album + * @param uuid a UUID for the declaration + * @param description a description for the context album + * @param scope the scope + * @param writable a flag for writable context + * @param schemaName the name of the schema + * @param schemaVersion the version of the declaration + */ + public void addContextAlbumDeclaration(final String name, final String version, final String uuid, + final String description, final String scope, final boolean writable, final String schemaName, + final String schemaVersion) { + final ST st = stg.getInstanceOf("ctxAlbumDecl"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(UUID, uuid); + st.add(DESCRIPTION, description); + st.add(SCOPE, scope); + st.add(WRITABLE, writable); + st.add(SCHEMA_NAME, schemaName); + st.add(SCHEMA_VERSION, schemaVersion); + model.add(DECLARATION, st); + } + + /** + * Creates a new event field definition which belongs to an event. + * + * @param eventName the event name + * @param version the event version + * @param fieldName the name for the field in the event + * @param fieldSchema the schema of the field + * @param fieldSchemaVersion the version of the schema + * @param optional a flag for optional fields + * @return a CLI command for event field definition + */ + public ST createEventFieldDefinition(final String eventName, final String version, final String fieldName, + final String fieldSchema, final String fieldSchemaVersion, final boolean optional) { + final ST st = stg.getInstanceOf("eventDefField"); + st.add(EVENT_NAME, eventName); + st.add(VERSION, version); + st.add(FIELD_NAME, fieldName); + st.add(FIELD_SCHEMA, fieldSchema); + st.add(FIELD_SCHEMA_VERSION, fieldSchemaVersion); + st.add(OPTIONAL, optional); + return st; + } + + /** + * Creates a new task logic definition which belongs to a task. + * + * @param taskName the name of the task + * @param version the task version + * @param flavour the flavour, e.g. JAVA or JAVASCRIPT + * @param logic the actual logic (use either a string or a multi-line with + * LS some code LE + * @return a CLI command for task definition, logic + */ + public ST createTaskDefLogic(final String taskName, final String version, final String flavour, + final String logic) { + final ST st = stg.getInstanceOf("taskDefLogic"); + st.add(TASK_NAME, taskName); + st.add(VERSION, version); + st.add(FLAVOUR, flavour); + st.add(LOGIC, logic); + return st; + } + + /** + * Adds a new event declaration to the model. + * + * @param name the event name + * @param version the event version + * @param uuid a UUID for the definition + * @param description a description of the event + * @param nameSpace the name space for the event + * @param source a source sending the event + * @param target a target receiving the event + * @param fields any event fields + */ + public void addEventDeclaration(final String name, final String version, final String uuid, + final String description, final String nameSpace, final String source, final String target, + final List fields) { + final ST st = stg.getInstanceOf("eventDecl"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(UUID, uuid); + st.add(DESCRIPTION, description); + st.add(SOURCE, source); + st.add(TARGET, target); + st.add(FIELDS, fields); + + if (nameSpace != null) { + st.add(NAME_SPACE, nameSpace); + } else if (defaultNamespace != null) { + st.add(NAME_SPACE, defaultNamespace); + } + + model.add(DECLARATION, st); + } + + /** + * Adds a new task declaration to the model. + * + * @param name the name of the task + * @param version the version of the task + * @param uuid a UUID for the definition + * @param description a description of the task + * @param infields all infields for the task + * @param outfields all outfields for the task + * @param logic the logic for the task + * @param parameters any task parameter + * @param contextRefs any context reference + */ + public void addTaskDeclaration(final String name, final String version, final String uuid, final String description, + final List infields, final List outfields, final ST logic, final List parameters, + final List contextRefs) { + final ST st = stg.getInstanceOf("taskDecl"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(UUID, uuid); + st.add(DESCRIPTION, description); + st.add(INFIELDS, infields); + st.add(OUTFIELDS, outfields); + st.add(LOGIC, logic); + st.add(PARAMS, parameters); + st.add(CONTEXT_REFS, contextRefs); + model.add(DECLARATION, st); + } + + /** + * Adds a new policy definition to the model. + * + * @param name the name of the policy + * @param version the version of the policy + * @param uuid a UUID for the definition + * @param description a description of the policy + * @param template the template type for this policy + * @param firstState the first state of the policy + * @param states all policy states + */ + public void addPolicyDefinition(final String name, final String version, final String uuid, + final String description, final String template, final String firstState, final List states) { + final ST st = stg.getInstanceOf("policyDef"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(UUID, uuid); + st.add(DESCRIPTION, description); + st.add(TEMPLATE, template); + st.add(FIRST_STATE, firstState); + st.add(STATES, states); + model.add(DEFINITIONS, st); + } + + /** + * Creates a new task infield definition. + * + * @param taskName the name of the task + * @param version the version of the task + * @param fieldName the name of the infield + * @param fieldSchema the schema for the infield + * @param fieldSchemaVersion the version of the schema + * @return a CLI command for task infield definition + */ + public ST createTaskDefinitionInfields(final String taskName, final String version, final String fieldName, + final String fieldSchema, final String fieldSchemaVersion) { + final ST st = stg.getInstanceOf("taskDefInputFields"); + st.add(TASK_NAME, taskName); + st.add(VERSION, version); + st.add(FIELD_NAME, fieldName); + st.add(FIELD_SCHEMA, fieldSchema); + st.add(FIELD_SCHEMA_VERSION, fieldSchemaVersion); + return st; + } + + /** + * Creates a new task outfield definition. + * + * @param taskName the name of the task + * @param version the version of the task + * @param fieldName the name of the outfield + * @param fieldSchema the schema for the outfield + * @param fieldSchemaVersion the version of the schema + * @return a CLI command for task outfield definition + */ + public ST createTaskDefinitionOutfields(final String taskName, final String version, final String fieldName, + final String fieldSchema, final String fieldSchemaVersion) { + final ST st = stg.getInstanceOf("taskDefOutputFields"); + st.add(TASK_NAME, taskName); + st.add(VERSION, version); + st.add(FIELD_NAME, fieldName); + st.add(FIELD_SCHEMA, fieldSchema); + st.add(FIELD_SCHEMA_VERSION, fieldSchemaVersion); + return st; + } + + /** + * Creates a new task parameter definition belonging to a task. + * + * @param name the name of the task + * @param version the version of the task + * @param parName the parameter name + * @param defaultValue a default value for the parameter + * @return a CLI command for a task parameter definition + */ + public ST createTaskDefinitionParameters(final String name, final String version, final String parName, + final String defaultValue) { + final ST st = stg.getInstanceOf("taskDefParameter"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(PAR_NAME, parName); + st.add(DEFAULT_VALUE, defaultValue); + return st; + } + + /** + * Creates a new task definition context reference which belongs to a task. + * + * @param name the name of the task + * @param version the version of the task + * @param albumName the name of the context album + * @param albumVersion the version of the context album + * @return a CLI command for a task context reference definition + */ + public ST createTaskDefinitionContextRef(final String name, final String version, final String albumName, + final String albumVersion) { + final ST st = stg.getInstanceOf("taskDefCtxRef"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(ALBUM_NAME, albumName); + st.add(ALBUM_VERSION, albumVersion); + return st; + } + + /** + * Creates a new policy state task definition for a task which belongs to a state which belongs + * to a policy. + * + * @param policyName the name of the policy + * @param version the version of the policy + * @param stateName the name of the new state + * @param taskLocalName the local (in policy and state) name of the task + * @param taskName the identifier of the task (previously defined as a task) + * @param taskVersion the version of the task definition + * @param outputType the output type + * @param outputName the output name + * @return a CLI command for a policy state task definition + */ + public ST createPolicyStateTask(final String policyName, final String version, final String stateName, + final String taskLocalName, final String taskName, final String taskVersion, final String outputType, + final String outputName) { + final ST st = stg.getInstanceOf("policyStateTask"); + st.add(POLICY_NAME, policyName); + st.add(VERSION, version); + st.add(STATE_NAME, stateName); + st.add(TASK_LOCAL_NAME, taskLocalName); + st.add(TASK_NAME, taskName); + st.add(TASK_VERSION, taskVersion); + st.add(OUTPUT_TYPE, outputType); + st.add(OUTPUT_NAME, outputName); + return st; + } + + /** + * Creates a new policy state output definition for a state which belongs to a policy. + * + * @param policyName the name of the policy + * @param version the version of the policy + * @param stateName the name of the new state + * @param outputName the name of the new output + * @param eventName the event name for the output + * @param eventVersion the version of the event for the output + * @param nextState the next state if any + * @return a CLI command for a state output definition + */ + public ST createPolicyStateOutput(final String policyName, final String version, final String stateName, + final String outputName, final String eventName, final String eventVersion, final String nextState) { + final ST st = stg.getInstanceOf("policyStateOutput"); + st.add(POLICY_NAME, policyName); + st.add(VERSION, version); + st.add(STATE_NAME, stateName); + st.add(OUTPUT_NAME, outputName); + st.add(EVENT_NAME, eventName); + st.add(EVENT_VERSION, eventVersion); + st.add(NEXT_STATE, nextState); + return st; + } + + /** + * Creates a new policy state definition for a state which belongs to a policy. + * + * @param policyName the name of the policy + * @param version the version of the policy + * @param stateName the name of the new state + * @param triggerName the name of the trigger event + * @param triggerVersion the version of the trigger event + * @param defaultTask the identifier of the default task + * @param defaultTaskVersion the version of the default task + * @param outputs the output definitions of the state + * @param tasks the task definition of the state + * @param tsLogic the task selection logic of the state + * @param finalizerLogics the finalizer logics for the state + * @param ctxRefs any context reference for the state + * @return a CLI command for a policy state definition + */ + public ST createPolicyStateDef(final String policyName, final String version, final String stateName, + final String triggerName, final String triggerVersion, final String defaultTask, + final String defaultTaskVersion, final List outputs, final List tasks, final List tsLogic, + final List finalizerLogics, final List ctxRefs) { + final ST st = stg.getInstanceOf("policyStateDef"); + st.add(POLICY_NAME, policyName); + st.add(VERSION, version); + st.add(STATE_NAME, stateName); + st.add(TRIGGER_NAME, triggerName); + st.add(TRIGGER_VERSION, triggerVersion); + st.add(DEFAULT_TASK, defaultTask); + st.add(DEFAULT_TASK_VERSION, defaultTaskVersion); + st.add(OUTPUTS, outputs); + st.add(TASKS, tasks); + st.add(TS_LOGIC, tsLogic); + st.add(FINALIZER_LOGICS, finalizerLogics); + st.add(CTX_REFS, ctxRefs); + return st; + } + + /** + * Creates a new task selection logic definition for a state which belongs to a policy. + * + * @param name the name of the policy + * @param version the version of the policy + * @param stateName the name of the state + * @param logicFlavour the flavour, e.g. JAVA or JAVASCRIPT + * @param logic the actual logic (use either a string or a multi-line with + * LS some code LE + * @return a CLI command for task selection logic definition + */ + public ST createPolicyStateDefTaskSelLogic(final String name, final String version, final String stateName, + final String logicFlavour, final String logic) { + final ST st = stg.getInstanceOf("policyStateTaskSelectionLogic"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(STATE_NAME, stateName); + st.add(LOGIC_FLAVOUR, logicFlavour); + st.add(LOGIC, logic); + return st; + } + + /** + * Creates a new state finalizer definition for a state which belongs to a policy. + * + * @param name the name of the policy + * @param version the version of the policy + * @param stateName the name of the state + * @param finalizerLogicName name of the finalizer logic + * @param logicFlavour the flavour, e.g. JAVA or JAVASCRIPT + * @param logic the actual logic (use either a string or a multi-line with + * LS some code LE + * @return a CLI command for finalizer definition + */ + public ST createPolicyStateDefFinalizerLogic(final String name, final String version, final String stateName, + final String finalizerLogicName, final String logicFlavour, final String logic) { + final ST st = stg.getInstanceOf("policyStateFinalizerLogic"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(STATE_NAME, stateName); + st.add(FINALIZER_LOGIC_NAME, finalizerLogicName); + st.add(LOGIC_FLAVOUR, logicFlavour); + st.add(LOGIC, logic); + return st; + } + + /** + * Creates a new policy state context reference for a state which belongs to a policy. + * + * @param name the name of the policy + * @param version the version of the policy + * @param stateName the name of the state + * @param albumName the name of the album + * @param albumVersion the version of the album + * @return a CLI command for state context reference + */ + public ST createPolicyStateDefContextRef(final String name, final String version, final String stateName, + final String albumName, final String albumVersion) { + final ST st = stg.getInstanceOf("policyStateContextRef"); + st.add(NAME, name); + st.add(VERSION, version); + st.add(STATE_NAME, stateName); + st.add(ALBUM_NAME, albumName); + st.add(ALBUM_VERSION, albumVersion); + return st; + } + +} diff --git a/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestGeneration.java b/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestGeneration.java new file mode 100644 index 000000000..851c06631 --- /dev/null +++ b/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestGeneration.java @@ -0,0 +1,138 @@ +/*- + * ============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.auth.clicodegen; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.Test; +import org.onap.policy.apex.auth.clicodegen.CodeGeneratorCliEditor; +import org.stringtemplate.v4.STGroup; +import org.stringtemplate.v4.STGroupFile; + +/** + * Test for the CG CLI Editor STG file. + * + * @author Sven van der Meer (sven.van.der.meer@ericsson.com) + */ +public class TestGeneration { + + /** + * Get the chunks for the codegen. + * + * @return the chunks + */ + private static Map> getCodeGenChunks() { + // CHECKSTYLE:OFF: LineLength + + final Map> chunks = new LinkedHashMap<>(); + + chunks.put("/policyModel", + Arrays.asList("name", "version", "uuid", "description", "declarations", "definitions")); + chunks.put("/schemaDecl", Arrays.asList("name", "version", "uuid", "description", "flavour", "schema")); + chunks.put("/ctxAlbumDecl", Arrays.asList("name", "version", "uuid", "description", "scope", "writable", + "schemaName", "schemaVersion")); + chunks.put("/eventDecl", + Arrays.asList("name", "version", "uuid", "description", "nameSpace", "source", "target", "fields")); + chunks.put("/eventDefField", + Arrays.asList("eventName", "version", "fieldName", "fieldSchema", "fieldSchemaVersion", "optional")); + chunks.put("/taskDecl", + Arrays.asList("name", "version", "uuid", "description", "infields", "outfields", "logic")); + chunks.put("/taskDefInputFields", + Arrays.asList("taskName", "version", "fieldName", "fieldSchema", "fieldSchemaVersion")); + chunks.put("/taskDefOutputFields", + Arrays.asList("taskName", "version", "fieldName", "fieldSchema", "fieldSchemaVersion")); + chunks.put("/taskDefLogic", Arrays.asList("taskName", "version", "flavour", "logic")); + chunks.put("/taskDefParameter", Arrays.asList("name", "version", "parName", "defaultValue")); + chunks.put("/taskDefCtxRef", Arrays.asList("name", "version", "albumName", "albumVersion")); + chunks.put("/policyDef", Arrays.asList("name", "version", "uuid", "description", "template", "firstState")); + chunks.put("/policyStateDef", Arrays.asList("policyName", "version", "stateName", "triggerName", + "triggerVersion", "defaultTask", "defaultTaskVersion", "outputs", "tasks")); + chunks.put("/policyStateOutput", Arrays.asList("policyName", "version", "stateName", "outputName", "eventName", + "eventVersion", "nextState")); + chunks.put("/policyStateTaskSelectionLogic", + Arrays.asList("name", "version", "stateName", "logicFlavour", "logic")); + chunks.put("/policyStateTask", Arrays.asList("policyName", "version", "stateName", "taskLocalName", "taskName", + "taskVersion", "outputType", "outputName")); + chunks.put("/policyStateFinalizerLogic", + Arrays.asList("name", "version", "stateName", "finalizerLogicName", "logicFlavour", "logic")); + chunks.put("/policyStateContextRef", + Arrays.asList("name", "version", "stateName", "albumName", "albumVersion")); + + return chunks; + // CHECKSTYLE:ON: LineLength + } + + /** Test STG load. */ + @Test + public void testGenerationLoad() { + final StErrorListener errListener = new StErrorListener(); + final STGroupFile stg = new STGroupFile(CodeGeneratorCliEditor.STG_FILE); + stg.setListener(errListener); + + stg.getTemplateNames(); // dummy to compile group and get errors + assertEquals(0, errListener.getErrorCount()); + } + + /** Test STG chunks. */ + @Test + public void testGenerationChunks() { + final StErrorListener errListener = new StErrorListener(); + final STGroupFile stg = new STGroupFile(CodeGeneratorCliEditor.STG_FILE); + stg.setListener(errListener); + + stg.getTemplateNames(); // dummy to compile group and get errors + final Map> chunks = getCodeGenChunks(); + String error = ""; + final Set definedNames = stg.getTemplateNames(); + for (final STGroup group : stg.getImportedGroups()) { + definedNames.addAll(group.getTemplateNames()); + } + final Set requiredNames = chunks.keySet(); + + for (final String required : requiredNames) { + if (!definedNames.contains(required)) { + error += " - target STG does not define template for <" + required + ">\n"; + } else { + final Set definedParams = ((stg.getInstanceOf(required).getAttributes() == null) + ? new TreeSet() : stg.getInstanceOf(required).getAttributes().keySet()); + final List requiredParams = chunks.get(required); + for (final String reqArg : requiredParams) { + if (!definedParams.contains(reqArg)) { + error += " - target STG with template <" + required + "> does not define argument <" + reqArg + + ">\n"; + } + } + } + } + + if (!("".equals(error))) { + System.err.println(error); + } + assertEquals(0, error.length()); + } +} diff --git a/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestSTG.java b/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestSTG.java deleted file mode 100644 index 1fbc78de9..000000000 --- a/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/TestSTG.java +++ /dev/null @@ -1,138 +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.auth.clicodegen; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.junit.Test; -import org.onap.policy.apex.auth.clicodegen.CGCliEditor; -import org.stringtemplate.v4.STGroup; -import org.stringtemplate.v4.STGroupFile; - -/** - * Test for the CG CLI Editor STG file. - * - * @author Sven van der Meer (sven.van.der.meer@ericsson.com) - */ -public class TestSTG { - - /** - * Get the chunks for the codegen. - * - * @return the chunks - */ - private static Map> getCodeGenChunks() { - // CHECKSTYLE:OFF: LineLength - - final Map> chunks = new LinkedHashMap<>(); - - chunks.put("/policyModel", - Arrays.asList("name", "version", "uuid", "description", "declarations", "definitions")); - chunks.put("/schemaDecl", Arrays.asList("name", "version", "uuid", "description", "flavour", "schema")); - chunks.put("/ctxAlbumDecl", Arrays.asList("name", "version", "uuid", "description", "scope", "writable", - "schemaName", "schemaVersion")); - chunks.put("/eventDecl", - Arrays.asList("name", "version", "uuid", "description", "nameSpace", "source", "target", "fields")); - chunks.put("/eventDefField", - Arrays.asList("eventName", "version", "fieldName", "fieldSchema", "fieldSchemaVersion", "optional")); - chunks.put("/taskDecl", - Arrays.asList("name", "version", "uuid", "description", "infields", "outfields", "logic")); - chunks.put("/taskDefInputFields", - Arrays.asList("taskName", "version", "fieldName", "fieldSchema", "fieldSchemaVersion")); - chunks.put("/taskDefOutputFields", - Arrays.asList("taskName", "version", "fieldName", "fieldSchema", "fieldSchemaVersion")); - chunks.put("/taskDefLogic", Arrays.asList("taskName", "version", "flavour", "logic")); - chunks.put("/taskDefParameter", Arrays.asList("name", "version", "parName", "defaultValue")); - chunks.put("/taskDefCtxRef", Arrays.asList("name", "version", "albumName", "albumVersion")); - chunks.put("/policyDef", Arrays.asList("name", "version", "uuid", "description", "template", "firstState")); - chunks.put("/policyStateDef", Arrays.asList("policyName", "version", "stateName", "triggerName", - "triggerVersion", "defaultTask", "defaultTaskVersion", "outputs", "tasks")); - chunks.put("/policyStateOutput", Arrays.asList("policyName", "version", "stateName", "outputName", "eventName", - "eventVersion", "nextState")); - chunks.put("/policyStateTaskSelectionLogic", - Arrays.asList("name", "version", "stateName", "logicFlavour", "logic")); - chunks.put("/policyStateTask", Arrays.asList("policyName", "version", "stateName", "taskLocalName", "taskName", - "taskVersion", "outputType", "outputName")); - chunks.put("/policyStateFinalizerLogic", - Arrays.asList("name", "version", "stateName", "finalizerLogicName", "logicFlavour", "logic")); - chunks.put("/policyStateContextRef", - Arrays.asList("name", "version", "stateName", "albumName", "albumVersion")); - - return chunks; - // CHECKSTYLE:ON: LineLength - } - - /** Test STG load. */ - @Test - public void testSTGLoad() { - final StErrorListener errListener = new StErrorListener(); - final STGroupFile stg = new STGroupFile(CGCliEditor.STG_FILE); - stg.setListener(errListener); - - stg.getTemplateNames(); // dummy to compile group and get errors - assertEquals(0, errListener.getErrorCount()); - } - - /** Test STG chunks. */ - @Test - public void testSTGChunks() { - final StErrorListener errListener = new StErrorListener(); - final STGroupFile stg = new STGroupFile(CGCliEditor.STG_FILE); - stg.setListener(errListener); - - stg.getTemplateNames(); // dummy to compile group and get errors - final Map> chunks = getCodeGenChunks(); - String error = ""; - final Set definedNames = stg.getTemplateNames(); - for (final STGroup group : stg.getImportedGroups()) { - definedNames.addAll(group.getTemplateNames()); - } - final Set requiredNames = chunks.keySet(); - - for (final String required : requiredNames) { - if (!definedNames.contains(required)) { - error += " - target STG does not define template for <" + required + ">\n"; - } else { - final Set definedParams = ((stg.getInstanceOf(required).getAttributes() == null) - ? new TreeSet() : stg.getInstanceOf(required).getAttributes().keySet()); - final List requiredParams = chunks.get(required); - for (final String reqArg : requiredParams) { - if (!definedParams.contains(reqArg)) { - error += " - target STG with template <" + required + "> does not define argument <" + reqArg - + ">\n"; - } - } - } - } - - if (!("".equals(error))) { - System.err.println(error); - } - assertEquals(0, error.length()); - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCLIEditorMain.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCLIEditorMain.java deleted file mode 100644 index 718c75a96..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCLIEditorMain.java +++ /dev/null @@ -1,195 +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.auth.clieditor; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Set; -import java.util.TreeSet; - -import org.onap.policy.apex.model.utilities.json.JsonHandler; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class initiates an Apex CLI editor from a java main method. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexCLIEditorMain { - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexCLIEditorMain.class); - - // The editor parameters - private CLIParameters parameters; - - // The CLI commands read in from JSON - private CLICommands commands; - - // The Apex model properties read in from JSON - private ApexModelProperties apexModelProperties; - - // The number of errors encountered in command processing - private int errorCount = 0; - - /** - * Instantiates the Apex CLI editor. - * - * @param args the command line arguments - */ - public ApexCLIEditorMain(final String[] args) { - LOGGER.info("Starting Apex CLI editor {} . . .", Arrays.toString(args)); - - try { - final CLIParameterParser parser = new CLIParameterParser(); - parameters = parser.parse(args); - - if (parameters.isHelpSet()) { - parser.help(ApexCLIEditorMain.class.getCanonicalName()); - return; - } - parameters.validate(); - } catch (final Exception e) { - LOGGER.error("start of Apex command line editor failed, ", e); - errorCount++; - return; - } - - LOGGER.debug("parameters are: {}", parameters.toString()); - - // Read the command definitions - try { - commands = new JsonHandler().read(CLICommands.class, parameters.getMetadataStream()); - } catch (final Exception e) { - LOGGER.error("start of Apex command line editor failed, error reading command metadata from {}", - parameters.getMetadataLocation(), e); - errorCount++; - return; - } - - // The JSON processing returns null if there is an empty file - if (commands == null || commands.getCommandSet().isEmpty()) { - LOGGER.error("start of Apex command line editor failed, no commands found in {}", - parameters.getApexPropertiesLocation()); - errorCount++; - return; - } - - LOGGER.debug("found {} commands", commands.getCommandSet().size()); - - // Read the Apex properties - try { - apexModelProperties = new JsonHandler().read(ApexModelProperties.class, - parameters.getApexPropertiesStream()); - } catch (final Exception e) { - LOGGER.error("start of Apex command line editor failed, error reading Apex model properties from " - + parameters.getApexPropertiesLocation()); - LOGGER.error(e.getMessage()); - errorCount++; - return; - } - - // The JSON processing returns null if there is an empty file - if (apexModelProperties == null) { - LOGGER.error("start of Apex command line editor failed, no Apex model properties found in {}", - parameters.getApexPropertiesLocation()); - errorCount++; - return; - } - - LOGGER.debug("model properties are: {}", apexModelProperties.toString()); - - // Find the system commands - final Set systemCommandNodes = new TreeSet<>(); - for (final CLICommand command : commands.getCommandSet()) { - if (command.isSystemCommand()) { - systemCommandNodes.add(new KeywordNode(command.getName(), command)); - } - } - - // Read in the command hierarchy, this builds a tree of commands - final KeywordNode rootKeywordNode = new KeywordNode("root"); - for (final CLICommand command : commands.getCommandSet()) { - rootKeywordNode.processKeywords(command.getKeywordlist(), command); - } - rootKeywordNode.addSystemCommandNodes(systemCommandNodes); - - // Create the model we will work towards - ApexModelHandler modelHandler = null; - try { - modelHandler = - new ApexModelHandler(apexModelProperties.getProperties(), parameters.getInputModelFileName()); - } catch (final Exception e) { - LOGGER.error("execution of Apex command line editor failed: ", e); - errorCount++; - return; - } - - final CLIEditorLoop cliEditorLoop = - new CLIEditorLoop(apexModelProperties.getProperties(), modelHandler, rootKeywordNode); - try { - errorCount = - cliEditorLoop.runLoop(parameters.getCommandInputStream(), parameters.getOutputStream(), parameters); - - if (errorCount == 0) { - LOGGER.info("Apex CLI editor completed execution"); - } else { - LOGGER.error("execution of Apex command line editor failed: {} command execution failure(s) occurred", - errorCount); - } - } catch (final IOException e) { - LOGGER.error("execution of Apex command line editor failed: " + e.getMessage()); - } - } - - /** - * Get the number of errors encountered in command processing. - * - * @return the number of errors - */ - public int getErrorCount() { - return errorCount; - } - - /** - * Sets the number of errors encountered in command processing. - * - * @param errorCount the number of errors - */ - public void setErrorCount(final int errorCount) { - this.errorCount = errorCount; - } - - - /** - * The main method, kicks off the editor. - * - * @param args the arguments - */ - public static void main(final String[] args) { - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(args); - - // Only call system.exit on errors as it brings the JVM down - if (cliEditor.getErrorCount() > 0) { - System.exit(cliEditor.getErrorCount()); - } - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCommandLineEditorMain.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCommandLineEditorMain.java new file mode 100644 index 000000000..0df8ac629 --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCommandLineEditorMain.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.auth.clieditor; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Set; +import java.util.TreeSet; + +import org.onap.policy.apex.model.utilities.json.JsonHandler; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class initiates an Apex CLI editor from a java main method. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexCommandLineEditorMain { + // Get a reference to the logger + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexCommandLineEditorMain.class); + + // The editor parameters + private CommandLineParameters parameters; + + // The CLI commands read in from JSON + private CommandLineCommands commands; + + // The Apex model properties read in from JSON + private ApexModelProperties apexModelProperties; + + // The number of errors encountered in command processing + private int errorCount = 0; + + /** + * Instantiates the Apex CLI editor. + * + * @param args the command line arguments + */ + public ApexCommandLineEditorMain(final String[] args) { + String startMessage = "Starting Apex CLI editor " + Arrays.toString(args) + " . . ."; + LOGGER.info(startMessage); + + try { + final CommandLineParameterParser parser = new CommandLineParameterParser(); + parameters = parser.parse(args); + + if (parameters.isHelpSet()) { + parser.help(ApexCommandLineEditorMain.class.getCanonicalName()); + return; + } + parameters.validate(); + } catch (final Exception e) { + LOGGER.error("start of Apex command line editor failed, ", e); + errorCount++; + return; + } + + String message = "parameters are: " + parameters.toString(); + LOGGER.debug(message); + + // Read the command definitions + try { + commands = new JsonHandler().read(CommandLineCommands.class, + parameters.getMetadataStream()); + } catch (final Exception e) { + LOGGER.error("start of Apex command line editor failed, error reading command metadata from {}", + parameters.getMetadataLocation(), e); + errorCount++; + return; + } + + // The JSON processing returns null if there is an empty file + if (commands == null || commands.getCommandSet().isEmpty()) { + LOGGER.error("start of Apex command line editor failed, no commands found in {}", + parameters.getApexPropertiesLocation()); + errorCount++; + return; + } + + LOGGER.debug("found {} commands", commands.getCommandSet().size()); + + // Read the Apex properties + try { + apexModelProperties = new JsonHandler().read(ApexModelProperties.class, + parameters.getApexPropertiesStream()); + } catch (final Exception e) { + LOGGER.error("start of Apex command line editor failed, error reading Apex model properties from " + + parameters.getApexPropertiesLocation()); + LOGGER.error(e.getMessage()); + errorCount++; + return; + } + + // The JSON processing returns null if there is an empty file + if (apexModelProperties == null) { + LOGGER.error("start of Apex command line editor failed, no Apex model properties found in {}", + parameters.getApexPropertiesLocation()); + errorCount++; + return; + } + + String modelPropertiesString = "model properties are: " + apexModelProperties.toString(); + LOGGER.debug(modelPropertiesString); + + // Find the system commands + final Set systemCommandNodes = new TreeSet<>(); + for (final CommandLineCommand command : commands.getCommandSet()) { + if (command.isSystemCommand()) { + systemCommandNodes.add(new KeywordNode(command.getName(), command)); + } + } + + // Read in the command hierarchy, this builds a tree of commands + final KeywordNode rootKeywordNode = new KeywordNode("root"); + for (final CommandLineCommand command : commands.getCommandSet()) { + rootKeywordNode.processKeywords(command.getKeywordlist(), command); + } + rootKeywordNode.addSystemCommandNodes(systemCommandNodes); + + // Create the model we will work towards + ApexModelHandler modelHandler = null; + try { + modelHandler = new ApexModelHandler(apexModelProperties.getProperties(), + parameters.getInputModelFileName()); + } catch (final Exception e) { + LOGGER.error("execution of Apex command line editor failed: ", e); + errorCount++; + return; + } + + final CommandLineEditorLoop cliEditorLoop = new CommandLineEditorLoop(apexModelProperties.getProperties(), + modelHandler, rootKeywordNode); + try { + errorCount = cliEditorLoop.runLoop(parameters.getCommandInputStream(), parameters.getOutputStream(), + parameters); + + if (errorCount == 0) { + LOGGER.info("Apex CLI editor completed execution"); + } else { + LOGGER.error("execution of Apex command line editor failed: {} command execution failure(s) occurred", + errorCount); + } + } catch (final IOException e) { + LOGGER.error("execution of Apex command line editor failed: " + e.getMessage()); + } + } + + /** + * Get the number of errors encountered in command processing. + * + * @return the number of errors + */ + public int getErrorCount() { + return errorCount; + } + + /** + * Sets the number of errors encountered in command processing. + * + * @param errorCount the number of errors + */ + public void setErrorCount(final int errorCount) { + this.errorCount = errorCount; + } + + /** + * The main method, kicks off the editor. + * + * @param args the arguments + */ + public static void main(final String[] args) { + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(args); + + // Only call system.exit on errors as it brings the JVM down + if (cliEditor.getErrorCount() > 0) { + System.exit(cliEditor.getErrorCount()); + } + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexModelHandler.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexModelHandler.java index 2cf2633b2..2e1a4732b 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexModelHandler.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexModelHandler.java @@ -24,7 +24,7 @@ import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; -import java.util.TreeMap; +import java.util.SortedMap; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexModel; @@ -64,7 +64,7 @@ public class ApexModelHandler { final ApexApiResult result = apexModel.loadFromFile(modelFileName); if (result.isNok()) { - throw new CLIException(result.getMessages().get(0)); + throw new CommandLineException(result.getMessages().get(0)); } } @@ -76,8 +76,8 @@ public class ApexModelHandler { * @param writer A writer to which to write output * @return the result of the executed command */ - public ApexApiResult executeCommand(final CLICommand command, - final TreeMap argumentValues, final PrintWriter writer) { + public ApexApiResult executeCommand(final CommandLineCommand command, + final SortedMap argumentValues, final PrintWriter writer) { // Get the method final Method apiMethod = getCommandMethod(command); @@ -92,22 +92,22 @@ public class ApexModelHandler { writer.println(result); return result; } else { - throw new CLIException( - INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND - + command.getName() + "\" the returned object is not an instance of ApexAPIResult"); + throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + + FAILED_FOR_COMMAND + command.getName() + + "\" the returned object is not an instance of ApexAPIResult"); } } catch (IllegalAccessException | IllegalArgumentException e) { writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND - + command.getName() + "\""); + + command.getName() + "\""); e.printStackTrace(writer); - throw new CLIException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() - + FAILED_FOR_COMMAND + command.getName() + "\"", e); + throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND + + command.getName() + "\"", e); } catch (final InvocationTargetException e) { writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND - + command.getName() + "\""); + + command.getName() + "\""); e.getCause().printStackTrace(writer); - throw new CLIException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() - + FAILED_FOR_COMMAND + command.getName() + "\"", e); + throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND + + command.getName() + "\"", e); } } @@ -117,9 +117,9 @@ public class ApexModelHandler { * @param command The command * @return the API method */ - private Method getCommandMethod(final CLICommand command) { - final String className = command.getAPIClassName(); - final String methodName = command.getAPIMethodName(); + private Method getCommandMethod(final CommandLineCommand command) { + final String className = command.getApiClassName(); + final String methodName = command.getApiMethodName(); try { final Class apiClass = Class.forName(className); @@ -128,11 +128,11 @@ public class ApexModelHandler { return apiMethod; } } - throw new CLIException("specified method \"" + command.getApiMethod() + "\" not found for command \"" - + command.getName() + "\""); + throw new CommandLineException("specified method \"" + command.getApiMethod() + + "\" not found for command \"" + command.getName() + "\""); } catch (final ClassNotFoundException e) { - throw new CLIException("specified class \"" + command.getApiMethod() + "\" not found for command \"" - + command.getName() + "\""); + throw new CommandLineException("specified class \"" + command.getApiMethod() + "\" not found for command \"" + + command.getName() + "\""); } } @@ -144,26 +144,26 @@ public class ApexModelHandler { * @param apiMethod the method itself * @return the argument list */ - private Object[] getParameterArray(final CLICommand command, final TreeMap argumentValues, - final Method apiMethod) { + private Object[] getParameterArray(final CommandLineCommand command, + final SortedMap argumentValues, final Method apiMethod) { final Object[] parameterArray = new Object[argumentValues.size()]; - int i = 0; + int item = 0; try { for (final Class parametertype : apiMethod.getParameterTypes()) { - final String parameterValue = - argumentValues.get(command.getArgumentList().get(i).getArgumentName()).getValue(); + final String parameterValue = argumentValues.get(command.getArgumentList().get(item).getArgumentName()) + .getValue(); if (parametertype.equals(boolean.class)) { - parameterArray[i] = Boolean.valueOf(parameterValue); + parameterArray[item] = Boolean.valueOf(parameterValue); } else { - parameterArray[i] = parameterValue; + parameterArray[item] = parameterValue; } - i++; + item++; } } catch (final Exception e) { - throw new CLIException("number of argument mismatch on method \"" + command.getApiMethod() - + "\" for command \"" + command.getName() + "\""); + throw new CommandLineException("number of argument mismatch on method \"" + command.getApiMethod() + + "\" for command \"" + command.getName() + "\""); } return parameterArray; diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgument.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgument.java deleted file mode 100644 index b215f69e4..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgument.java +++ /dev/null @@ -1,144 +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.auth.clieditor; - -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class holds the definition of an argument of a CLI command. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLIArgument implements Comparable { - private final String argumentName; - private final boolean nullable; - private final String description; - - /** - * This Constructor constructs a non nullable command line argument with a blank name and - * description. - */ - public CLIArgument() { - this("", false, ""); - } - - /** - * This Constructor constructs a non nullable command line argument with the given name and - * description. - * - * @param incomingArgumentName the argument name - */ - public CLIArgument(final String incomingArgumentName) { - this(incomingArgumentName, false, ""); - } - - /** - * This Constructor constructs a command line argument with the given name, nullability, and - * description. - * - * @param argumentName the argument name - * @param nullable the nullable - * @param description the description - */ - public CLIArgument(final String argumentName, final boolean nullable, final String description) { - this.argumentName = argumentName; - this.nullable = nullable; - this.description = description; - } - - /** - * Gets the argument name. - * - * @return the argument name - */ - public String getArgumentName() { - return argumentName; - } - - /** - * Checks if the argument is nullable. - * - * @return true, if checks if the argument is nullable - */ - public boolean isNullable() { - return nullable; - } - - /** - * Gets the argument description. - * - * @return the argument description - */ - public String getDescription() { - return description; - } - - /** - * Gets the argument help. - * - * @return the argument help - */ - public String getHelp() { - final StringBuilder builder = new StringBuilder(); - builder.append(argumentName); - builder.append(nullable ? ": (O) " : ": (M) "); - builder.append(description); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "CLIArgument [argumentName=" + argumentName + ", nullable=" + nullable + ", description=" + description - + "]"; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final CLIArgument otherArgument) { - Assertions.argumentNotNull(otherArgument, "comparison object may not be null"); - - if (this == otherArgument) { - return 0; - } - if (getClass() != otherArgument.getClass()) { - return this.hashCode() - otherArgument.hashCode(); - } - - final CLIArgument other = otherArgument; - - if (!argumentName.equals(other.argumentName)) { - return argumentName.compareTo(other.argumentName); - } - if (nullable != other.nullable) { - return (this.hashCode() - other.hashCode()); - } - return description.compareTo(otherArgument.description); - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgumentValue.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgumentValue.java deleted file mode 100644 index d87a8dc5b..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIArgumentValue.java +++ /dev/null @@ -1,91 +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.auth.clieditor; - -/** - * This class represents an argument used on a command and its value. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLIArgumentValue { - private final CLIArgument cliArgument; - private boolean specified; - private String value; - - /** - * The Constructor creates an argument value for the given argument, has not been set, and has - * no value. - * - * @param cliArgument the argument for which this object is a value - */ - public CLIArgumentValue(final CLIArgument cliArgument) { - this.cliArgument = cliArgument; - specified = false; - value = null; - } - - /** - * Gets the argument for which this object is a value. - * - * @return the argument for which this object is a value - */ - public CLIArgument getCliArgument() { - return cliArgument; - } - - /** - * Checks if the argument value is specified. - * - * @return true, if the argument value is specified - */ - public boolean isSpecified() { - return specified; - } - - /** - * Gets the argument value. - * - * @return the argument value - */ - public String getValue() { - return value; - } - - /** - * Sets the argument value. - * - * @param value the argument value - */ - public void setValue(final String value) { - this.value = value; - specified = true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "CLIArgumentValue [cliArgument=" + cliArgument + ", specified=" + specified + ", value=" + value + "]"; - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommand.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommand.java deleted file mode 100644 index 40c0a40a5..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommand.java +++ /dev/null @@ -1,240 +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.auth.clieditor; - -import java.util.ArrayList; -import java.util.List; - -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class represents a single Apex CLI command that is issued to the Apex Editor Java API - * {@link org.onap.policy.apex.model.modelapi.ApexEditorApi}. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLICommand implements Comparable { - private String name = ""; - private final List keywordlist = new ArrayList<>(); - private final List argumentList = new ArrayList<>(); - private String apiMethod = ""; - private boolean systemCommand = false; - private String description = ""; - - /** - * Gets the class name of the class that executes this command in the Java API. - * - * @return the class name of the class that executes this command in the Java API - */ - public String getAPIClassName() { - final int lastDotPos = apiMethod.lastIndexOf('.'); - if (lastDotPos == -1) { - throw new CLIException("invalid API method name specified on command \"" + name - + "\", class name not found: " + apiMethod); - } - return apiMethod.substring(0, lastDotPos); - } - - /** - * Gets the method name of the method that executes this command in the Java API. - * - * @return the the method name of the method that executes this command in the Java API - */ - public String getAPIMethodName() { - final int lastDotPos = apiMethod.lastIndexOf('.'); - if (lastDotPos == -1) { - throw new CLIException("invalid API method name specified on command \"" + name - + "\", class name not found: " + apiMethod); - } - if (lastDotPos == apiMethod.length() - 1) { - throw new CLIException("no API method name specified on command \"" + name + "\": " + apiMethod); - } - return apiMethod.substring(lastDotPos + 1); - } - - /** - * Gets the name of the editor command. - * - * @return the name of the editor command - */ - public String getName() { - return name; - } - - /** - * Sets the name of the editor command. - * - * @param name the name of the editor command - */ - public void setName(final String name) { - this.name = name; - } - - /** - * Gets the list of keywords for this command. - * - * @return the list of keywords for this command - */ - public List getKeywordlist() { - return keywordlist; - } - - /** - * Gets the list of arguments for this command. - * - * @return the list of arguments for this command - */ - public List getArgumentList() { - return argumentList; - } - - /** - * Gets the method of the method that executes this command in the Java API. - * - * @return the method of the method that executes this command in the Java API - */ - public String getApiMethod() { - return apiMethod; - } - - /** - * Sets the method of the method that executes this command in the Java API. - * - * @param apiMethod the method of the method that executes this command in the Java API - */ - public void setApiMethod(final String apiMethod) { - this.apiMethod = apiMethod; - } - - /** - * Gets the description of the command. - * - * @return the description of the command - */ - public String getDescription() { - return description; - } - - /** - * Sets the description of the command. - * - * @param description the description of the command - */ - public void setDescription(final String description) { - this.description = description; - } - - /** - * Checks if this command is a system command. - * - * @return true, if this command is a system command - */ - public boolean isSystemCommand() { - return systemCommand; - } - - /** - * Sets whether this command is a system command. - * - * @param systemCommand whether this command is a system command - */ - public void setSystemCommand(final boolean systemCommand) { - this.systemCommand = systemCommand; - } - - /** - * Gets help for this command. - * - * @return the help for this command - */ - public String getHelp() { - final StringBuilder builder = new StringBuilder(); - for (final String keyword : keywordlist) { - builder.append(keyword); - builder.append(' '); - } - builder.append('{'); - builder.append(name); - builder.append("}: "); - builder.append(description); - - for (final CLIArgument argument : argumentList) { - if (argument == null) { - continue; - } - builder.append("\n\t"); - builder.append(argument.getHelp()); - } - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "CLICommand [name=" + name + ",keywordlist=" + keywordlist + ", argumentList=" + argumentList - + ", apiMethod=" + apiMethod + ", systemCommand=" + systemCommand + ", description=" + description - + "]"; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final CLICommand otherCommand) { - Assertions.argumentNotNull(otherCommand, "comparison object may not be null"); - - if (this == otherCommand) { - return 0; - } - if (getClass() != otherCommand.getClass()) { - return this.hashCode() - otherCommand.hashCode(); - } - - final CLICommand other = otherCommand; - - for (int i = 0, j = 0;; i++, j++) { - if (i < keywordlist.size() && j < otherCommand.keywordlist.size()) { - if (!keywordlist.get(i).equals(other.keywordlist.get(j))) { - return keywordlist.get(i).compareTo(other.keywordlist.get(j)); - } - } else if (i == keywordlist.size() && j == otherCommand.keywordlist.size()) { - break; - } else if (i == keywordlist.size()) { - return -1; - } else { - return 1; - } - } - if (!argumentList.equals(other.argumentList)) { - return (argumentList.hashCode() - other.argumentList.hashCode()); - } - if (systemCommand != other.systemCommand) { - return (this.hashCode() - other.hashCode()); - } - return apiMethod.compareTo(other.apiMethod); - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommands.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommands.java deleted file mode 100644 index 4c9bab045..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLICommands.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.auth.clieditor; - -import java.util.Set; -import java.util.TreeSet; - -/** - * This class contains the CLI commands read in from a JSON file. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLICommands { - private final Set commandList = new TreeSet<>(); - - /** - * Gets the command set. - * - * @return the command set - */ - public Set getCommandSet() { - return commandList; - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIEditorLoop.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIEditorLoop.java deleted file mode 100644 index a574099bf..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIEditorLoop.java +++ /dev/null @@ -1,543 +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.auth.clieditor; - -import static org.onap.policy.apex.model.utilities.TreeMapUtils.findMatchingEntries; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.AbstractMap.SimpleEntry; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.TreeMap; - -import org.onap.policy.apex.model.modelapi.ApexApiResult; -import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.model.utilities.TreeMapUtils; - -/** - * This class implements the editor loop, the loop of execution that continuously executes commands - * until the quit command is issued or EOF is detected on input. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLIEditorLoop { - // The model handler that is handling the API towards the Apex model being editied - private final ApexModelHandler modelHandler; - - // Holds the current location in the keyword hierarchy - private final ArrayDeque keywordNodeDeque = new ArrayDeque<>(); - - // Logic block tags - private final String logicBlockStartTag; - private final String logicBlockEndTag; - - // File Macro tag - private final String macroFileTag; - - /** - * Initiate the loop with the keyword node tree. - * - * @param properties The CLI editor properties defined for execution - * @param modelHandler the model handler that will handle commands - * @param rootKeywordNode The root keyword node tree - */ - public CLIEditorLoop(final Properties properties, final ApexModelHandler modelHandler, - final KeywordNode rootKeywordNode) { - this.modelHandler = modelHandler; - keywordNodeDeque.push(rootKeywordNode); - - logicBlockStartTag = properties.getProperty("DEFAULT_LOGIC_BLOCK_START_TAG"); - logicBlockEndTag = properties.getProperty("DEFAULT_LOGIC_BLOCK_END_TAG"); - macroFileTag = properties.getProperty("DEFAULT_MACRO_FILE_TAG"); - } - - /** - * Run a command loop. - * - * @param inputStream The stream to read commands from - * @param outputStream The stream to write command output and messages to - * @param parameters The parameters for the CLI editor - * @return the exit code from command processing - * @throws IOException Thrown on exceptions on IO - */ - public int runLoop(final InputStream inputStream, final OutputStream outputStream, final CLIParameters parameters) - throws IOException { - // Readers and writers for input and output - final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - final PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream)); - - // The parser parses the input lines into commands and arguments - final CLILineParser parser = new CLILineParser(); - - // The main loop for command handing, it continues until EOF on the input stream or until a - // quit command - int errorCount = 0; - ApexApiResult result = new ApexApiResult(); - while (result.getResult() != Result.FINISHED) { - if (!parameters.isIgnoreCommandFailures() && errorCount > 0) { - break; - } - - // Output prompt and get a line of input - writer.print(getPrompt()); - writer.flush(); - String line = reader.readLine(); - if (line == null) { - break; - } - - // Expand any macros in the script - try { - while (line.contains(macroFileTag)) { - line = expandMacroFile(parameters, line); - } - } - // Print any error messages from command parsing and finding - catch (final CLIException e) { - writer.println(e.getMessage()); - errorCount++; - continue; - } - - if (parameters.isEchoSet()) { - writer.println(line); - } - - String logicBlock = null; - if (line.trim().endsWith(logicBlockStartTag)) { - line = line.replace(logicBlockStartTag, "").trim(); - - logicBlock = ""; - while (true) { - String logicLine = reader.readLine(); - if (logicLine == null) { - logicBlock = null; - break; - } - - try { - while (logicLine.contains(macroFileTag)) { - logicLine = expandMacroFile(parameters, logicLine); - } - } - // Print any error messages from command parsing and finding - catch (final CLIException e) { - writer.println(e.getMessage()); - errorCount++; - continue; - } - - if (parameters.isEchoSet()) { - writer.println(logicLine); - } - - if (logicLine.trim().endsWith(logicBlockEndTag)) { - logicBlock += logicLine.replace(logicBlockEndTag, "").trim() + "\n"; - break; - } else { - logicBlock += logicLine + "\n"; - } - } - } - - try { - // Parse the line into a list of commands and arguments - final List commandWords = parser.parse(line, logicBlock); - - // Find the command, if the command is null, then we are simply changing position in - // the hierarchy - final CLICommand command = findCommand(commandWords); - if (command != null) { - // Check the arguments of the command - final TreeMap argumentValues = getArgumentValues(command, commandWords); - - // Execute the command, a FINISHED result means a command causes the loop to - // leave execution - result = executeCommand(command, argumentValues, writer); - if (result.isNok()) { - errorCount++; - } - } - } - // Print any error messages from command parsing and finding - catch (final CLIException e) { - writer.println(e.getMessage()); - errorCount++; - } catch (final Exception e) { - e.printStackTrace(writer); - } - } - - // Get the output model - if (!parameters.isSuppressModelOutputSet()) { - final String modelString = modelHandler.writeModelToString(writer); - - if (parameters.checkSetOutputModelFileName()) { - TextFileUtils.putStringAsTextFile(modelString, parameters.getOutputModelFileName()); - } else { - System.out.println(modelString); - } - } - - reader.close(); - writer.close(); - - return errorCount; - } - - /** - * Output a prompt that indicates where in the keyword hierarchy we are. - * - * @return A string with the prompt - */ - private String getPrompt() { - final StringBuilder builder = new StringBuilder(); - final Iterator keynodeDequeIter = keywordNodeDeque.descendingIterator(); - - while (keynodeDequeIter.hasNext()) { - builder.append('/'); - builder.append(keynodeDequeIter.next().getKeyword()); - } - builder.append("> "); - - return builder.toString(); - } - - /** - * Finds a command for the given input command words. Command words need only ne specified - * enough to uniquely identify them. Therefore, "p s o c" will find the command "policy state - * output create" - * - * @param commandWords The commands and arguments parsed from the command line by the parser - * @return The found command - */ - - private CLICommand findCommand(final List commandWords) { - CLICommand command = null; - - final KeywordNode startKeywordNode = keywordNodeDeque.peek(); - - // Go down through the keywords searching for the command - for (int i = 0; i < commandWords.size(); i++) { - final KeywordNode searchKeywordNode = keywordNodeDeque.peek(); - - // We have got to the arguments, time to stop looking - if (commandWords.get(i).indexOf('=') > 0) { - unwindStack(startKeywordNode); - throw new CLIException("command not found: " + stringAL2String(commandWords)); - } - - // If the node entries found is not equal to one, then we have either no command or more - // than one command matching - final List> foundNodeEntries = - findMatchingEntries(searchKeywordNode.getChildren(), commandWords.get(i)); - if (foundNodeEntries.isEmpty()) { - unwindStack(startKeywordNode); - throw new CLIException("command not found: " + stringAL2String(commandWords)); - } else if (foundNodeEntries.size() > 1) { - unwindStack(startKeywordNode); - throw new CLIException("multiple commands matched: " + stringAL2String(commandWords) + " [" - + nodeAL2String(foundNodeEntries) + ']'); - } - - // Record the fully expanded command word - commandWords.set(i, foundNodeEntries.get(0).getKey()); - - // Check if there is a command - final KeywordNode childKeywordNode = foundNodeEntries.get(0).getValue(); - command = childKeywordNode.getCommand(); - - // If the command is null, we go into a sub mode, otherwise we unwind the stack of - // commands and return the found command - if (command == null) { - keywordNodeDeque.push(childKeywordNode); - } else { - unwindStack(startKeywordNode); - return command; - } - } - - return null; - } - - /** - * Unwind the stack of keyword node entries we have placed on the queue in a command search. - * - * @param startKeywordNode The point on the queue we want to unwind to - */ - private void unwindStack(final KeywordNode startKeywordNode) { - // Unwind the stack - while (true) { - if (keywordNodeDeque.peek().equals(startKeywordNode)) { - return; - } - keywordNodeDeque.pop(); - } - } - - /** - * Check the arguments of the command. - * - * @param command The command to check - * @param commandWords The command words entered - * @return the argument values - */ - private TreeMap getArgumentValues(final CLICommand command, - final List commandWords) { - final TreeMap argumentValues = new TreeMap<>(); - for (final CLIArgument argument : command.getArgumentList()) { - if (argument != null) { - argumentValues.put(argument.getArgumentName(), new CLIArgumentValue(argument)); - } - } - - // Set the value of the arguments - for (final Entry argument : getCommandArguments(commandWords)) { - final List> foundArguments = - TreeMapUtils.findMatchingEntries(argumentValues, argument.getKey()); - if (foundArguments.size() == 0) { - throw new CLIException("command " + stringAL2String(commandWords) + ": " + " argument \"" - + argument.getKey() + "\" not allowed on command"); - } else if (foundArguments.size() > 1) { - throw new CLIException("command " + stringAL2String(commandWords) + ": " + " argument " + argument - + " matches multiple arguments [" + argumentAL2String(foundArguments) + ']'); - } - - // Set the value of the argument, stripping off any quotes - final String argumentValue = argument.getValue().replaceAll("^\"", "").replaceAll("\"$", ""); - foundArguments.get(0).getValue().setValue(argumentValue); - } - - // Now check all mandatory arguments are set - for (final CLIArgumentValue argumentValue : argumentValues.values()) { - // Argument values are null by default so if this argument is not nullable it is - // mandatory - if (!argumentValue.isSpecified() && !argumentValue.getCliArgument().isNullable()) { - throw new CLIException("command " + stringAL2String(commandWords) + ": " + " mandatory argument \"" - + argumentValue.getCliArgument().getArgumentName() + "\" not specified"); - } - } - - return argumentValues; - } - - /** - * Get the arguments of the command, the command words have already been conditioned into an - * array starting with the command words and ending with the arguments as name=value tuples. - * - * @param commandWords The command words entered by the user - * @return the arguments as an entry array list - */ - private ArrayList> getCommandArguments(final List commandWords) { - final ArrayList> arguments = new ArrayList<>(); - - // Iterate over the command words, arguments are of the format name=value - for (final String word : commandWords) { - final int equalsPos = word.indexOf('='); - if (equalsPos > 0) { - arguments.add( - new SimpleEntry<>(word.substring(0, equalsPos), word.substring(equalsPos + 1, word.length()))); - } - } - - return arguments; - } - - /** - * Execute system and editor commands. - * - * @param command The command to execute - * @param argumentValues The arguments input on the command line to invoke the command - * @param writer The writer to use for any output from the command - * @return the result of execution of the command - */ - private ApexApiResult executeCommand(final CLICommand command, - final TreeMap argumentValues, final PrintWriter writer) { - if (command.isSystemCommand()) { - return exceuteSystemCommand(command, writer); - } else { - return modelHandler.executeCommand(command, argumentValues, writer); - } - } - - /** - * Execute system commands. - * - * @param command The command to execute - * @param writer The writer to use for any output from the command - * @return the result of execution of the command - */ - private ApexApiResult exceuteSystemCommand(final CLICommand command, final PrintWriter writer) { - if ("back".equals(command.getName())) { - return executeBackCommand(); - } else if ("help".equals(command.getName())) { - return executeHelpCommand(writer); - } else if ("quit".equals(command.getName())) { - return executeQuitCommand(); - } else { - return new ApexApiResult(Result.SUCCESS); - } - } - - /** - * Execute the "back" command. - * - * @return the result of execution of the command - */ - private ApexApiResult executeBackCommand() { - if (keywordNodeDeque.size() > 1) { - keywordNodeDeque.pop(); - } - return new ApexApiResult(Result.SUCCESS); - } - - /** - * Execute the "quit" command. - * - * @return the result of execution of the command - */ - private ApexApiResult executeQuitCommand() { - return new ApexApiResult(Result.FINISHED); - } - - /** - * Execute the "help" command. - * - * @param writer The writer to use for output from the command - * @return the result of execution of the command - */ - private ApexApiResult executeHelpCommand(final PrintWriter writer) { - for (final CLICommand command : keywordNodeDeque.peek().getCommands()) { - writer.println(command.getHelp()); - } - return new ApexApiResult(Result.SUCCESS); - } - - /** - * Helper method to output an array list of keyword node entries to a string. - * - * @param nodeEntryArrayList the array list of keyword node entries - * @return the string - */ - private String nodeAL2String(final List> nodeEntryArrayList) { - final ArrayList stringArrayList = new ArrayList<>(); - for (final Entry node : nodeEntryArrayList) { - stringArrayList.add(node.getValue().getKeyword()); - } - - return stringAL2String(stringArrayList); - } - - /** - * Helper method to output an array list of argument entries to a string. - * - * @param argumentArrayList the argument array list - * @return the string - */ - private String argumentAL2String(final List> argumentArrayList) { - final ArrayList stringArrayList = new ArrayList<>(); - for (final Entry argument : argumentArrayList) { - stringArrayList.add(argument.getValue().getCliArgument().getArgumentName()); - } - - return stringAL2String(stringArrayList); - } - - /** - * Helper method to output an array list of strings to a string. - * - * @param stringArrayList the array list of strings - * @return the string - */ - private String stringAL2String(final List stringArrayList) { - final StringBuilder builder = new StringBuilder(); - boolean first = true; - for (final String word : stringArrayList) { - if (first) { - first = false; - } else { - builder.append(','); - } - builder.append(word); - } - - return builder.toString(); - } - - /** - * This method reads in the file from a file macro statement, expands the macro, and replaces - * the Macro tag in the line with the file contents. - * - * @param parameters The parameters for the CLI editor - * @param line The line with the macro keyword in it - * @return the expanded line - */ - private String expandMacroFile(final CLIParameters parameters, final String line) { - final int macroTagPos = line.indexOf(macroFileTag); - - // Get the line before and after the macro tag - final String lineBeforeMacroTag = line.substring(0, macroTagPos); - final String lineAfterMacroTag = line.substring(macroTagPos + macroFileTag.length()).replaceAll("^\\s*", ""); - - // Get the file name that is the argument of the Macro tag - final String[] lineWords = lineAfterMacroTag.split("\\s+"); - - if (lineWords.length == 0) { - throw new CLIException("no file name specified for Macro File Tag"); - } - - // Get the macro file name and the remainder of the line after the file name - String macroFileName = lineWords[0]; - final String lineAfterMacroFileName = lineAfterMacroTag.replaceFirst(macroFileName, ""); - - if (macroFileName.length() > 2 && macroFileName.startsWith("\"") && macroFileName.endsWith("\"")) { - macroFileName = macroFileName.substring(1, macroFileName.length() - 1); - } else { - throw new CLIException( - "macro file name \"" + macroFileName + "\" must exist and be quoted with double quotes \"\""); - } - - // Append the working directory to the macro file name - macroFileName = parameters.getWorkingDirectory() + File.separatorChar + macroFileName; - - // Now, get the text file for the argument of the macro - String macroFileContents = null; - try { - macroFileContents = TextFileUtils.getTextFileAsString(macroFileName); - } catch (final IOException e) { - throw new CLIException("file \"" + macroFileName + "\" specified in Macro File Tag not found", e); - } - - return lineBeforeMacroTag + macroFileContents + lineAfterMacroFileName; - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIException.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIException.java deleted file mode 100644 index 94b8c14a6..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIException.java +++ /dev/null @@ -1,49 +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.auth.clieditor; - -/** - * A run time exception used to report parsing and command input errors. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLIException extends IllegalArgumentException { - private static final long serialVersionUID = 6520231162404452427L; - - /** - * Create a CLIException with a message. - * - * @param message the message - */ - public CLIException(final String message) { - super(message); - } - - /** - * Create a CLIException with a message and an exception. - * - * @param message the message - * @param th the throwable - */ - public CLIException(final String message, final Throwable th) { - super(message, th); - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLILineParser.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLILineParser.java deleted file mode 100644 index 70c2f834b..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLILineParser.java +++ /dev/null @@ -1,323 +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.auth.clieditor; - -import java.util.ArrayList; -import java.util.List; - -/** - * This class chops a command line up into commands, parameters and arguments. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLILineParser { - - /** - * This method breaks a line of input up into commands, parameters, and arguments. Commands are - * standalone words at the beginning of the line, of which there may be multiple Parameters are - * single words followed by an '=' character Arguments are single words or a block of quoted - * text following an '=' character. - * - *

Format: command [command....] parameter=argument [parameter = argument] - * - *

Examples entity create name=hello description="description of hello" help entity list - * - * @param line The line to parse - * @param logicBlock A block of logic code to be taken literally - * @return the string array list - */ - public List parse(final String line, final String logicBlock) { - return checkFormat( - mergeArguments(mergeEquals( - splitOnEquals(stripAndSplitWords(mergeQuotes(splitOnChar(stripComments(line), '\"')))))), - logicBlock); - } - - /** - * Strip comments from lines, comments start with a # character. - * - * @param line the line - * @return the line without comments - */ - private String stripComments(final String line) { - final int commentPos = line.indexOf('#'); - if (commentPos == -1) { - return line; - } else { - return line.substring(0, commentPos); - } - } - - /** - * This method merges an array with separate quotes into an array with quotes delimiting the - * start and end of quoted words Example [Humpty ],["],[Dumpty sat on the wall],["],[, Humpty - * Dumpty had ],["],["],a ["],[great],["],[ fall] becomes [Humpty ],["Dumpty sat on the - * wall"],[, Humpty Dumpty had ],[""],[a],["great"],[ fall]. - * - * @param wordsSplitOnQuotes the words split on quotes - * @return the merged array list - */ - private ArrayList mergeQuotes(final ArrayList wordsSplitOnQuotes) { - final ArrayList wordsWithQuotesMerged = new ArrayList<>(); - - for (int i = 0; i < wordsSplitOnQuotes.size();) { - if ("\"".equals(wordsSplitOnQuotes.get(i))) { - StringBuilder quotedWord = new StringBuilder(wordsSplitOnQuotes.get(i++)); - - for (; i < wordsSplitOnQuotes.size(); i++) { - quotedWord.append(wordsSplitOnQuotes.get(i)); - if ("\"".equals(wordsSplitOnQuotes.get(i))) { - i++; - break; - } - } - String quotedWordToString = quotedWord.toString(); - if (quotedWordToString.matches("^\".*\"$")) { - wordsWithQuotesMerged.add(quotedWordToString); - } else { - throw new CLIException("trailing quote found in input " + wordsSplitOnQuotes); - } - } else { - wordsWithQuotesMerged.add(wordsSplitOnQuotes.get(i++)); - } - } - - return wordsWithQuotesMerged; - } - - /** - * This method splits the words on an array list into an array list where each portion of the - * line is split into words by '=', quoted words are ignored Example: aaa = bbb = ccc=ddd=eee = - * becomes [aaa ],[=],[bbb ],[=],[ccc],[=],[ddd],[=],[eee ],[=]. - * - * @param words the words - * @return the merged array list - */ - private ArrayList splitOnEquals(final ArrayList words) { - final ArrayList wordsSplitOnEquals = new ArrayList<>(); - - for (final String word : words) { - // Is this a quoted word ? - if (word.startsWith("\"")) { - wordsSplitOnEquals.add(word); - continue; - } - - // Split on equals character - final ArrayList splitWords = splitOnChar(word, '='); - for (final String splitWord : splitWords) { - wordsSplitOnEquals.add(splitWord); - } - } - - return wordsSplitOnEquals; - } - - /** - * This method merges an array with separate equals into an array with equals delimiting the - * start of words Example: [aaa ],[=],[bbb ],[=],[ccc],[=],[ddd],[=],[eee ],[=] becomes [aaa - * ],[= bbb ],[= ccc],[=ddd],[=eee ],[=]. - * - * @param wordsSplitOnEquals the words split on equals - * @return the merged array list - */ - private ArrayList mergeEquals(final ArrayList wordsSplitOnEquals) { - final ArrayList wordsWithEqualsMerged = new ArrayList<>(); - - for (int i = 0; i < wordsSplitOnEquals.size();) { - // Is this a quoted word ? - if (wordsSplitOnEquals.get(i).startsWith("\"")) { - wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i)); - continue; - } - - if ("=".equals(wordsSplitOnEquals.get(i))) { - if (i < wordsSplitOnEquals.size() - 1 && !wordsSplitOnEquals.get(i + 1).startsWith("=")) { - wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i) + wordsSplitOnEquals.get(i + 1)); - i += 2; - } else { - wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i++)); - } - } else { - wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i++)); - } - } - - return wordsWithEqualsMerged; - } - - /** - * This method merges words that start with an '=' character with the previous word if that word - * does not start with an '='. - * - * @param words the words - * @return the merged array list - */ - private ArrayList mergeArguments(final ArrayList words) { - final ArrayList mergedArguments = new ArrayList<>(); - - for (int i = 0; i < words.size(); i++) { - // Is this a quoted word ? - if (words.get(i).startsWith("\"")) { - mergedArguments.add(words.get(i)); - continue; - } - - if (words.get(i).startsWith("=")) { - if (i > 0 && !words.get(i - 1).startsWith("=")) { - mergedArguments.remove(mergedArguments.size() - 1); - mergedArguments.add(words.get(i - 1) + words.get(i)); - } else { - mergedArguments.add(words.get(i)); - } - } else { - mergedArguments.add(words.get(i)); - } - } - - return mergedArguments; - } - - /** - * This method strips all non quoted white space down to single spaces and splits non-quoted - * words into separate words. - * - * @param words the words - * @return the array list with white space stripped and words split - */ - private ArrayList stripAndSplitWords(final ArrayList words) { - final ArrayList strippedAndSplitWords = new ArrayList<>(); - - for (String word : words) { - // Is this a quoted word - if (word.startsWith("\"")) { - strippedAndSplitWords.add(word); - continue; - } - - // Strip white space by replacing all white space with blanks and then removing leading - // and trailing blanks - word = word.replaceAll("\\s+", " ").trim(); - - if (word.length() == 0) { - continue; - } - - // Split on space characters - final String[] splitWords = word.split(" "); - for (final String splitWord : splitWords) { - strippedAndSplitWords.add(splitWord); - } - } - - return strippedAndSplitWords; - } - - /** - * This method splits a line of text into an array list where each portion of the line is split - * into words by a character, with the characters themselves as separate words Example: Humpty - * "Dumpty sat on the wall", Humpty Dumpty had ""a "great" fall becomes [Humpty ],["],[Dumpty - * sat on the wall],["],[, Humpty Dumpty had ],["],["],a ["],[great],["],[ fall]. - * - * @param line the input line - * @param splitChar the split char - * @return the split array list - */ - private ArrayList splitOnChar(final String line, final char splitChar) { - final ArrayList wordsSplitOnQuotes = new ArrayList<>(); - - int currentPos = 0; - while (currentPos != -1) { - final int quotePos = line.indexOf(splitChar, currentPos); - if (quotePos != -1) { - if (currentPos < quotePos) { - wordsSplitOnQuotes.add(line.substring(currentPos, quotePos)); - } - wordsSplitOnQuotes.add("" + splitChar); - currentPos = quotePos + 1; - - if (currentPos == line.length()) { - currentPos = -1; - } - } else { - wordsSplitOnQuotes.add(line.substring(currentPos)); - currentPos = quotePos; - } - } - - return wordsSplitOnQuotes; - } - - /** - * This method checks that an array list containing a command is in the correct format. - * - * @param commandWords the command words - * @param logicBlock A block of logic code to be taken literally - * @return the checked array list - */ - private ArrayList checkFormat(final ArrayList commandWords, final String logicBlock) { - // There should be at least one word - if (commandWords.isEmpty()) { - return commandWords; - } - - // The first word must be alphanumeric, that is a command - if (!commandWords.get(0).matches("^[a-zA-Z0-9]*$")) { - throw new CLIException( - "first command word is not alphanumeric or is not a command: " + commandWords.get(0)); - } - - // Now check that we have a sequence of commands at the beginning - int currentWordPos = 0; - while (currentWordPos < commandWords.size()) { - if (commandWords.get(currentWordPos).matches("^[a-zA-Z0-9]*$")) { - currentWordPos++; - } else { - break; - } - } - - while (currentWordPos < commandWords.size()) { - // From now on we should have a sequence of parameters with arguments delimited by a - // single '=' character - if (currentWordPos < commandWords.size() - 1 || logicBlock == null) { - // No logic block - if (commandWords.get(currentWordPos).matches("^[a-zA-Z0-9]+=[a-zA-Z0-9/\"].*$")) { - currentWordPos++; - } else { - throw new CLIException( - "command argument is not properly formed: " + commandWords.get(currentWordPos)); - } - } else { - // Logic block - if (commandWords.get(currentWordPos).matches("^[a-zA-Z0-9]+=")) { - commandWords.set(currentWordPos, commandWords.get(currentWordPos) + logicBlock); - currentWordPos++; - } else { - throw new CLIException( - "command argument is not properly formed: " + commandWords.get(currentWordPos)); - } - } - } - - return commandWords; - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameterParser.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameterParser.java deleted file mode 100644 index 8a0c6eff3..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameterParser.java +++ /dev/null @@ -1,159 +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.auth.clieditor; - -import java.nio.file.Paths; -import java.util.Arrays; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; - -/** - * This class reads and handles command line parameters to the Apex CLI editor. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLIParameterParser { - private static final int MAX_HELP_LINE_LENGTH = 120; - - // Apache Commons CLI options - private final Options options; - - /** - * Construct the options for the CLI editor. - */ - public CLIParameterParser() { - options = new Options(); - options.addOption(Option.builder("h").longOpt("help").desc("outputs the usage of this command").required(false) - .type(Boolean.class).build()); - options.addOption(Option.builder("m").longOpt("metadata-file").desc("name of the command metadata file to use") - .hasArg().argName("CMD_METADATA_FILE").required(false).type(String.class).build()); - options.addOption( - Option.builder("a").longOpt("model-props-file").desc("name of the apex model properties file to use") - .hasArg().argName("MODEL_PROPS_FILE").required(false).type(String.class).build()); - options.addOption(Option.builder("c").longOpt("command-file") - .desc("name of a file containing editor commands to run into the editor").hasArg() - .argName("COMMAND_FILE").required(false).type(String.class).build()); - options.addOption(Option.builder("l").longOpt("log-file") - .desc("name of a file that will contain command logs from the editor, will log to standard output " - + "if not specified or suppressed with \"-nl\" flag") - .hasArg().argName("LOG_FILE").required(false).type(String.class).build()); - options.addOption(Option.builder("nl").longOpt("no-log") - .desc("if specified, no logging or output of commands to standard output or log file is carried out") - .required(false).type(Boolean.class).build()); - options.addOption(Option.builder("nm").longOpt("no-model-output") - .desc("if specified, no output of a model to standard output or model output file is carried out, " - + "the user can use the \"save\" command in a script to save a model") - .required(false).type(Boolean.class).build()); - options.addOption(Option.builder("i").longOpt("input-model-file") - .desc("name of a file that contains an input model for the editor").hasArg().argName("INPUT_MODEL_FILE") - .required(false).type(String.class).build()); - options.addOption(Option.builder("o").longOpt("output-model-file") - .desc("name of a file that will contain the output model for the editor, " - + "will output model to standard output if not specified or suppressed with \"-nm\" flag") - .hasArg().argName("OUTPUT_MODEL_FILE").required(false).type(String.class).build()); - options.addOption(Option.builder("if").longOpt("ignore-failures") - .desc("true or false, ignore failures of commands in command files and continue executing the " - + "command file") - .hasArg().argName("IGNORE_FAILURES_FLAG").required(false).type(Boolean.class).build()); - options.addOption(Option.builder("wd").longOpt("working-directory") - .desc("the working directory that is the root for the CLI editor and is the root from which to " - + "look for included macro files") - .hasArg().argName("WORKING_DIRECTORY").required(false).type(String.class).build()); - } - - /** - * Parse the command line options. - * - * @param args The arguments - * @return the CLI parameters - */ - public CLIParameters parse(final String[] args) { - CommandLine commandLine = null; - try { - commandLine = new DefaultParser().parse(options, args); - } catch (final ParseException e) { - throw new CLIException("invalid command line arguments specified : " + e.getMessage()); - } - - final CLIParameters parameters = new CLIParameters(); - final String[] remainingArgs = commandLine.getArgs(); - - if (remainingArgs.length > 0) { - throw new CLIException("too many command line arguments specified : " + Arrays.toString(remainingArgs)); - } - - if (commandLine.hasOption('h')) { - parameters.setHelp(true); - } - if (commandLine.hasOption('m')) { - parameters.setMetadataFileName(commandLine.getOptionValue('m')); - } - if (commandLine.hasOption('a')) { - parameters.setApexPorpertiesFileName(commandLine.getOptionValue('a')); - } - if (commandLine.hasOption('c')) { - parameters.setCommandFileName(commandLine.getOptionValue('c')); - } - if (commandLine.hasOption('l')) { - parameters.setLogFileName(commandLine.getOptionValue('l')); - } - if (commandLine.hasOption("nl")) { - parameters.setSuppressLog(true); - } - if (commandLine.hasOption("nm")) { - parameters.setSuppressModelOutput(true); - } - if (commandLine.hasOption('i')) { - parameters.setInputModelFileName(commandLine.getOptionValue('i')); - } - if (commandLine.hasOption('o')) { - parameters.setOutputModelFileName(commandLine.getOptionValue('o')); - } - if (commandLine.hasOption("if")) { - parameters.setIgnoreCommandFailuresSet(true); - parameters.setIgnoreCommandFailures(Boolean.valueOf(commandLine.getOptionValue("if"))); - } else { - parameters.setIgnoreCommandFailuresSet(false); - } - if (commandLine.hasOption("wd")) { - parameters.setWorkingDirectory(commandLine.getOptionValue("wd")); - } else { - parameters.setWorkingDirectory(Paths.get("").toAbsolutePath().toString()); - } - - return parameters; - } - - /** - * Print help information. - * - * @param mainClassName the main class name - */ - public void help(final String mainClassName) { - final HelpFormatter helpFormatter = new HelpFormatter(); - helpFormatter.printHelp(MAX_HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, ""); - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameters.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameters.java deleted file mode 100644 index 24356d128..000000000 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameters.java +++ /dev/null @@ -1,573 +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.auth.clieditor; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * This class reads and handles command line parameters to the Apex CLI editor. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CLIParameters { - // Default location of the command definition meta data in JSON - private static final String JSON_COMMAND_METADATA_RESOURCE = "etc/editor/Commands.json"; - private static final String APEX_MODEL_PROPERTIES_RESOURCE = "etc/editor/ApexModelProperties.json"; - - // The editor parameters - private boolean helpSet = false; - private String metadataFileName = null; - private String apexPropertiesFileName = null; - private String commandFileName = null; - private String inputModelFileName = null; - private String outputModelFileName = null; - private String workingDirectory = null; - private String logFileName = null; - private boolean echo = false; - private boolean suppressLog = false; - private boolean suppressModelOutput = false; - private boolean ignoreCommandFailuresSet = false; - private boolean ignoreCommandFailures = false; - - /** - * Validates the command line parameters. - */ - public void validate() { - validateReadableFile("Metadata File", metadataFileName); - validateReadableFile("Properties File", apexPropertiesFileName); - validateReadableFile("Command File", commandFileName); - validateReadableFile("Input Model File", inputModelFileName); - validateWritableFile("Output Model File", outputModelFileName); - validateWritableFile("Log File", logFileName); - validateWritableDirectory("Working Directory", workingDirectory); - - if (isSuppressLogSet()) { - setEcho(false); - } else { - if (checkSetCommandFileName()) { - setEcho(true); - if (!checkSetIgnoreCommandFailures()) { - setIgnoreCommandFailures(false); - } - } else { - setEcho(false); - if (!checkSetIgnoreCommandFailures()) { - setIgnoreCommandFailures(true); - } - } - } - } - - /** - * Gets the command metadata for the editor commands as a stream. - * - * @return the command metadata for the editor commands as a stream. - * @throws IOException the IO exception - */ - public InputStream getMetadataStream() throws IOException { - if (metadataFileName == null) { - return ResourceUtils.getResourceAsStream(JSON_COMMAND_METADATA_RESOURCE); - } else { - return new FileInputStream(new File(metadataFileName)); - } - } - - /** - * Gets the location of command metadata for the editor commands. - * - * @return the location of command metadata for the editor commands - */ - public String getMetadataLocation() { - if (metadataFileName == null) { - return "resource: \"" + JSON_COMMAND_METADATA_RESOURCE + "\""; - } else { - return "file: \"" + metadataFileName + "\""; - } - } - - /** - * Gets the properties that are used for command default values as a stream. - * - * @return the properties that are used for command default values as a stream - * @throws IOException the IO exception - */ - public InputStream getApexPropertiesStream() throws IOException { - if (apexPropertiesFileName == null) { - return ResourceUtils.getResourceAsStream(APEX_MODEL_PROPERTIES_RESOURCE); - } else { - return new FileInputStream(new File(apexPropertiesFileName)); - } - } - - /** - * Gets the location of the properties that are used for command default values. - * - * @return the location of the properties that are used for command default values - */ - public String getApexPropertiesLocation() { - if (metadataFileName == null) { - return "resource: \"" + APEX_MODEL_PROPERTIES_RESOURCE + "\""; - } else { - return "file: \"" + apexPropertiesFileName + "\""; - } - } - - /** - * Gets the input stream on which commands are being received. - * - * @return the input stream on which commands are being received - * @throws IOException the IO exception - */ - public InputStream getCommandInputStream() throws IOException { - if (commandFileName == null) { - return System.in; - } else { - return new FileInputStream(new File(commandFileName)); - } - } - - /** - * Gets the output stream on which command result messages are being output. - * - * @return the output stream on which command result messages are being output - * @throws IOException the IO exception - */ - public OutputStream getOutputStream() throws IOException { - // Check if log suppression is active, if so, consume all output on a byte array output stream - if (isSuppressLogSet()) { - return new ByteArrayOutputStream(); - - } - if (logFileName == null) { - return System.out; - } else { - return new FileOutputStream(new File(logFileName), true); - } - } - - /** - * Validate that a file is readable. - * - * @param fileTag the file tag, a tag used for information and error messages - * @param fileName the file name to check - */ - private void validateReadableFile(final String fileTag, final String fileName) { - if (fileName == null) { - return; - } - final File theFile = new File(fileName); - final String prefixExceptionMessage = "File " + fileName + "of type " + fileTag; - - if (!theFile.exists()) { - throw new CLIException(prefixExceptionMessage + " does not exist"); - } - if (!theFile.isFile()) { - throw new CLIException(prefixExceptionMessage + " is not a normal file"); - } - if (!theFile.canRead()) { - throw new CLIException(prefixExceptionMessage + " is ureadable"); - } - } - - /** - * Validate that a file is writable. - * - * @param fileTag the file tag, a tag used for information and error messages - * @param fileName the file name to check - */ - private void validateWritableFile(final String fileTag, final String fileName) { - if (fileName == null) { - return; - } - final File theFile = new File(fileName); - final String prefixExceptionMessage = "File " + fileName + "of type " + fileTag; - if (theFile.exists()) { - if (!theFile.isFile()) { - throw new CLIException(prefixExceptionMessage + " is not a normal file"); - } - if (!theFile.canWrite()) { - throw new CLIException(prefixExceptionMessage + " cannot be written"); - } - } else { - try { - theFile.createNewFile(); - } catch (final IOException e) { - throw new CLIException(prefixExceptionMessage + " cannot be created: ", e); - } - } - } - - /** - * Validate that a directory exists and is writable. - * - * @param directoryTag the directory tag, a tag used for information and error messages - * @param directoryName the directory name to check - */ - private void validateWritableDirectory(final String directoryTag, final String directoryName) { - if (directoryName == null) { - return; - } - final File theDirectory = new File(directoryName); - final String prefixExceptionMessage = "directory " + directoryName + "of type " + directoryTag; - - if (theDirectory.exists()) { - if (!theDirectory.isDirectory()) { - throw new CLIException(prefixExceptionMessage + " is not a directory"); - } - if (!theDirectory.canWrite()) { - throw new CLIException(prefixExceptionMessage + " cannot be written"); - } - } - } - - /** - * Checks if help is set. - * - * @return true, if help is set - */ - public boolean isHelpSet() { - return helpSet; - } - - /** - * Sets whether the help flag is set or not. - * - * @param isHelpSet the value of the help flag - */ - public void setHelp(final boolean isHelpSet) { - this.helpSet = isHelpSet; - } - - /** - * Gets the file name of the command metadata file for the editor commands. - * - * @return the file name of the command metadata file for the editor commands - */ - public String getMetadataFileName() { - return metadataFileName; - } - - /** - * Sets the file name of the command metadata file for the editor commands. - * - * @param metadataFileName the file name of the command metadata file for the editor commands - */ - public void setMetadataFileName(final String metadataFileName) { - this.metadataFileName = metadataFileName.trim(); - } - - /** - * Check if the file name of the command metadata file for the editor commands is set. - * - * @return true, if the file name of the command metadata file for the editor commands is set - */ - public boolean checkSetMetadataFileName() { - return metadataFileName != null && metadataFileName.length() > 0; - } - - /** - * Gets the file name of the file containing properties that are used for command default - * values. - * - * @return the file name of the file containing properties that are used for command default - * values - */ - public String getApexPorpertiesFileName() { - return apexPropertiesFileName; - } - - /** - * Sets the file name of the file containing properties that are used for command default - * values. - * - * @param apexPorpertiesFileName the file name of the file containing properties that are used - * for command default values - */ - public void setApexPorpertiesFileName(final String apexPorpertiesFileName) { - apexPropertiesFileName = apexPorpertiesFileName.trim(); - } - - /** - * Check if the file name of the file containing properties that are used for command default - * values is set. - * - * @return true, if the file name of the file containing properties that are used for command - * default values is set - */ - public boolean checkSetApexPropertiesFileName() { - return apexPropertiesFileName != null && apexPropertiesFileName.length() > 0; - } - - /** - * Gets the name of the file containing commands to be streamed into the CLI editor. - * - * @return the name of the file containing commands to be streamed into the CLI editor - */ - public String getCommandFileName() { - return commandFileName; - } - - /** - * Sets the name of the file containing commands to be streamed into the CLI editor. - * - * @param commandFileName the name of the file containing commands to be streamed into the CLI - * editor - */ - public void setCommandFileName(final String commandFileName) { - this.commandFileName = commandFileName.trim(); - } - - /** - * Check if the name of the file containing commands to be streamed into the CLI editor is set. - * - * @return true, if the name of the file containing commands to be streamed into the CLI editor - * is set - */ - public boolean checkSetCommandFileName() { - return commandFileName != null && commandFileName.length() > 0; - } - - /** - * Gets the name of the file containing the Apex model that will be used to initialize the Apex - * model in the CLI editor. - * - * @return the name of the file containing the Apex model that will be used to initialize the - * Apex model in the CLI editor - */ - public String getInputModelFileName() { - return inputModelFileName; - } - - /** - * Sets the name of the file containing the Apex model that will be used to initialize the Apex - * model in the CLI editor. - * - * @param inputModelFileName the name of the file containing the Apex model that will be used to - * initialize the Apex model in the CLI editor - */ - public void setInputModelFileName(final String inputModelFileName) { - this.inputModelFileName = inputModelFileName.trim(); - } - - /** - * Check if the name of the file containing the Apex model that will be used to initialize the - * Apex model in the CLI editor is set. - * - * @return true, if the name of the file containing the Apex model that will be used to - * initialize the Apex model in the CLI editor is set - */ - public boolean checkSetInputModelFileName() { - return inputModelFileName != null && inputModelFileName.length() > 0; - } - - /** - * Gets the name of the file that the Apex CLI editor will save the Apex model to when it exits. - * - * @return the name of the file that the Apex CLI editor will save the Apex model to when it - * exits - */ - public String getOutputModelFileName() { - return outputModelFileName; - } - - /** - * Sets the name of the file that the Apex CLI editor will save the Apex model to when it exits. - * - * @param outputModelFileName the name of the file that the Apex CLI editor will save the Apex - * model to when it exits - */ - public void setOutputModelFileName(final String outputModelFileName) { - this.outputModelFileName = outputModelFileName.trim(); - } - - /** - * Check if the name of the file that the Apex CLI editor will save the Apex model to when it - * exits is set. - * - * @return true, if the name of the file that the Apex CLI editor will save the Apex model to - * when it exits is set - */ - public boolean checkSetOutputModelFileName() { - return outputModelFileName != null && outputModelFileName.length() > 0; - } - - /** - * Gets the working directory that is the root for CLI editor macro includes. - * - * @return the CLI editor working directory - */ - public String getWorkingDirectory() { - return workingDirectory; - } - - /** - * Sets the working directory that is the root for CLI editor macro includes. - * - * @param workingDirectory the CLI editor working directory - */ - public void setWorkingDirectory(final String workingDirectory) { - this.workingDirectory = workingDirectory.trim(); - } - - /** - * Gets the name of the file to which the Apex CLI editor will log commands and responses. - * - * @return the name of the file to which the Apex CLI editor will log commands and responses - */ - public String getLogFileName() { - return logFileName; - } - - /** - * Sets the name of the file to which the Apex CLI editor will log commands and responses. - * - * @param logFileName the name of the file to which the Apex CLI editor will log commands and - * responses - */ - public void setLogFileName(final String logFileName) { - this.logFileName = logFileName.trim(); - } - - /** - * Check if the name of the file to which the Apex CLI editor will log commands and responses is - * set. - * - * @return true, if the name of the file to which the Apex CLI editor will log commands and - * responses is set - */ - public boolean checkSetLogFileName() { - return logFileName != null; - } - - /** - * Checks if the Apex CLI editor is set to echo commands that have been entered. - * - * @return true, if the Apex CLI editor is set to echo commands that have been entered - */ - public boolean isEchoSet() { - return echo; - } - - /** - * Sets whether the Apex CLI editor should echo commands that have been entered. - * - * @param echo true, if the Apex CLI editor should echo commands that have been entered - */ - public void setEcho(final boolean echo) { - this.echo = echo; - } - - /** - * Checks whether the Apex CLI editor is set to suppress logging of command output. - * - * @return true, if the Apex CLI editor is set to suppress logging of command output. - */ - public boolean isSuppressLogSet() { - return suppressLog; - } - - /** - * Sets whether the Apex CLI editor should suppress logging of command output. - * - * @param suppressLog true, if the Apex CLI editor should suppress logging of command output - */ - public void setSuppressLog(final boolean suppressLog) { - this.suppressLog = suppressLog; - } - - /** - * Checks whether the Apex CLI editor is set to suppress output of its Apex model on exit. - * - * @return true, if checks if the Apex CLI editor is set to suppress output of its Apex model on - * exit - */ - public boolean isSuppressModelOutputSet() { - return suppressModelOutput; - } - - /** - * Sets whether the Apex CLI editor should suppress output of its Apex model on exit. - * - * @param suppressModelOutput true, if the Apex CLI editor should suppress output of its Apex - * model on exit - */ - public void setSuppressModelOutput(final boolean suppressModelOutput) { - this.suppressModelOutput = suppressModelOutput; - } - - /** - * Check if the command failures flag is set. - * - * @return true if the command failures flag has been set - */ - public boolean checkSetIgnoreCommandFailures() { - return ignoreCommandFailuresSet; - } - - /** - * Checks if the command failures flag is set. - * - * @param ignoreCommandFailuresSet true if the command failures flag has been set - */ - public void setIgnoreCommandFailuresSet(final boolean ignoreCommandFailuresSet) { - this.ignoreCommandFailuresSet = ignoreCommandFailuresSet; - } - - /** - * Checks if command failures should be ignored and command execution continue. - * - * @return true if command failures should be ignored - */ - public boolean isIgnoreCommandFailures() { - return ignoreCommandFailures; - } - - /** - * Sets if command errors should be ignored and command execution continue. - * - * @param ignoreCommandFailures true if command errors should be ignored - */ - public void setIgnoreCommandFailures(final boolean ignoreCommandFailures) { - this.ignoreCommandFailures = ignoreCommandFailures; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "CLIParameters [helpSet=" + helpSet + ", metadataFileName=" + metadataFileName - + ", apexPropertiesFileName=" + apexPropertiesFileName + ", commandFileName=" + commandFileName - + ", inputModelFileName=" + inputModelFileName + ", outputModelFileName=" + outputModelFileName - + ", logFileName=" + logFileName + ", echo=" + echo + ", suppressLog=" + suppressLog - + ", suppressModelOutput=" + suppressModelOutput + "]"; - } -} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java new file mode 100644 index 000000000..f1a6e7867 --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java @@ -0,0 +1,144 @@ +/*- + * ============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.auth.clieditor; + +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class holds the definition of an argument of a CLI command. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineArgument implements Comparable { + private final String argumentName; + private final boolean nullable; + private final String description; + + /** + * This Constructor constructs a non nullable command line argument with a blank name and + * description. + */ + public CommandLineArgument() { + this("", false, ""); + } + + /** + * This Constructor constructs a non nullable command line argument with the given name and + * description. + * + * @param incomingArgumentName the argument name + */ + public CommandLineArgument(final String incomingArgumentName) { + this(incomingArgumentName, false, ""); + } + + /** + * This Constructor constructs a command line argument with the given name, nullability, and + * description. + * + * @param argumentName the argument name + * @param nullable the nullable + * @param description the description + */ + public CommandLineArgument(final String argumentName, final boolean nullable, final String description) { + this.argumentName = argumentName; + this.nullable = nullable; + this.description = description; + } + + /** + * Gets the argument name. + * + * @return the argument name + */ + public String getArgumentName() { + return argumentName; + } + + /** + * Checks if the argument is nullable. + * + * @return true, if checks if the argument is nullable + */ + public boolean isNullable() { + return nullable; + } + + /** + * Gets the argument description. + * + * @return the argument description + */ + public String getDescription() { + return description; + } + + /** + * Gets the argument help. + * + * @return the argument help + */ + public String getHelp() { + final StringBuilder builder = new StringBuilder(); + builder.append(argumentName); + builder.append(nullable ? ": (O) " : ": (M) "); + builder.append(description); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "CLIArgument [argumentName=" + argumentName + ", nullable=" + nullable + ", description=" + description + + "]"; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final CommandLineArgument otherArgument) { + Assertions.argumentNotNull(otherArgument, "comparison object may not be null"); + + if (this == otherArgument) { + return 0; + } + if (getClass() != otherArgument.getClass()) { + return this.hashCode() - otherArgument.hashCode(); + } + + final CommandLineArgument other = otherArgument; + + if (!argumentName.equals(other.argumentName)) { + return argumentName.compareTo(other.argumentName); + } + if (nullable != other.nullable) { + return (this.hashCode() - other.hashCode()); + } + return description.compareTo(otherArgument.description); + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgumentValue.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgumentValue.java new file mode 100644 index 000000000..64059e31b --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgumentValue.java @@ -0,0 +1,91 @@ +/*- + * ============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.auth.clieditor; + +/** + * This class represents an argument used on a command and its value. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineArgumentValue { + private final CommandLineArgument cliArgument; + private boolean specified; + private String value; + + /** + * The Constructor creates an argument value for the given argument, has not been set, and has + * no value. + * + * @param cliArgument the argument for which this object is a value + */ + public CommandLineArgumentValue(final CommandLineArgument cliArgument) { + this.cliArgument = cliArgument; + specified = false; + value = null; + } + + /** + * Gets the argument for which this object is a value. + * + * @return the argument for which this object is a value + */ + public CommandLineArgument getCliArgument() { + return cliArgument; + } + + /** + * Checks if the argument value is specified. + * + * @return true, if the argument value is specified + */ + public boolean isSpecified() { + return specified; + } + + /** + * Gets the argument value. + * + * @return the argument value + */ + public String getValue() { + return value; + } + + /** + * Sets the argument value. + * + * @param value the argument value + */ + public void setValue(final String value) { + this.value = value; + specified = true; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "CLIArgumentValue [cliArgument=" + cliArgument + ", specified=" + specified + ", value=" + value + "]"; + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java new file mode 100644 index 000000000..6c651cb6b --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java @@ -0,0 +1,240 @@ +/*- + * ============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.auth.clieditor; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class represents a single Apex CLI command that is issued to the Apex Editor Java API + * {@link org.onap.policy.apex.model.modelapi.ApexEditorApi}. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineCommand implements Comparable { + private String name = ""; + private final List keywordlist = new ArrayList<>(); + private final List argumentList = new ArrayList<>(); + private String apiMethod = ""; + private boolean systemCommand = false; + private String description = ""; + + /** + * Gets the class name of the class that executes this command in the Java API. + * + * @return the class name of the class that executes this command in the Java API + */ + public String getApiClassName() { + final int lastDotPos = apiMethod.lastIndexOf('.'); + if (lastDotPos == -1) { + throw new CommandLineException("invalid API method name specified on command \"" + name + + "\", class name not found: " + apiMethod); + } + return apiMethod.substring(0, lastDotPos); + } + + /** + * Gets the method name of the method that executes this command in the Java API. + * + * @return the the method name of the method that executes this command in the Java API + */ + public String getApiMethodName() { + final int lastDotPos = apiMethod.lastIndexOf('.'); + if (lastDotPos == -1) { + throw new CommandLineException("invalid API method name specified on command \"" + name + + "\", class name not found: " + apiMethod); + } + if (lastDotPos == apiMethod.length() - 1) { + throw new CommandLineException("no API method name specified on command \"" + name + "\": " + apiMethod); + } + return apiMethod.substring(lastDotPos + 1); + } + + /** + * Gets the name of the editor command. + * + * @return the name of the editor command + */ + public String getName() { + return name; + } + + /** + * Sets the name of the editor command. + * + * @param name the name of the editor command + */ + public void setName(final String name) { + this.name = name; + } + + /** + * Gets the list of keywords for this command. + * + * @return the list of keywords for this command + */ + public List getKeywordlist() { + return keywordlist; + } + + /** + * Gets the list of arguments for this command. + * + * @return the list of arguments for this command + */ + public List getArgumentList() { + return argumentList; + } + + /** + * Gets the method of the method that executes this command in the Java API. + * + * @return the method of the method that executes this command in the Java API + */ + public String getApiMethod() { + return apiMethod; + } + + /** + * Sets the method of the method that executes this command in the Java API. + * + * @param apiMethod the method of the method that executes this command in the Java API + */ + public void setApiMethod(final String apiMethod) { + this.apiMethod = apiMethod; + } + + /** + * Gets the description of the command. + * + * @return the description of the command + */ + public String getDescription() { + return description; + } + + /** + * Sets the description of the command. + * + * @param description the description of the command + */ + public void setDescription(final String description) { + this.description = description; + } + + /** + * Checks if this command is a system command. + * + * @return true, if this command is a system command + */ + public boolean isSystemCommand() { + return systemCommand; + } + + /** + * Sets whether this command is a system command. + * + * @param systemCommand whether this command is a system command + */ + public void setSystemCommand(final boolean systemCommand) { + this.systemCommand = systemCommand; + } + + /** + * Gets help for this command. + * + * @return the help for this command + */ + public String getHelp() { + final StringBuilder builder = new StringBuilder(); + for (final String keyword : keywordlist) { + builder.append(keyword); + builder.append(' '); + } + builder.append('{'); + builder.append(name); + builder.append("}: "); + builder.append(description); + + for (final CommandLineArgument argument : argumentList) { + if (argument == null) { + continue; + } + builder.append("\n\t"); + builder.append(argument.getHelp()); + } + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "CLICommand [name=" + name + ",keywordlist=" + keywordlist + ", argumentList=" + argumentList + + ", apiMethod=" + apiMethod + ", systemCommand=" + systemCommand + ", description=" + description + + "]"; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final CommandLineCommand otherCommand) { + Assertions.argumentNotNull(otherCommand, "comparison object may not be null"); + + if (this == otherCommand) { + return 0; + } + if (getClass() != otherCommand.getClass()) { + return this.hashCode() - otherCommand.hashCode(); + } + + final CommandLineCommand other = otherCommand; + + for (int i = 0, j = 0;; i++, j++) { + if (i < keywordlist.size() && j < otherCommand.keywordlist.size()) { + if (!keywordlist.get(i).equals(other.keywordlist.get(j))) { + return keywordlist.get(i).compareTo(other.keywordlist.get(j)); + } + } else if (i == keywordlist.size() && j == otherCommand.keywordlist.size()) { + break; + } else if (i == keywordlist.size()) { + return -1; + } else { + return 1; + } + } + if (!argumentList.equals(other.argumentList)) { + return (argumentList.hashCode() - other.argumentList.hashCode()); + } + if (systemCommand != other.systemCommand) { + return (this.hashCode() - other.hashCode()); + } + return apiMethod.compareTo(other.apiMethod); + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommands.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommands.java new file mode 100644 index 000000000..45d8a4bd3 --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommands.java @@ -0,0 +1,42 @@ +/*- + * ============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.auth.clieditor; + +import java.util.Set; +import java.util.TreeSet; + +/** + * This class contains the CLI commands read in from a JSON file. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineCommands { + private final Set commandList = new TreeSet<>(); + + /** + * Gets the command set. + * + * @return the command set + */ + public Set getCommandSet() { + return commandList; + } +} 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 new file mode 100644 index 000000000..7a34ce7c1 --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java @@ -0,0 +1,544 @@ +/*- + * ============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.auth.clieditor; + +import static org.onap.policy.apex.model.utilities.TreeMapUtils.findMatchingEntries; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.util.AbstractMap.SimpleEntry; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.TreeMap; + +import org.onap.policy.apex.model.modelapi.ApexApiResult; +import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.model.utilities.TreeMapUtils; + +/** + * This class implements the editor loop, the loop of execution that continuously executes commands until the quit + * command is issued or EOF is detected on input. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineEditorLoop { + // The model handler that is handling the API towards the Apex model being editied + private final ApexModelHandler modelHandler; + + // Holds the current location in the keyword hierarchy + private final ArrayDeque keywordNodeDeque = new ArrayDeque<>(); + + // Logic block tags + private final String logicBlockStartTag; + private final String logicBlockEndTag; + + // File Macro tag + private final String macroFileTag; + + /** + * Initiate the loop with the keyword node tree. + * + * @param properties The CLI editor properties defined for execution + * @param modelHandler the model handler that will handle commands + * @param rootKeywordNode The root keyword node tree + */ + public CommandLineEditorLoop(final Properties properties, final ApexModelHandler modelHandler, + final KeywordNode rootKeywordNode) { + this.modelHandler = modelHandler; + keywordNodeDeque.push(rootKeywordNode); + + logicBlockStartTag = properties.getProperty("DEFAULT_LOGIC_BLOCK_START_TAG"); + logicBlockEndTag = properties.getProperty("DEFAULT_LOGIC_BLOCK_END_TAG"); + macroFileTag = properties.getProperty("DEFAULT_MACRO_FILE_TAG"); + } + + /** + * Run a command loop. + * + * @param inputStream The stream to read commands from + * @param outputStream The stream to write command output and messages to + * @param parameters The parameters for the CLI editor + * @return the exit code from command processing + * @throws IOException Thrown on exceptions on IO + */ + public int runLoop(final InputStream inputStream, final OutputStream outputStream, + final CommandLineParameters parameters) throws IOException { + // Readers and writers for input and output + final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + final PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream)); + + // The parser parses the input lines into commands and arguments + final CommandLineParser parser = new CommandLineParser(); + + // The main loop for command handing, it continues until EOF on the input stream or until a + // quit command + int errorCount = 0; + ApexApiResult result = new ApexApiResult(); + while (result.getResult() != Result.FINISHED) { + if (!parameters.isIgnoreCommandFailures() && errorCount > 0) { + break; + } + + // Output prompt and get a line of input + writer.print(getPrompt()); + writer.flush(); + String line = reader.readLine(); + if (line == null) { + break; + } + + // Expand any macros in the script + try { + while (line.contains(macroFileTag)) { + line = expandMacroFile(parameters, line); + } + } + // Print any error messages from command parsing and finding + catch (final CommandLineException e) { + writer.println(e.getMessage()); + errorCount++; + continue; + } + + if (parameters.isEchoSet()) { + writer.println(line); + } + + String logicBlock = null; + if (line.trim().endsWith(logicBlockStartTag)) { + line = line.replace(logicBlockStartTag, "").trim(); + + logicBlock = ""; + while (true) { + String logicLine = reader.readLine(); + if (logicLine == null) { + logicBlock = null; + break; + } + + try { + while (logicLine.contains(macroFileTag)) { + logicLine = expandMacroFile(parameters, logicLine); + } + } + // Print any error messages from command parsing and finding + catch (final CommandLineException e) { + writer.println(e.getMessage()); + errorCount++; + continue; + } + + if (parameters.isEchoSet()) { + writer.println(logicLine); + } + + if (logicLine.trim().endsWith(logicBlockEndTag)) { + logicBlock += logicLine.replace(logicBlockEndTag, "").trim() + "\n"; + break; + } else { + logicBlock += logicLine + "\n"; + } + } + } + + try { + // Parse the line into a list of commands and arguments + final List commandWords = parser.parse(line, logicBlock); + + // Find the command, if the command is null, then we are simply changing position in + // the hierarchy + final CommandLineCommand command = findCommand(commandWords); + if (command != null) { + // Check the arguments of the command + final TreeMap argumentValues = getArgumentValues(command, + commandWords); + + // Execute the command, a FINISHED result means a command causes the loop to + // leave execution + result = executeCommand(command, argumentValues, writer); + if (result.isNok()) { + errorCount++; + } + } + } + // Print any error messages from command parsing and finding + catch (final CommandLineException e) { + writer.println(e.getMessage()); + errorCount++; + } catch (final Exception e) { + e.printStackTrace(writer); + } + } + + // Get the output model + if (!parameters.isSuppressModelOutputSet()) { + final String modelString = modelHandler.writeModelToString(writer); + + if (parameters.checkSetOutputModelFileName()) { + TextFileUtils.putStringAsTextFile(modelString, parameters.getOutputModelFileName()); + } else { + System.out.println(modelString); + } + } + + reader.close(); + writer.close(); + + return errorCount; + } + + /** + * Output a prompt that indicates where in the keyword hierarchy we are. + * + * @return A string with the prompt + */ + private String getPrompt() { + final StringBuilder builder = new StringBuilder(); + final Iterator keynodeDequeIter = keywordNodeDeque.descendingIterator(); + + while (keynodeDequeIter.hasNext()) { + builder.append('/'); + builder.append(keynodeDequeIter.next().getKeyword()); + } + builder.append("> "); + + return builder.toString(); + } + + /** + * Finds a command for the given input command words. Command words need only ne specified enough to uniquely + * identify them. Therefore, "p s o c" will find the command "policy state output create" + * + * @param commandWords The commands and arguments parsed from the command line by the parser + * @return The found command + */ + + private CommandLineCommand findCommand(final List commandWords) { + CommandLineCommand command = null; + + final KeywordNode startKeywordNode = keywordNodeDeque.peek(); + + // Go down through the keywords searching for the command + for (int i = 0; i < commandWords.size(); i++) { + final KeywordNode searchKeywordNode = keywordNodeDeque.peek(); + + // We have got to the arguments, time to stop looking + if (commandWords.get(i).indexOf('=') > 0) { + unwindStack(startKeywordNode); + throw new CommandLineException("command not found: " + stringAL2String(commandWords)); + } + + // If the node entries found is not equal to one, then we have either no command or more + // than one command matching + final List> foundNodeEntries = findMatchingEntries( + searchKeywordNode.getChildren(), commandWords.get(i)); + if (foundNodeEntries.isEmpty()) { + unwindStack(startKeywordNode); + throw new CommandLineException("command not found: " + stringAL2String(commandWords)); + } else if (foundNodeEntries.size() > 1) { + unwindStack(startKeywordNode); + throw new CommandLineException("multiple commands matched: " + stringAL2String(commandWords) + " [" + + nodeAL2String(foundNodeEntries) + ']'); + } + + // Record the fully expanded command word + commandWords.set(i, foundNodeEntries.get(0).getKey()); + + // Check if there is a command + final KeywordNode childKeywordNode = foundNodeEntries.get(0).getValue(); + command = childKeywordNode.getCommand(); + + // If the command is null, we go into a sub mode, otherwise we unwind the stack of + // commands and return the found command + if (command == null) { + keywordNodeDeque.push(childKeywordNode); + } else { + unwindStack(startKeywordNode); + return command; + } + } + + return null; + } + + /** + * Unwind the stack of keyword node entries we have placed on the queue in a command search. + * + * @param startKeywordNode The point on the queue we want to unwind to + */ + private void unwindStack(final KeywordNode startKeywordNode) { + // Unwind the stack + while (true) { + if (keywordNodeDeque.peek().equals(startKeywordNode)) { + return; + } + keywordNodeDeque.pop(); + } + } + + /** + * Check the arguments of the command. + * + * @param command The command to check + * @param commandWords The command words entered + * @return the argument values + */ + private TreeMap getArgumentValues(final CommandLineCommand command, + final List commandWords) { + final TreeMap argumentValues = new TreeMap<>(); + for (final CommandLineArgument argument : command.getArgumentList()) { + if (argument != null) { + argumentValues.put(argument.getArgumentName(), new CommandLineArgumentValue(argument)); + } + } + + // Set the value of the arguments + 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 \"" + + argument.getKey() + "\" not allowed on command"); + } else if (foundArguments.size() > 1) { + throw new CommandLineException("command " + stringAL2String(commandWords) + ": " + " argument " + + argument + " matches multiple arguments [" + argumentAL2String(foundArguments) + ']'); + } + + // Set the value of the argument, stripping off any quotes + final String argumentValue = argument.getValue().replaceAll("^\"", "").replaceAll("\"$", ""); + foundArguments.get(0).getValue().setValue(argumentValue); + } + + // Now check all mandatory arguments are set + for (final CommandLineArgumentValue argumentValue : argumentValues.values()) { + // 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) + ": " + + " mandatory argument \"" + argumentValue.getCliArgument().getArgumentName() + + "\" not specified"); + } + } + + return argumentValues; + } + + /** + * Get the arguments of the command, the command words have already been conditioned into an array starting with the + * command words and ending with the arguments as name=value tuples. + * + * @param commandWords The command words entered by the user + * @return the arguments as an entry array list + */ + private ArrayList> getCommandArguments(final List commandWords) { + final ArrayList> arguments = new ArrayList<>(); + + // Iterate over the command words, arguments are of the format name=value + for (final String word : commandWords) { + final int equalsPos = word.indexOf('='); + if (equalsPos > 0) { + arguments.add(new SimpleEntry<>(word.substring(0, equalsPos), + word.substring(equalsPos + 1, word.length()))); + } + } + + return arguments; + } + + /** + * Execute system and editor commands. + * + * @param command The command to execute + * @param argumentValues The arguments input on the command line to invoke the command + * @param writer The writer to use for any output from the command + * @return the result of execution of the command + */ + private ApexApiResult executeCommand(final CommandLineCommand command, + final TreeMap argumentValues, final PrintWriter writer) { + if (command.isSystemCommand()) { + return exceuteSystemCommand(command, writer); + } else { + return modelHandler.executeCommand(command, argumentValues, writer); + } + } + + /** + * Execute system commands. + * + * @param command The command to execute + * @param writer The writer to use for any output from the command + * @return the result of execution of the command + */ + private ApexApiResult exceuteSystemCommand(final CommandLineCommand command, final PrintWriter writer) { + if ("back".equals(command.getName())) { + return executeBackCommand(); + } else if ("help".equals(command.getName())) { + return executeHelpCommand(writer); + } else if ("quit".equals(command.getName())) { + return executeQuitCommand(); + } else { + return new ApexApiResult(Result.SUCCESS); + } + } + + /** + * Execute the "back" command. + * + * @return the result of execution of the command + */ + private ApexApiResult executeBackCommand() { + if (keywordNodeDeque.size() > 1) { + keywordNodeDeque.pop(); + } + return new ApexApiResult(Result.SUCCESS); + } + + /** + * Execute the "quit" command. + * + * @return the result of execution of the command + */ + private ApexApiResult executeQuitCommand() { + return new ApexApiResult(Result.FINISHED); + } + + /** + * Execute the "help" command. + * + * @param writer The writer to use for output from the command + * @return the result of execution of the command + */ + private ApexApiResult executeHelpCommand(final PrintWriter writer) { + for (final CommandLineCommand command : keywordNodeDeque.peek().getCommands()) { + writer.println(command.getHelp()); + } + return new ApexApiResult(Result.SUCCESS); + } + + /** + * Helper method to output an array list of keyword node entries to a string. + * + * @param nodeEntryArrayList the array list of keyword node entries + * @return the string + */ + private String nodeAL2String(final List> nodeEntryArrayList) { + final ArrayList stringArrayList = new ArrayList<>(); + for (final Entry node : nodeEntryArrayList) { + stringArrayList.add(node.getValue().getKeyword()); + } + + return stringAL2String(stringArrayList); + } + + /** + * Helper method to output an array list of argument entries to a string. + * + * @param argumentArrayList the argument array list + * @return the string + */ + private String argumentAL2String(final List> argumentArrayList) { + final ArrayList stringArrayList = new ArrayList<>(); + for (final Entry argument : argumentArrayList) { + stringArrayList.add(argument.getValue().getCliArgument().getArgumentName()); + } + + return stringAL2String(stringArrayList); + } + + /** + * Helper method to output an array list of strings to a string. + * + * @param stringArrayList the array list of strings + * @return the string + */ + private String stringAL2String(final List stringArrayList) { + final StringBuilder builder = new StringBuilder(); + boolean first = true; + for (final String word : stringArrayList) { + if (first) { + first = false; + } else { + builder.append(','); + } + builder.append(word); + } + + return builder.toString(); + } + + /** + * This method reads in the file from a file macro statement, expands the macro, and replaces the Macro tag in the + * line with the file contents. + * + * @param parameters The parameters for the CLI editor + * @param line The line with the macro keyword in it + * @return the expanded line + */ + private String expandMacroFile(final CommandLineParameters parameters, final String line) { + final int macroTagPos = line.indexOf(macroFileTag); + + // Get the line before and after the macro tag + final String lineBeforeMacroTag = line.substring(0, macroTagPos); + final String lineAfterMacroTag = line.substring(macroTagPos + macroFileTag.length()).replaceAll("^\\s*", ""); + + // Get the file name that is the argument of the Macro tag + final String[] lineWords = lineAfterMacroTag.split("\\s+"); + + if (lineWords.length == 0) { + throw new CommandLineException("no file name specified for Macro File Tag"); + } + + // Get the macro file name and the remainder of the line after the file name + String macroFileName = lineWords[0]; + final String lineAfterMacroFileName = lineAfterMacroTag.replaceFirst(macroFileName, ""); + + if (macroFileName.length() > 2 && macroFileName.startsWith("\"") && macroFileName.endsWith("\"")) { + macroFileName = macroFileName.substring(1, macroFileName.length() - 1); + } else { + throw new CommandLineException("macro file name \"" + macroFileName + + "\" must exist and be quoted with double quotes \"\""); + } + + // Append the working directory to the macro file name + macroFileName = parameters.getWorkingDirectory() + File.separatorChar + macroFileName; + + // Now, get the text file for the argument of the macro + String macroFileContents = null; + try { + macroFileContents = TextFileUtils.getTextFileAsString(macroFileName); + } catch (final IOException e) { + throw new CommandLineException("file \"" + macroFileName + "\" specified in Macro File Tag not found", e); + } + + return lineBeforeMacroTag + macroFileContents + lineAfterMacroFileName; + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineException.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineException.java new file mode 100644 index 000000000..4ff17458e --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineException.java @@ -0,0 +1,49 @@ +/*- + * ============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.auth.clieditor; + +/** + * A run time exception used to report parsing and command input errors. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineException extends IllegalArgumentException { + private static final long serialVersionUID = 6520231162404452427L; + + /** + * Create a CLIException with a message. + * + * @param message the message + */ + public CommandLineException(final String message) { + super(message); + } + + /** + * Create a CLIException with a message and an exception. + * + * @param message the message + * @param th the throwable + */ + public CommandLineException(final String message, final Throwable th) { + super(message, th); + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.java new file mode 100644 index 000000000..a37d07fab --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.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.auth.clieditor; + +import java.nio.file.Paths; +import java.util.Arrays; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +/** + * This class reads and handles command line parameters to the Apex CLI editor. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineParameterParser { + private static final int MAX_HELP_LINE_LENGTH = 120; + + // Apache Commons CLI options + private final Options options; + + /** + * Construct the options for the CLI editor. + */ + public CommandLineParameterParser() { + options = new Options(); + options.addOption(Option.builder("h").longOpt("help").desc("outputs the usage of this command").required(false) + .type(Boolean.class).build()); + options.addOption(Option.builder("m").longOpt("metadata-file").desc("name of the command metadata file to use") + .hasArg().argName("CMD_METADATA_FILE").required(false).type(String.class).build()); + options.addOption(Option.builder("a").longOpt("model-props-file") + .desc("name of the apex model properties file to use").hasArg().argName("MODEL_PROPS_FILE") + .required(false).type(String.class).build()); + options.addOption(Option.builder("c").longOpt("command-file") + .desc("name of a file containing editor commands to run into the editor").hasArg() + .argName("COMMAND_FILE").required(false).type(String.class).build()); + options.addOption(Option.builder("l").longOpt("log-file").desc( + "name of a file that will contain command logs from the editor, will log to standard output " + + "if not specified or suppressed with \"-nl\" flag") + .hasArg().argName("LOG_FILE").required(false).type(String.class).build()); + options.addOption(Option.builder("nl").longOpt("no-log").desc( + "if specified, no logging or output of commands to standard output or log file is carried out") + .required(false).type(Boolean.class).build()); + options.addOption(Option.builder("nm").longOpt("no-model-output").desc( + "if specified, no output of a model to standard output or model output file is carried out, " + + "the user can use the \"save\" command in a script to save a model") + .required(false).type(Boolean.class).build()); + options.addOption(Option.builder("i").longOpt("input-model-file") + .desc("name of a file that contains an input model for the editor").hasArg() + .argName("INPUT_MODEL_FILE").required(false).type(String.class).build()); + options.addOption(Option.builder("o").longOpt("output-model-file") + .desc("name of a file that will contain the output model for the editor, " + + "will output model to standard output if not specified " + + "or suppressed with \"-nm\" flag") + .hasArg().argName("OUTPUT_MODEL_FILE").required(false).type(String.class).build()); + options.addOption(Option.builder("if").longOpt("ignore-failures") + .desc("true or false, ignore failures of commands in command files and continue executing the " + + "command file") + .hasArg().argName("IGNORE_FAILURES_FLAG").required(false).type(Boolean.class).build()); + options.addOption(Option.builder("wd").longOpt("working-directory") + .desc("the working directory that is the root for the CLI editor and is the root from which to " + + "look for included macro files") + .hasArg().argName("WORKING_DIRECTORY").required(false).type(String.class).build()); + } + + /** + * Parse the command line options. + * + * @param args The arguments + * @return the CLI parameters + */ + public CommandLineParameters parse(final String[] args) { + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new CommandLineException("invalid command line arguments specified : " + e.getMessage()); + } + + final CommandLineParameters parameters = new CommandLineParameters(); + final String[] remainingArgs = commandLine.getArgs(); + + if (remainingArgs.length > 0) { + throw new CommandLineException( + "too many command line arguments specified : " + Arrays.toString(remainingArgs)); + } + + if (commandLine.hasOption('h')) { + parameters.setHelp(true); + } + if (commandLine.hasOption('m')) { + parameters.setMetadataFileName(commandLine.getOptionValue('m')); + } + if (commandLine.hasOption('a')) { + parameters.setApexPorpertiesFileName(commandLine.getOptionValue('a')); + } + if (commandLine.hasOption('c')) { + parameters.setCommandFileName(commandLine.getOptionValue('c')); + } + if (commandLine.hasOption('l')) { + parameters.setLogFileName(commandLine.getOptionValue('l')); + } + if (commandLine.hasOption("nl")) { + parameters.setSuppressLog(true); + } + if (commandLine.hasOption("nm")) { + parameters.setSuppressModelOutput(true); + } + if (commandLine.hasOption('i')) { + parameters.setInputModelFileName(commandLine.getOptionValue('i')); + } + if (commandLine.hasOption('o')) { + parameters.setOutputModelFileName(commandLine.getOptionValue('o')); + } + if (commandLine.hasOption("if")) { + parameters.setIgnoreCommandFailuresSet(true); + parameters.setIgnoreCommandFailures(Boolean.valueOf(commandLine.getOptionValue("if"))); + } else { + parameters.setIgnoreCommandFailuresSet(false); + } + if (commandLine.hasOption("wd")) { + parameters.setWorkingDirectory(commandLine.getOptionValue("wd")); + } else { + parameters.setWorkingDirectory(Paths.get("").toAbsolutePath().toString()); + } + + return parameters; + } + + /** + * Print help information. + * + * @param mainClassName the main class name + */ + public void help(final String mainClassName) { + final HelpFormatter helpFormatter = new HelpFormatter(); + helpFormatter.printHelp(MAX_HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, ""); + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameters.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameters.java new file mode 100644 index 000000000..9a03dcfde --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameters.java @@ -0,0 +1,576 @@ +/*- + * ============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.auth.clieditor; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * This class reads and handles command line parameters to the Apex CLI editor. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineParameters { + // Recurring string constants + private static final String OF_TYPE_TAG = "of type "; + + // Default location of the command definition meta data in JSON + private static final String JSON_COMMAND_METADATA_RESOURCE = "etc/editor/Commands.json"; + private static final String APEX_MODEL_PROPERTIES_RESOURCE = "etc/editor/ApexModelProperties.json"; + + // The editor parameters + private boolean helpSet = false; + private String metadataFileName = null; + private String apexPropertiesFileName = null; + private String commandFileName = null; + private String inputModelFileName = null; + private String outputModelFileName = null; + private String workingDirectory = null; + private String logFileName = null; + private boolean echo = false; + private boolean suppressLog = false; + private boolean suppressModelOutput = false; + private boolean ignoreCommandFailuresSet = false; + private boolean ignoreCommandFailures = false; + + /** + * Validates the command line parameters. + */ + public void validate() { + validateReadableFile("Metadata File", metadataFileName); + validateReadableFile("Properties File", apexPropertiesFileName); + validateReadableFile("Command File", commandFileName); + validateReadableFile("Input Model File", inputModelFileName); + validateWritableFile("Output Model File", outputModelFileName); + validateWritableFile("Log File", logFileName); + validateWritableDirectory("Working Directory", workingDirectory); + + if (isSuppressLogSet()) { + setEcho(false); + } else { + if (checkSetCommandFileName()) { + setEcho(true); + if (!checkSetIgnoreCommandFailures()) { + setIgnoreCommandFailures(false); + } + } else { + setEcho(false); + if (!checkSetIgnoreCommandFailures()) { + setIgnoreCommandFailures(true); + } + } + } + } + + /** + * Gets the command metadata for the editor commands as a stream. + * + * @return the command metadata for the editor commands as a stream. + * @throws IOException the IO exception + */ + public InputStream getMetadataStream() throws IOException { + if (metadataFileName == null) { + return ResourceUtils.getResourceAsStream(JSON_COMMAND_METADATA_RESOURCE); + } else { + return new FileInputStream(new File(metadataFileName)); + } + } + + /** + * Gets the location of command metadata for the editor commands. + * + * @return the location of command metadata for the editor commands + */ + public String getMetadataLocation() { + if (metadataFileName == null) { + return "resource: \"" + JSON_COMMAND_METADATA_RESOURCE + "\""; + } else { + return "file: \"" + metadataFileName + "\""; + } + } + + /** + * Gets the properties that are used for command default values as a stream. + * + * @return the properties that are used for command default values as a stream + * @throws IOException the IO exception + */ + public InputStream getApexPropertiesStream() throws IOException { + if (apexPropertiesFileName == null) { + return ResourceUtils.getResourceAsStream(APEX_MODEL_PROPERTIES_RESOURCE); + } else { + return new FileInputStream(new File(apexPropertiesFileName)); + } + } + + /** + * Gets the location of the properties that are used for command default values. + * + * @return the location of the properties that are used for command default values + */ + public String getApexPropertiesLocation() { + if (metadataFileName == null) { + return "resource: \"" + APEX_MODEL_PROPERTIES_RESOURCE + "\""; + } else { + return "file: \"" + apexPropertiesFileName + "\""; + } + } + + /** + * Gets the input stream on which commands are being received. + * + * @return the input stream on which commands are being received + * @throws IOException the IO exception + */ + public InputStream getCommandInputStream() throws IOException { + if (commandFileName == null) { + return System.in; + } else { + return new FileInputStream(new File(commandFileName)); + } + } + + /** + * Gets the output stream on which command result messages are being output. + * + * @return the output stream on which command result messages are being output + * @throws IOException the IO exception + */ + public OutputStream getOutputStream() throws IOException { + // Check if log suppression is active, if so, consume all output on a byte array output stream + if (isSuppressLogSet()) { + return new ByteArrayOutputStream(); + + } + if (logFileName == null) { + return System.out; + } else { + return new FileOutputStream(new File(logFileName), true); + } + } + + /** + * Validate that a file is readable. + * + * @param fileTag the file tag, a tag used for information and error messages + * @param fileName the file name to check + */ + private void validateReadableFile(final String fileTag, final String fileName) { + if (fileName == null) { + return; + } + final File theFile = new File(fileName); + final String prefixExceptionMessage = "File " + fileName + OF_TYPE_TAG + fileTag; + + if (!theFile.exists()) { + throw new CommandLineException(prefixExceptionMessage + " does not exist"); + } + if (!theFile.isFile()) { + throw new CommandLineException(prefixExceptionMessage + " is not a normal file"); + } + if (!theFile.canRead()) { + throw new CommandLineException(prefixExceptionMessage + " is ureadable"); + } + } + + /** + * Validate that a file is writable. + * + * @param fileTag the file tag, a tag used for information and error messages + * @param fileName the file name to check + */ + private void validateWritableFile(final String fileTag, final String fileName) { + if (fileName == null) { + return; + } + final File theFile = new File(fileName); + final String prefixExceptionMessage = "File " + fileName + OF_TYPE_TAG + fileTag; + if (theFile.exists()) { + if (!theFile.isFile()) { + throw new CommandLineException(prefixExceptionMessage + " is not a normal file"); + } + if (!theFile.canWrite()) { + throw new CommandLineException(prefixExceptionMessage + " cannot be written"); + } + } else { + try { + theFile.createNewFile(); + } catch (final IOException e) { + throw new CommandLineException(prefixExceptionMessage + " cannot be created: ", e); + } + } + } + + /** + * Validate that a directory exists and is writable. + * + * @param directoryTag the directory tag, a tag used for information and error messages + * @param directoryName the directory name to check + */ + private void validateWritableDirectory(final String directoryTag, final String directoryName) { + if (directoryName == null) { + return; + } + final File theDirectory = new File(directoryName); + final String prefixExceptionMessage = "directory " + directoryName + OF_TYPE_TAG + directoryTag; + + if (theDirectory.exists()) { + if (!theDirectory.isDirectory()) { + throw new CommandLineException(prefixExceptionMessage + " is not a directory"); + } + if (!theDirectory.canWrite()) { + throw new CommandLineException(prefixExceptionMessage + " cannot be written"); + } + } + } + + /** + * Checks if help is set. + * + * @return true, if help is set + */ + public boolean isHelpSet() { + return helpSet; + } + + /** + * Sets whether the help flag is set or not. + * + * @param isHelpSet the value of the help flag + */ + public void setHelp(final boolean isHelpSet) { + this.helpSet = isHelpSet; + } + + /** + * Gets the file name of the command metadata file for the editor commands. + * + * @return the file name of the command metadata file for the editor commands + */ + public String getMetadataFileName() { + return metadataFileName; + } + + /** + * Sets the file name of the command metadata file for the editor commands. + * + * @param metadataFileName the file name of the command metadata file for the editor commands + */ + public void setMetadataFileName(final String metadataFileName) { + this.metadataFileName = metadataFileName.trim(); + } + + /** + * Check if the file name of the command metadata file for the editor commands is set. + * + * @return true, if the file name of the command metadata file for the editor commands is set + */ + public boolean checkSetMetadataFileName() { + return metadataFileName != null && metadataFileName.length() > 0; + } + + /** + * Gets the file name of the file containing properties that are used for command default + * values. + * + * @return the file name of the file containing properties that are used for command default + * values + */ + public String getApexPorpertiesFileName() { + return apexPropertiesFileName; + } + + /** + * Sets the file name of the file containing properties that are used for command default + * values. + * + * @param apexPorpertiesFileName the file name of the file containing properties that are used + * for command default values + */ + public void setApexPorpertiesFileName(final String apexPorpertiesFileName) { + apexPropertiesFileName = apexPorpertiesFileName.trim(); + } + + /** + * Check if the file name of the file containing properties that are used for command default + * values is set. + * + * @return true, if the file name of the file containing properties that are used for command + * default values is set + */ + public boolean checkSetApexPropertiesFileName() { + return apexPropertiesFileName != null && apexPropertiesFileName.length() > 0; + } + + /** + * Gets the name of the file containing commands to be streamed into the CLI editor. + * + * @return the name of the file containing commands to be streamed into the CLI editor + */ + public String getCommandFileName() { + return commandFileName; + } + + /** + * Sets the name of the file containing commands to be streamed into the CLI editor. + * + * @param commandFileName the name of the file containing commands to be streamed into the CLI + * editor + */ + public void setCommandFileName(final String commandFileName) { + this.commandFileName = commandFileName.trim(); + } + + /** + * Check if the name of the file containing commands to be streamed into the CLI editor is set. + * + * @return true, if the name of the file containing commands to be streamed into the CLI editor + * is set + */ + public boolean checkSetCommandFileName() { + return commandFileName != null && commandFileName.length() > 0; + } + + /** + * Gets the name of the file containing the Apex model that will be used to initialize the Apex + * model in the CLI editor. + * + * @return the name of the file containing the Apex model that will be used to initialize the + * Apex model in the CLI editor + */ + public String getInputModelFileName() { + return inputModelFileName; + } + + /** + * Sets the name of the file containing the Apex model that will be used to initialize the Apex + * model in the CLI editor. + * + * @param inputModelFileName the name of the file containing the Apex model that will be used to + * initialize the Apex model in the CLI editor + */ + public void setInputModelFileName(final String inputModelFileName) { + this.inputModelFileName = inputModelFileName.trim(); + } + + /** + * Check if the name of the file containing the Apex model that will be used to initialize the + * Apex model in the CLI editor is set. + * + * @return true, if the name of the file containing the Apex model that will be used to + * initialize the Apex model in the CLI editor is set + */ + public boolean checkSetInputModelFileName() { + return inputModelFileName != null && inputModelFileName.length() > 0; + } + + /** + * Gets the name of the file that the Apex CLI editor will save the Apex model to when it exits. + * + * @return the name of the file that the Apex CLI editor will save the Apex model to when it + * exits + */ + public String getOutputModelFileName() { + return outputModelFileName; + } + + /** + * Sets the name of the file that the Apex CLI editor will save the Apex model to when it exits. + * + * @param outputModelFileName the name of the file that the Apex CLI editor will save the Apex + * model to when it exits + */ + public void setOutputModelFileName(final String outputModelFileName) { + this.outputModelFileName = outputModelFileName.trim(); + } + + /** + * Check if the name of the file that the Apex CLI editor will save the Apex model to when it + * exits is set. + * + * @return true, if the name of the file that the Apex CLI editor will save the Apex model to + * when it exits is set + */ + public boolean checkSetOutputModelFileName() { + return outputModelFileName != null && outputModelFileName.length() > 0; + } + + /** + * Gets the working directory that is the root for CLI editor macro includes. + * + * @return the CLI editor working directory + */ + public String getWorkingDirectory() { + return workingDirectory; + } + + /** + * Sets the working directory that is the root for CLI editor macro includes. + * + * @param workingDirectory the CLI editor working directory + */ + public void setWorkingDirectory(final String workingDirectory) { + this.workingDirectory = workingDirectory.trim(); + } + + /** + * Gets the name of the file to which the Apex CLI editor will log commands and responses. + * + * @return the name of the file to which the Apex CLI editor will log commands and responses + */ + public String getLogFileName() { + return logFileName; + } + + /** + * Sets the name of the file to which the Apex CLI editor will log commands and responses. + * + * @param logFileName the name of the file to which the Apex CLI editor will log commands and + * responses + */ + public void setLogFileName(final String logFileName) { + this.logFileName = logFileName.trim(); + } + + /** + * Check if the name of the file to which the Apex CLI editor will log commands and responses is + * set. + * + * @return true, if the name of the file to which the Apex CLI editor will log commands and + * responses is set + */ + public boolean checkSetLogFileName() { + return logFileName != null; + } + + /** + * Checks if the Apex CLI editor is set to echo commands that have been entered. + * + * @return true, if the Apex CLI editor is set to echo commands that have been entered + */ + public boolean isEchoSet() { + return echo; + } + + /** + * Sets whether the Apex CLI editor should echo commands that have been entered. + * + * @param echo true, if the Apex CLI editor should echo commands that have been entered + */ + public void setEcho(final boolean echo) { + this.echo = echo; + } + + /** + * Checks whether the Apex CLI editor is set to suppress logging of command output. + * + * @return true, if the Apex CLI editor is set to suppress logging of command output. + */ + public boolean isSuppressLogSet() { + return suppressLog; + } + + /** + * Sets whether the Apex CLI editor should suppress logging of command output. + * + * @param suppressLog true, if the Apex CLI editor should suppress logging of command output + */ + public void setSuppressLog(final boolean suppressLog) { + this.suppressLog = suppressLog; + } + + /** + * Checks whether the Apex CLI editor is set to suppress output of its Apex model on exit. + * + * @return true, if checks if the Apex CLI editor is set to suppress output of its Apex model on + * exit + */ + public boolean isSuppressModelOutputSet() { + return suppressModelOutput; + } + + /** + * Sets whether the Apex CLI editor should suppress output of its Apex model on exit. + * + * @param suppressModelOutput true, if the Apex CLI editor should suppress output of its Apex + * model on exit + */ + public void setSuppressModelOutput(final boolean suppressModelOutput) { + this.suppressModelOutput = suppressModelOutput; + } + + /** + * Check if the command failures flag is set. + * + * @return true if the command failures flag has been set + */ + public boolean checkSetIgnoreCommandFailures() { + return ignoreCommandFailuresSet; + } + + /** + * Checks if the command failures flag is set. + * + * @param ignoreCommandFailuresSet true if the command failures flag has been set + */ + public void setIgnoreCommandFailuresSet(final boolean ignoreCommandFailuresSet) { + this.ignoreCommandFailuresSet = ignoreCommandFailuresSet; + } + + /** + * Checks if command failures should be ignored and command execution continue. + * + * @return true if command failures should be ignored + */ + public boolean isIgnoreCommandFailures() { + return ignoreCommandFailures; + } + + /** + * Sets if command errors should be ignored and command execution continue. + * + * @param ignoreCommandFailures true if command errors should be ignored + */ + public void setIgnoreCommandFailures(final boolean ignoreCommandFailures) { + this.ignoreCommandFailures = ignoreCommandFailures; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "CLIParameters [helpSet=" + helpSet + ", metadataFileName=" + metadataFileName + + ", apexPropertiesFileName=" + apexPropertiesFileName + ", commandFileName=" + commandFileName + + ", inputModelFileName=" + inputModelFileName + ", outputModelFileName=" + outputModelFileName + + ", logFileName=" + logFileName + ", echo=" + echo + ", suppressLog=" + suppressLog + + ", suppressModelOutput=" + suppressModelOutput + "]"; + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParser.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParser.java new file mode 100644 index 000000000..aa74f4ba3 --- /dev/null +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParser.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.auth.clieditor; + +import java.util.ArrayList; +import java.util.List; + +/** + * This class chops a command line up into commands, parameters and arguments. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CommandLineParser { + + /** + * This method breaks a line of input up into commands, parameters, and arguments. Commands are + * standalone words at the beginning of the line, of which there may be multiple Parameters are + * single words followed by an '=' character Arguments are single words or a block of quoted + * text following an '=' character. + * + *

Format: command [command....] parameter=argument [parameter = argument] + * + *

Examples entity create name=hello description="description of hello" help entity list + * + * @param line The line to parse + * @param logicBlock A block of logic code to be taken literally + * @return the string array list + */ + public List parse(final String line, final String logicBlock) { + return checkFormat( + mergeArguments(mergeEquals( + splitOnEquals(stripAndSplitWords(mergeQuotes(splitOnChar(stripComments(line), '\"')))))), + logicBlock); + } + + /** + * Strip comments from lines, comments start with a # character. + * + * @param line the line + * @return the line without comments + */ + private String stripComments(final String line) { + final int commentPos = line.indexOf('#'); + if (commentPos == -1) { + return line; + } else { + return line.substring(0, commentPos); + } + } + + /** + * This method merges an array with separate quotes into an array with quotes delimiting the + * start and end of quoted words Example [Humpty ],["],[Dumpty sat on the wall],["],[, Humpty + * Dumpty had ],["],["],a ["],[great],["],[ fall] becomes [Humpty ],["Dumpty sat on the + * wall"],[, Humpty Dumpty had ],[""],[a],["great"],[ fall]. + * + * @param wordsSplitOnQuotes the words split on quotes + * @return the merged array list + */ + private ArrayList mergeQuotes(final ArrayList wordsSplitOnQuotes) { + final ArrayList wordsWithQuotesMerged = new ArrayList<>(); + + for (int i = 0; i < wordsSplitOnQuotes.size();) { + if ("\"".equals(wordsSplitOnQuotes.get(i))) { + StringBuilder quotedWord = new StringBuilder(wordsSplitOnQuotes.get(i++)); + + for (; i < wordsSplitOnQuotes.size(); i++) { + quotedWord.append(wordsSplitOnQuotes.get(i)); + if ("\"".equals(wordsSplitOnQuotes.get(i))) { + i++; + break; + } + } + String quotedWordToString = quotedWord.toString(); + if (quotedWordToString.matches("^\".*\"$")) { + wordsWithQuotesMerged.add(quotedWordToString); + } else { + throw new CommandLineException("trailing quote found in input " + wordsSplitOnQuotes); + } + } else { + wordsWithQuotesMerged.add(wordsSplitOnQuotes.get(i++)); + } + } + + return wordsWithQuotesMerged; + } + + /** + * This method splits the words on an array list into an array list where each portion of the + * line is split into words by '=', quoted words are ignored Example: aaa = bbb = ccc=ddd=eee = + * becomes [aaa ],[=],[bbb ],[=],[ccc],[=],[ddd],[=],[eee ],[=]. + * + * @param words the words + * @return the merged array list + */ + private ArrayList splitOnEquals(final ArrayList words) { + final ArrayList wordsSplitOnEquals = new ArrayList<>(); + + for (final String word : words) { + // Is this a quoted word ? + if (word.startsWith("\"")) { + wordsSplitOnEquals.add(word); + continue; + } + + // Split on equals character + final ArrayList splitWords = splitOnChar(word, '='); + for (final String splitWord : splitWords) { + wordsSplitOnEquals.add(splitWord); + } + } + + return wordsSplitOnEquals; + } + + /** + * This method merges an array with separate equals into an array with equals delimiting the + * start of words Example: [aaa ],[=],[bbb ],[=],[ccc],[=],[ddd],[=],[eee ],[=] becomes [aaa + * ],[= bbb ],[= ccc],[=ddd],[=eee ],[=]. + * + * @param wordsSplitOnEquals the words split on equals + * @return the merged array list + */ + private ArrayList mergeEquals(final ArrayList wordsSplitOnEquals) { + final ArrayList wordsWithEqualsMerged = new ArrayList<>(); + + for (int i = 0; i < wordsSplitOnEquals.size();) { + // Is this a quoted word ? + if (wordsSplitOnEquals.get(i).startsWith("\"")) { + wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i)); + continue; + } + + if ("=".equals(wordsSplitOnEquals.get(i))) { + if (i < wordsSplitOnEquals.size() - 1 && !wordsSplitOnEquals.get(i + 1).startsWith("=")) { + wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i) + wordsSplitOnEquals.get(i + 1)); + i += 2; + } else { + wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i++)); + } + } else { + wordsWithEqualsMerged.add(wordsSplitOnEquals.get(i++)); + } + } + + return wordsWithEqualsMerged; + } + + /** + * This method merges words that start with an '=' character with the previous word if that word + * does not start with an '='. + * + * @param words the words + * @return the merged array list + */ + private ArrayList mergeArguments(final ArrayList words) { + final ArrayList mergedArguments = new ArrayList<>(); + + for (int i = 0; i < words.size(); i++) { + // Is this a quoted word ? + if (words.get(i).startsWith("\"")) { + mergedArguments.add(words.get(i)); + continue; + } + + if (words.get(i).startsWith("=")) { + if (i > 0 && !words.get(i - 1).startsWith("=")) { + mergedArguments.remove(mergedArguments.size() - 1); + mergedArguments.add(words.get(i - 1) + words.get(i)); + } else { + mergedArguments.add(words.get(i)); + } + } else { + mergedArguments.add(words.get(i)); + } + } + + return mergedArguments; + } + + /** + * This method strips all non quoted white space down to single spaces and splits non-quoted + * words into separate words. + * + * @param words the words + * @return the array list with white space stripped and words split + */ + private ArrayList stripAndSplitWords(final ArrayList words) { + final ArrayList strippedAndSplitWords = new ArrayList<>(); + + for (String word : words) { + // Is this a quoted word + if (word.startsWith("\"")) { + strippedAndSplitWords.add(word); + continue; + } + + // Strip white space by replacing all white space with blanks and then removing leading + // and trailing blanks + word = word.replaceAll("\\s+", " ").trim(); + + if (word.length() == 0) { + continue; + } + + // Split on space characters + final String[] splitWords = word.split(" "); + for (final String splitWord : splitWords) { + strippedAndSplitWords.add(splitWord); + } + } + + return strippedAndSplitWords; + } + + /** + * This method splits a line of text into an array list where each portion of the line is split + * into words by a character, with the characters themselves as separate words Example: Humpty + * "Dumpty sat on the wall", Humpty Dumpty had ""a "great" fall becomes [Humpty ],["],[Dumpty + * sat on the wall],["],[, Humpty Dumpty had ],["],["],a ["],[great],["],[ fall]. + * + * @param line the input line + * @param splitChar the split char + * @return the split array list + */ + private ArrayList splitOnChar(final String line, final char splitChar) { + final ArrayList wordsSplitOnQuotes = new ArrayList<>(); + + int currentPos = 0; + while (currentPos != -1) { + final int quotePos = line.indexOf(splitChar, currentPos); + if (quotePos != -1) { + if (currentPos < quotePos) { + wordsSplitOnQuotes.add(line.substring(currentPos, quotePos)); + } + wordsSplitOnQuotes.add("" + splitChar); + currentPos = quotePos + 1; + + if (currentPos == line.length()) { + currentPos = -1; + } + } else { + wordsSplitOnQuotes.add(line.substring(currentPos)); + currentPos = quotePos; + } + } + + return wordsSplitOnQuotes; + } + + /** + * This method checks that an array list containing a command is in the correct format. + * + * @param commandWords the command words + * @param logicBlock A block of logic code to be taken literally + * @return the checked array list + */ + private ArrayList checkFormat(final ArrayList commandWords, final String logicBlock) { + // There should be at least one word + if (commandWords.isEmpty()) { + return commandWords; + } + + // The first word must be alphanumeric, that is a command + if (!commandWords.get(0).matches("^[a-zA-Z0-9]*$")) { + throw new CommandLineException( + "first command word is not alphanumeric or is not a command: " + commandWords.get(0)); + } + + // Now check that we have a sequence of commands at the beginning + int currentWordPos = 0; + while (currentWordPos < commandWords.size()) { + if (commandWords.get(currentWordPos).matches("^[a-zA-Z0-9]*$")) { + currentWordPos++; + } else { + break; + } + } + + while (currentWordPos < commandWords.size()) { + // From now on we should have a sequence of parameters with arguments delimited by a + // single '=' character + if (currentWordPos < commandWords.size() - 1 || logicBlock == null) { + // No logic block + if (commandWords.get(currentWordPos).matches("^[a-zA-Z0-9]+=[a-zA-Z0-9/\"].*$")) { + currentWordPos++; + } else { + throw new CommandLineException( + "command argument is not properly formed: " + commandWords.get(currentWordPos)); + } + } else { + // Logic block + if (commandWords.get(currentWordPos).matches("^[a-zA-Z0-9]+=")) { + commandWords.set(currentWordPos, commandWords.get(currentWordPos) + logicBlock); + currentWordPos++; + } else { + throw new CommandLineException( + "command argument is not properly formed: " + commandWords.get(currentWordPos)); + } + } + } + + return commandWords; + } +} diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java index 6be5c6846..c8bc7a083 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java @@ -37,7 +37,7 @@ import org.onap.policy.apex.model.utilities.Assertions; public class KeywordNode implements Comparable { private final String keyword; private final TreeMap children; - private CLICommand command; + private CommandLineCommand command; /** * This Constructor creates a keyword node with the given keyword and no command. @@ -54,7 +54,7 @@ public class KeywordNode implements Comparable { * @param keyword the keyword of the keyword node * @param command the command associated with this keyword */ - public KeywordNode(final String keyword, final CLICommand command) { + public KeywordNode(final String keyword, final CommandLineCommand command) { Assertions.argumentNotNull(keyword, "commands may not be null"); this.keyword = keyword; @@ -70,7 +70,7 @@ public class KeywordNode implements Comparable { * @param keywordList the list of keywords to process on this keyword node * @param incomingCommand the command */ - public void processKeywords(final List keywordList, final CLICommand incomingCommand) { + public void processKeywords(final List keywordList, final CommandLineCommand incomingCommand) { if (keywordList.isEmpty()) { this.command = incomingCommand; return; @@ -128,7 +128,7 @@ public class KeywordNode implements Comparable { * * @return the command of this keyword node */ - public CLICommand getCommand() { + public CommandLineCommand getCommand() { return command; } @@ -147,8 +147,8 @@ public class KeywordNode implements Comparable { * * @return the commands */ - public Set getCommands() { - final Set commandSet = new TreeSet<>(); + public Set getCommands() { + final Set commandSet = new TreeSet<>(); for (final KeywordNode child : children.values()) { if (child.getCommand() != null) { diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorEventsContext.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorEventsContext.java deleted file mode 100644 index bd75ddf76..000000000 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorEventsContext.java +++ /dev/null @@ -1,161 +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.auth.clieditor; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.model.utilities.TextFileUtils; - -/** - * The Class TestCLIEditorEventsContext. - */ -public class TestCLIEditorEventsContext { - // CHECKSTYLE:OFF: MagicNumber - - private static final Path SRC_MAIN_FOLDER = Paths.get("src/main/resources/"); - private static final Path SRC_TEST_FOLDER = Paths.get("src/test/resources/"); - - private static final Path SUB_FOLDER = SRC_MAIN_FOLDER.resolve("examples/scripts/"); - - private static final String SPACES = "\\s+"; - private static final String EMPTY_STRING = ""; - - private static final Path APEX_AVRO_POLICY_FILE = SUB_FOLDER.resolve("TestPolicyAvroEventContext.apex"); - private static final Path APEX_JAVA_POLICY_FILE = SUB_FOLDER.resolve("TestPolicyJavaEventContext.apex"); - - private static final String FILE_NAME = "TestPolicyJavaEventsAndContext"; - private static final String JSON_FILE = FILE_NAME + ".json"; - private static final String LOG_FILE = FILE_NAME + ".log"; - - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - /** - * Test java context model. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if an Apex error happens - */ - @Test - public void testJavaContextModel() throws IOException, ApexModelException { - - final File tempLogFile = temporaryFolder.newFile(LOG_FILE); - final File tempModelFile = temporaryFolder.newFile(JSON_FILE); - - final String[] cliArgs = new String[] {"-c", APEX_JAVA_POLICY_FILE.toString(), "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()}; - - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Get the model and log into strings - final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); - final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); - - // As a sanity check, count the number of non white space characters in log and model files - final int logCharCount = logString.replaceAll(SPACES, EMPTY_STRING).length(); - final int modelCharCount = modelString.replaceAll(SPACES, EMPTY_STRING).length(); - - assertEquals(25962, logCharCount); - assertEquals(46189, modelCharCount); - } - - /** - * Test avro context model. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if an Apex error happens - */ - @Test - public void testAvroContextModel() throws IOException, ApexModelException { - - final File tempLogFile = temporaryFolder.newFile(LOG_FILE); - final File tempModelFile = temporaryFolder.newFile(JSON_FILE); - - final String[] cliArgs = new String[] {"-c", APEX_AVRO_POLICY_FILE.toString(), "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()}; - - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Get the model and log into strings - final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); - final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); - - // As a sanity check, count the number of non white space characters in log and model files - final int logCharCount = logString.replaceAll(SPACES, EMPTY_STRING).length(); - final int modelCharCount = modelString.replaceAll(SPACES, EMPTY_STRING).length(); - - assertEquals(30407, logCharCount); - assertEquals(53022, modelCharCount); - - } - - @Test - public void test_emptyMetadataCommandFileWithEmptyJsonTag_errorcountGreaterThanOne() throws IOException { - - final File tempLogFile = temporaryFolder.newFile(LOG_FILE); - final File tempModelFile = temporaryFolder.newFile(JSON_FILE); - - final String modelFile = SRC_TEST_FOLDER.resolve("model").resolve("empty_commands.json").toString(); - final String apexPropertiesLocation = - SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json").toString(); - - final String[] cliArgs = - new String[] {"-c", APEX_AVRO_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o", - tempModelFile.getAbsolutePath(), "-m", modelFile, "-a", apexPropertiesLocation}; - - final ApexCLIEditorMain objUnderTest = new ApexCLIEditorMain(cliArgs); - assertEquals(1, objUnderTest.getErrorCount()); - - } - - @Test - public void test_emptyMetadataCommandFile_errorcountGreaterThanOne() throws IOException { - - final File tempLogFile = temporaryFolder.newFile(LOG_FILE); - final File tempModelFile = temporaryFolder.newFile(JSON_FILE); - - final File modelFile = temporaryFolder.newFile("empty_commands.json"); - - final String apexPropertiesLocation = - SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json").toString(); - - final String[] cliArgs = new String[] {"-c", APEX_AVRO_POLICY_FILE.toString(), "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-m", modelFile.getAbsolutePath(), - "-a", apexPropertiesLocation}; - - final ApexCLIEditorMain objUnderTest = new ApexCLIEditorMain(cliArgs); - assertEquals(1, objUnderTest.getErrorCount()); - - } - -} diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorOptions.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorOptions.java deleted file mode 100644 index 2056c9239..000000000 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorOptions.java +++ /dev/null @@ -1,277 +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.auth.clieditor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.model.utilities.TextFileUtils; - -/** - * The Class TestCLIEditorOptions. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestCLIEditorOptions { - // CHECKSTYLE:OFF: MagicNumber - - /** - * Test script options log model. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testScriptOptionsLogModel() throws IOException, ApexModelException { - final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); - final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); - - final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()}; - - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Get the model and log into strings - final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); - final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); - - // As a sanity check, count the number of non white space characters in log and model files - final int logCharCount = logString.replaceAll("\\s+", "").length(); - final int modelCharCount = modelString.replaceAll("\\s+", "").length(); - - assertEquals(1204, logCharCount); - assertEquals(2924, modelCharCount); - - tempLogFile.delete(); - tempModelFile.delete(); - } - - /** - * Test script options no log no model spec. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testScriptOptionsNoLogNoModelSpec() throws IOException, ApexModelException { - final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); - final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); - - final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl", "-nm"}; - - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Get the model and log into strings - final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); - final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); - - // As a sanity check, count the number of non white space characters in log and model files - final int logCharCount = logString.replaceAll("\\s+", "").length(); - final int modelCharCount = modelString.replaceAll("\\s+", "").length(); - - assertEquals(0, logCharCount); - assertEquals(0, modelCharCount); - - tempLogFile.delete(); - tempModelFile.delete(); - } - - /** - * Test script options log no model spec. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testScriptOptionsLogNoModelSpec() throws IOException, ApexModelException { - final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); - final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); - - final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nm"}; - - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Get the model and log into strings - final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); - final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); - - System.err.println(modelString); - // As a sanity check, count the number of non white space characters in log and model files - final int logCharCount = logString.replaceAll("\\s+", "").length(); - final int modelCharCount = modelString.replaceAll("\\s+", "").length(); - - assertEquals(1204, logCharCount); - assertEquals(0, modelCharCount); - - tempLogFile.delete(); - tempModelFile.delete(); - } - - /** - * Test script options no log model spec. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testScriptOptionsNoLogModelSpec() throws IOException, ApexModelException { - final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); - final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); - - final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", - tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl"}; - - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Get the model and log into strings - final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); - final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); - - // As a sanity check, count the number of non white space characters in log and model files - final int logCharCount = logString.replaceAll("\\s+", "").length(); - final int modelCharCount = modelString.replaceAll("\\s+", "").length(); - - assertEquals(0, logCharCount); - assertEquals(2924, modelCharCount); - - tempLogFile.delete(); - tempModelFile.delete(); - } - - /** - * Test script options no log no model no spec. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testScriptOptionsNoLogNoModelNoSpec() throws IOException, ApexModelException { - final String[] cliArgs = - new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-nl", "-nm"}; - - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - System.setOut(new PrintStream(baos)); - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Cursor for log - assertFalse(baos.toString().contains(">")); - - // Curly bracket from JSON model - assertFalse(baos.toString().contains("{")); - } - - /** - * Test script options log model no spec. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testScriptOptionsLogModelNoSpec() throws IOException, ApexModelException { - final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex"}; - - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - final PrintStream stdout = System.out; - System.setOut(new PrintStream(baos)); - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(cliArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Cursor for log - assertTrue(baos.toString().contains(">")); - - // Curly bracket from JSON model - assertTrue(baos.toString().contains("{")); - - System.setOut(stdout); - } - - /** - * Test script options input output model. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testScriptOptionsInputOutputModel() throws IOException, ApexModelException { - final File tempLogFileIn = File.createTempFile("ShellPolicyModelIn", ".log"); - final File tempLogFileOut = File.createTempFile("ShellPolicyModelOut", ".log"); - final File tempModelFileIn = File.createTempFile("ShellPolicyModelIn", ".json"); - final File tempModelFileOut = File.createTempFile("ShellPolicyModelOut", ".json"); - - // Generate input model - final String[] cliArgsIn = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", - "-l", tempLogFileIn.getAbsolutePath(), "-o", tempModelFileIn.getAbsolutePath()}; - - final ApexCLIEditorMain cliEditorIn = new ApexCLIEditorMain(cliArgsIn); - assertEquals(0, cliEditorIn.getErrorCount()); - - // Get the model and log into strings - final String tempLogFileInString = TextFileUtils.getTextFileAsString(tempLogFileIn.getCanonicalPath()); - final String tempModelFileInString = TextFileUtils.getTextFileAsString(tempModelFileIn.getCanonicalPath()); - - // As a sanity check, count the number of non white space characters in log and model files - final int tempLogFileInCharCount = tempLogFileInString.replaceAll("\\s+", "").length(); - final int tempModelFileInCharCount = tempModelFileInString.replaceAll("\\s+", "").length(); - - assertEquals(1204, tempLogFileInCharCount); - assertEquals(2924, tempModelFileInCharCount); - - final String[] cliArgsOut = new String[] {"-i", tempModelFileIn.getAbsolutePath(), "-c", - "src/main/resources/examples/scripts/ShellPolicyModelAddSchema.apex", "-l", - tempLogFileOut.getAbsolutePath(), "-o", tempModelFileOut.getAbsolutePath()}; - - final ApexCLIEditorMain cliEditorOut = new ApexCLIEditorMain(cliArgsOut); - assertEquals(0, cliEditorOut.getErrorCount()); - - // Get the model and log into strings - final String tempLogFileOutString = TextFileUtils.getTextFileAsString(tempLogFileOut.getCanonicalPath()); - final String tempModelFileOutString = TextFileUtils.getTextFileAsString(tempModelFileOut.getCanonicalPath()); - - // As a sanity check, count the number of non white space characters in log and model files - final int tempLogFileOutCharCount = tempLogFileOutString.replaceAll("\\s+", "").length(); - final int tempModelFileOutCharCount = tempModelFileOutString.replaceAll("\\s+", "").length(); - - assertEquals(1154, tempLogFileOutCharCount); - assertEquals(3356, tempModelFileOutCharCount); - - tempLogFileIn.delete(); - tempModelFileIn.delete(); - tempLogFileOut.delete(); - tempModelFileOut.delete(); - } -} diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorScripting.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorScripting.java deleted file mode 100644 index 44cc5c702..000000000 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCLIEditorScripting.java +++ /dev/null @@ -1,132 +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.auth.clieditor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -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.handling.ApexModelException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * The Class TestCLIEditorScripting. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestCLIEditorScripting { - - private File tempModelFile; - private File tempLogFile; - - private String[] sampleLBPolicyArgs; - - private String[] sampleLBPolicyMapArgs; - - /** - * Initialise args. - * - * @throws IOException Signals that an I/O exception has occurred. - */ - @Before - public void initialiseArgs() throws IOException { - tempModelFile = File.createTempFile("SampleLBPolicyMap", ".json"); - tempLogFile = File.createTempFile("SampleLBPolicyMap", ".log"); - - sampleLBPolicyArgs = new String[] {"-c", "src/test/resources/scripts/SampleLBPolicy.apex", "-o", - tempModelFile.getAbsolutePath(), "-l", tempLogFile.getAbsolutePath()}; - - sampleLBPolicyMapArgs = new String[] {"-c", "src/test/resources/scripts/SampleLBPolicy_WithMap.apex", "-o", - tempModelFile.getAbsolutePath(), "-l", tempLogFile.getAbsolutePath()}; - } - - /** - * Removes the generated files. - */ - @After - public void removeGeneratedFiles() { - tempModelFile.delete(); - tempLogFile.delete(); - } - - /** - * Test sample Fuzzy LB policy script. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testSampleLBPolicyScript() throws IOException, ApexModelException { - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(sampleLBPolicyArgs); - assertEquals(0, cliEditor.getErrorCount()); - - // Read the file from disk - final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); - - final URL writtenModelURL = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); - final AxPolicyModel writtenModel = modelReader.read(writtenModelURL.openStream()); - - final URL compareModelURL = - ResourceUtils.getLocalFile("src/test/resources/compare/FuzzyPolicyModel_Compare.json"); - final AxPolicyModel compareModel = modelReader.read(compareModelURL.openStream()); - - // Ignore key info UUIDs - writtenModel.getKeyInformation().getKeyInfoMap().clear(); - compareModel.getKeyInformation().getKeyInfoMap().clear(); - - assertTrue(writtenModel.equals(compareModel)); - } - - /** - * Test sample Fuzzy LB map policy script. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException if there is an Apex error - */ - @Test - public void testSampleLBMapPolicyScript() throws IOException, ApexModelException { - tempModelFile.delete(); - - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(sampleLBPolicyMapArgs); - assertEquals(0, cliEditor.getErrorCount()); - - assertTrue(tempModelFile.isFile()); - - // Read the file from disk - final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); - - final URL writtenModelURL = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); - final AxPolicyModel writtenModel = modelReader.read(writtenModelURL.openStream()); - - final AxValidationResult validationResult = new AxValidationResult(); - writtenModel.validate(validationResult); - assertEquals(AxValidationResult.ValidationResult.OBSERVATION, validationResult.getValidationResult()); - } -} diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorEventsContext.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorEventsContext.java new file mode 100644 index 000000000..b0d82b6fa --- /dev/null +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorEventsContext.java @@ -0,0 +1,171 @@ +/*- + * ============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.auth.clieditor; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.model.utilities.TextFileUtils; + +/** + * The Class TestCLIEditorEventsContext. + */ +public class TestCommandLineEditorEventsContext { + // CHECKSTYLE:OFF: MagicNumber + + private static final Path SRC_MAIN_FOLDER = Paths.get("src/main/resources/"); + private static final Path SRC_TEST_FOLDER = Paths.get("src/test/resources/"); + + private static final Path SUB_FOLDER = SRC_MAIN_FOLDER.resolve("examples/scripts/"); + + private static final String SPACES = "\\s+"; + private static final String EMPTY_STRING = ""; + + private static final Path APEX_AVRO_POLICY_FILE = SUB_FOLDER.resolve("TestPolicyAvroEventContext.apex"); + private static final Path APEX_JAVA_POLICY_FILE = SUB_FOLDER.resolve("TestPolicyJavaEventContext.apex"); + + private static final String FILE_NAME = "TestPolicyJavaEventsAndContext"; + private static final String JSON_FILE = FILE_NAME + ".json"; + private static final String LOG_FILE = FILE_NAME + ".log"; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + /** + * Test java context model. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if an Apex error happens + */ + @Test + public void testJavaContextModel() throws IOException, ApexModelException { + + final File tempLogFile = temporaryFolder.newFile(LOG_FILE); + final File tempModelFile = temporaryFolder.newFile(JSON_FILE); + + final String[] cliArgs = new String[] + { "-c", APEX_JAVA_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o", + tempModelFile.getAbsolutePath() }; + + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Get the model and log into strings + final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); + final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); + + // As a sanity check, count the number of non white space characters in log and model files + final int logCharCount = logString.replaceAll(SPACES, EMPTY_STRING).length(); + final int modelCharCount = modelString.replaceAll(SPACES, EMPTY_STRING).length(); + + assertEquals(25962, logCharCount); + assertEquals(46189, modelCharCount); + } + + /** + * Test avro context model. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if an Apex error happens + */ + @Test + public void testAvroContextModel() throws IOException, ApexModelException { + + final File tempLogFile = temporaryFolder.newFile(LOG_FILE); + final File tempModelFile = temporaryFolder.newFile(JSON_FILE); + + final String[] cliArgs = new String[] + { "-c", APEX_AVRO_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o", + tempModelFile.getAbsolutePath() }; + + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Get the model and log into strings + final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); + final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); + + // As a sanity check, count the number of non white space characters in log and model files + final int logCharCount = logString.replaceAll(SPACES, EMPTY_STRING).length(); + final int modelCharCount = modelString.replaceAll(SPACES, EMPTY_STRING).length(); + + assertEquals(30407, logCharCount); + assertEquals(53022, modelCharCount); + + } + + @Test + public void test_emptyMetadataCommandFileWithEmptyJsonTag_errorcountGreaterThanOne() throws IOException { + + final File tempLogFile = temporaryFolder.newFile(LOG_FILE); + final File tempModelFile = temporaryFolder.newFile(JSON_FILE); + + final String modelFile = SRC_TEST_FOLDER.resolve("model").resolve("empty_commands.json").toString(); + final String apexPropertiesLocation = SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json") + .toString(); + + final String[] cliArgs = new String[] + { "-c", APEX_AVRO_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o", + tempModelFile.getAbsolutePath(), "-m", modelFile, "-a", apexPropertiesLocation }; + + final ApexCommandLineEditorMain objUnderTest = new ApexCommandLineEditorMain(cliArgs); + assertEquals(1, objUnderTest.getErrorCount()); + + } + + @Test + public void test_emptyMetadataCommandFile_errorcountGreaterThanOne() throws IOException { + + final File tempLogFile = temporaryFolder.newFile(LOG_FILE); + final File tempModelFile = temporaryFolder.newFile(JSON_FILE); + + final File modelFile = temporaryFolder.newFile("empty_commands.json"); + + final String apexPropertiesLocation = SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json") + .toString(); + + final String[] cliArgs = new String[] { + "-c", + APEX_AVRO_POLICY_FILE.toString(), + "-l", + tempLogFile.getAbsolutePath(), + "-o", + tempModelFile.getAbsolutePath(), + "-m", + modelFile.getAbsolutePath(), + "-a", + apexPropertiesLocation + }; + + final ApexCommandLineEditorMain objUnderTest = new ApexCommandLineEditorMain(cliArgs); + assertEquals(1, objUnderTest.getErrorCount()); + + } + +} diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorOptions.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorOptions.java new file mode 100644 index 000000000..5ff87c01b --- /dev/null +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorOptions.java @@ -0,0 +1,277 @@ +/*- + * ============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.auth.clieditor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.model.utilities.TextFileUtils; + +/** + * The Class TestCLIEditorOptions. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestCommandLineEditorOptions { + // CHECKSTYLE:OFF: MagicNumber + + /** + * Test script options log model. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testScriptOptionsLogModel() throws IOException, ApexModelException { + final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); + final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); + + final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", + tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()}; + + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Get the model and log into strings + final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); + final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); + + // As a sanity check, count the number of non white space characters in log and model files + final int logCharCount = logString.replaceAll("\\s+", "").length(); + final int modelCharCount = modelString.replaceAll("\\s+", "").length(); + + assertEquals(1204, logCharCount); + assertEquals(2924, modelCharCount); + + tempLogFile.delete(); + tempModelFile.delete(); + } + + /** + * Test script options no log no model spec. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testScriptOptionsNoLogNoModelSpec() throws IOException, ApexModelException { + final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); + final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); + + final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", + tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl", "-nm"}; + + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Get the model and log into strings + final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); + final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); + + // As a sanity check, count the number of non white space characters in log and model files + final int logCharCount = logString.replaceAll("\\s+", "").length(); + final int modelCharCount = modelString.replaceAll("\\s+", "").length(); + + assertEquals(0, logCharCount); + assertEquals(0, modelCharCount); + + tempLogFile.delete(); + tempModelFile.delete(); + } + + /** + * Test script options log no model spec. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testScriptOptionsLogNoModelSpec() throws IOException, ApexModelException { + final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); + final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); + + final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", + tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nm"}; + + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Get the model and log into strings + final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); + final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); + + System.err.println(modelString); + // As a sanity check, count the number of non white space characters in log and model files + final int logCharCount = logString.replaceAll("\\s+", "").length(); + final int modelCharCount = modelString.replaceAll("\\s+", "").length(); + + assertEquals(1204, logCharCount); + assertEquals(0, modelCharCount); + + tempLogFile.delete(); + tempModelFile.delete(); + } + + /** + * Test script options no log model spec. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testScriptOptionsNoLogModelSpec() throws IOException, ApexModelException { + final File tempLogFile = File.createTempFile("ShellPolicyModel", ".log"); + final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json"); + + final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l", + tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl"}; + + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Get the model and log into strings + final String logString = TextFileUtils.getTextFileAsString(tempLogFile.getCanonicalPath()); + final String modelString = TextFileUtils.getTextFileAsString(tempModelFile.getCanonicalPath()); + + // As a sanity check, count the number of non white space characters in log and model files + final int logCharCount = logString.replaceAll("\\s+", "").length(); + final int modelCharCount = modelString.replaceAll("\\s+", "").length(); + + assertEquals(0, logCharCount); + assertEquals(2924, modelCharCount); + + tempLogFile.delete(); + tempModelFile.delete(); + } + + /** + * Test script options no log no model no spec. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testScriptOptionsNoLogNoModelNoSpec() throws IOException, ApexModelException { + final String[] cliArgs = + new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-nl", "-nm"}; + + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + System.setOut(new PrintStream(baos)); + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Cursor for log + assertFalse(baos.toString().contains(">")); + + // Curly bracket from JSON model + assertFalse(baos.toString().contains("{")); + } + + /** + * Test script options log model no spec. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testScriptOptionsLogModelNoSpec() throws IOException, ApexModelException { + final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex"}; + + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + final PrintStream stdout = System.out; + System.setOut(new PrintStream(baos)); + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Cursor for log + assertTrue(baos.toString().contains(">")); + + // Curly bracket from JSON model + assertTrue(baos.toString().contains("{")); + + System.setOut(stdout); + } + + /** + * Test script options input output model. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testScriptOptionsInputOutputModel() throws IOException, ApexModelException { + final File tempLogFileIn = File.createTempFile("ShellPolicyModelIn", ".log"); + final File tempLogFileOut = File.createTempFile("ShellPolicyModelOut", ".log"); + final File tempModelFileIn = File.createTempFile("ShellPolicyModelIn", ".json"); + final File tempModelFileOut = File.createTempFile("ShellPolicyModelOut", ".json"); + + // Generate input model + final String[] cliArgsIn = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", + "-l", tempLogFileIn.getAbsolutePath(), "-o", tempModelFileIn.getAbsolutePath()}; + + final ApexCommandLineEditorMain cliEditorIn = new ApexCommandLineEditorMain(cliArgsIn); + assertEquals(0, cliEditorIn.getErrorCount()); + + // Get the model and log into strings + final String tempLogFileInString = TextFileUtils.getTextFileAsString(tempLogFileIn.getCanonicalPath()); + final String tempModelFileInString = TextFileUtils.getTextFileAsString(tempModelFileIn.getCanonicalPath()); + + // As a sanity check, count the number of non white space characters in log and model files + final int tempLogFileInCharCount = tempLogFileInString.replaceAll("\\s+", "").length(); + final int tempModelFileInCharCount = tempModelFileInString.replaceAll("\\s+", "").length(); + + assertEquals(1204, tempLogFileInCharCount); + assertEquals(2924, tempModelFileInCharCount); + + final String[] cliArgsOut = new String[] {"-i", tempModelFileIn.getAbsolutePath(), "-c", + "src/main/resources/examples/scripts/ShellPolicyModelAddSchema.apex", "-l", + tempLogFileOut.getAbsolutePath(), "-o", tempModelFileOut.getAbsolutePath()}; + + final ApexCommandLineEditorMain cliEditorOut = new ApexCommandLineEditorMain(cliArgsOut); + assertEquals(0, cliEditorOut.getErrorCount()); + + // Get the model and log into strings + final String tempLogFileOutString = TextFileUtils.getTextFileAsString(tempLogFileOut.getCanonicalPath()); + final String tempModelFileOutString = TextFileUtils.getTextFileAsString(tempModelFileOut.getCanonicalPath()); + + // As a sanity check, count the number of non white space characters in log and model files + final int tempLogFileOutCharCount = tempLogFileOutString.replaceAll("\\s+", "").length(); + final int tempModelFileOutCharCount = tempModelFileOutString.replaceAll("\\s+", "").length(); + + assertEquals(1154, tempLogFileOutCharCount); + assertEquals(3356, tempModelFileOutCharCount); + + tempLogFileIn.delete(); + tempModelFileIn.delete(); + tempLogFileOut.delete(); + tempModelFileOut.delete(); + } +} diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorScripting.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorScripting.java new file mode 100644 index 000000000..1b49fb362 --- /dev/null +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestCommandLineEditorScripting.java @@ -0,0 +1,132 @@ +/*- + * ============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.auth.clieditor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +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.handling.ApexModelException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * The Class TestCLIEditorScripting. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestCommandLineEditorScripting { + + private File tempModelFile; + private File tempLogFile; + + private String[] samplePolicyArgs; + + private String[] samplePolicyMapArgs; + + /** + * Initialise args. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Before + public void initialiseArgs() throws IOException { + tempModelFile = File.createTempFile("SampleLBPolicyMap", ".json"); + tempLogFile = File.createTempFile("SampleLBPolicyMap", ".log"); + + samplePolicyArgs = new String[] {"-c", "src/test/resources/scripts/SampleLBPolicy.apex", "-o", + tempModelFile.getAbsolutePath(), "-l", tempLogFile.getAbsolutePath()}; + + samplePolicyMapArgs = new String[] {"-c", "src/test/resources/scripts/SampleLBPolicy_WithMap.apex", "-o", + tempModelFile.getAbsolutePath(), "-l", tempLogFile.getAbsolutePath()}; + } + + /** + * Removes the generated files. + */ + @After + public void removeGeneratedFiles() { + tempModelFile.delete(); + tempLogFile.delete(); + } + + /** + * Test sample Fuzzy LB policy script. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testSamplePolicyScript() throws IOException, ApexModelException { + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(samplePolicyArgs); + assertEquals(0, cliEditor.getErrorCount()); + + // Read the file from disk + final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); + + final URL writtenModelUrl = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); + final AxPolicyModel writtenModel = modelReader.read(writtenModelUrl.openStream()); + + final URL compareModelUrl = + ResourceUtils.getLocalFile("src/test/resources/compare/FuzzyPolicyModel_Compare.json"); + final AxPolicyModel compareModel = modelReader.read(compareModelUrl.openStream()); + + // Ignore key info UUIDs + writtenModel.getKeyInformation().getKeyInfoMap().clear(); + compareModel.getKeyInformation().getKeyInfoMap().clear(); + + assertTrue(writtenModel.equals(compareModel)); + } + + /** + * Test sample Fuzzy LB map policy script. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException if there is an Apex error + */ + @Test + public void testSampleMapPolicyScript() throws IOException, ApexModelException { + tempModelFile.delete(); + + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(samplePolicyMapArgs); + assertEquals(0, cliEditor.getErrorCount()); + + assertTrue(tempModelFile.isFile()); + + // Read the file from disk + final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); + + final URL writtenModelUrl = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); + final AxPolicyModel writtenModel = modelReader.read(writtenModelUrl.openStream()); + + final AxValidationResult validationResult = new AxValidationResult(); + writtenModel.validate(validationResult); + assertEquals(AxValidationResult.ValidationResult.OBSERVATION, validationResult.getValidationResult()); + } +} diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestContextAlbums.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestContextAlbums.java index 1b99fce16..a45212007 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestContextAlbums.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestContextAlbums.java @@ -36,11 +36,19 @@ import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; import org.onap.policy.common.utils.resources.ResourceUtils; +/** + * The Class TestContextAlbums. + */ public class TestContextAlbums { private String[] logicBlockArgs; private File tempModelFile; + /** + * Creates the temp files. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void createTempFiles() throws IOException { tempModelFile = File.createTempFile("TestPolicyModel", ".json"); @@ -65,20 +73,20 @@ public class TestContextAlbums { */ @Test public void testLogicBlock() throws IOException, ApexModelException { - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(logicBlockArgs); + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(logicBlockArgs); assertEquals(1, cliEditor.getErrorCount()); // Read the file from disk final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); modelReader.setValidateFlag(false); - final URL writtenModelURL = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); - final AxPolicyModel writtenModel = modelReader.read(writtenModelURL.openStream()); + final URL writtenModelUrl = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); + final AxPolicyModel writtenModel = modelReader.read(writtenModelUrl.openStream()); assertNotNull(writtenModel); - final URL compareModelURL = + final URL compareModelUrl = ResourceUtils.getLocalFile("src/test/resources/compare/ContextAlbumsModel_Compare.json"); - final AxPolicyModel compareModel = modelReader.read(compareModelURL.openStream()); + final AxPolicyModel compareModel = modelReader.read(compareModelUrl.openStream()); // Ignore key info UUIDs writtenModel.getKeyInformation().getKeyInfoMap().clear(); diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestFileMacro.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestFileMacro.java index eb2f2a46b..3195bf025 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestFileMacro.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestFileMacro.java @@ -46,6 +46,11 @@ public class TestFileMacro { private File tempModelFile; private File tempLogFile; + /** + * Creates the temp files. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void createTempFiles() throws IOException { tempModelFile = File.createTempFile("TestPolicyModel", ".json"); @@ -55,6 +60,9 @@ public class TestFileMacro { tempLogFile.getCanonicalPath(), "-o", tempModelFile.getCanonicalPath(), "-if", "true"}; } + /** + * Removes the generated models. + */ @After public void removeGeneratedModels() { tempModelFile.delete(); @@ -68,7 +76,7 @@ public class TestFileMacro { */ @Test public void testLogicBlock() throws IOException, ApexModelException { - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(fileMacroArgs); + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(fileMacroArgs); // We expect eight errors assertEquals(8, cliEditor.getErrorCount()); @@ -76,12 +84,12 @@ public class TestFileMacro { final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); modelReader.setValidateFlag(false); - final URL writtenModelURL = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); - final AxPolicyModel writtenModel = modelReader.read(writtenModelURL.openStream()); + final URL writtenModelUrl = ResourceUtils.getLocalFile(tempModelFile.getCanonicalPath()); + final AxPolicyModel writtenModel = modelReader.read(writtenModelUrl.openStream()); - final URL compareModelURL = + final URL compareModelUrl = ResourceUtils.getLocalFile("src/test/resources/compare/FileMacroModel_Compare.json"); - final AxPolicyModel compareModel = modelReader.read(compareModelURL.openStream()); + final AxPolicyModel compareModel = modelReader.read(compareModelUrl.openStream()); // Ignore key info UUIDs writtenModel.getKeyInformation().getKeyInfoMap().clear(); diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestLogicBlock.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestLogicBlock.java index 591acb29a..1a4f75576 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestLogicBlock.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/TestLogicBlock.java @@ -34,6 +34,10 @@ import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; import org.onap.policy.common.utils.resources.ResourceUtils; +// TODO: Auto-generated Javadoc +/** + * The Class TestLogicBlock. + */ public class TestLogicBlock { private String[] logicBlockArgs; private String[] avroSchemaArgs; @@ -41,6 +45,11 @@ public class TestLogicBlock { private File tempLogicModelFile; private File tempAvroModelFile; + /** + * Creates the temp files. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void createTempFiles() throws IOException { tempLogicModelFile = File.createTempFile("TestLogicPolicyModel", ".json"); @@ -53,6 +62,9 @@ public class TestLogicBlock { tempAvroModelFile.getCanonicalPath(), "-nl"}; } + /** + * Removes the temp files. + */ @After public void removeTempFiles() { tempLogicModelFile.delete(); @@ -67,18 +79,18 @@ public class TestLogicBlock { */ @Test public void testLogicBlock() throws IOException, ApexModelException { - new ApexCLIEditorMain(logicBlockArgs); + new ApexCommandLineEditorMain(logicBlockArgs); // Read the file from disk final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); modelReader.setValidateFlag(false); - final URL writtenModelURL = ResourceUtils.getLocalFile(tempLogicModelFile.getCanonicalPath()); - final AxPolicyModel writtenModel = modelReader.read(writtenModelURL.openStream()); + final URL writtenModelUrl = ResourceUtils.getLocalFile(tempLogicModelFile.getCanonicalPath()); + final AxPolicyModel writtenModel = modelReader.read(writtenModelUrl.openStream()); - final URL compareModelURL = + final URL compareModelUrl = ResourceUtils.getLocalFile("src/test/resources/compare/LogicBlockModel_Compare.json"); - final AxPolicyModel compareModel = modelReader.read(compareModelURL.openStream()); + final AxPolicyModel compareModel = modelReader.read(compareModelUrl.openStream()); // Ignore key info UUIDs writtenModel.getKeyInformation().getKeyInfoMap().clear(); @@ -95,18 +107,18 @@ public class TestLogicBlock { */ @Test public void testAvroSchema() throws IOException, ApexModelException { - new ApexCLIEditorMain(avroSchemaArgs); + new ApexCommandLineEditorMain(avroSchemaArgs); // Read the file from disk final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); modelReader.setValidateFlag(false); - final URL writtenModelURL = ResourceUtils.getLocalFile(tempAvroModelFile.getCanonicalPath()); - final AxPolicyModel writtenModel = modelReader.read(writtenModelURL.openStream()); + final URL writtenModelUrl = ResourceUtils.getLocalFile(tempAvroModelFile.getCanonicalPath()); + final AxPolicyModel writtenModel = modelReader.read(writtenModelUrl.openStream()); - final URL compareModelURL = + final URL compareModelUrl = ResourceUtils.getLocalFile("src/test/resources/compare/AvroSchemaModel_Compare.json"); - final AxPolicyModel compareModel = modelReader.read(compareModelURL.openStream()); + final AxPolicyModel compareModel = modelReader.read(compareModelUrl.openStream()); // Ignore key info UUIDs writtenModel.getKeyInformation().getKeyInfoMap().clear(); diff --git a/client/client-deployment/pom.xml b/client/client-deployment/pom.xml index aacf34a02..b3814db74 100644 --- a/client/client-deployment/pom.xml +++ b/client/client-deployment/pom.xml @@ -96,7 +96,6 @@ org.apache.maven.plugins maven-resources-plugin - 3.1.0 copy-common-resources-to-jar @@ -137,7 +136,6 @@ org.apache.maven.plugins maven-shade-plugin - 2.4.3 package @@ -186,7 +184,6 @@ org.apache.maven.plugins maven-war-plugin - 2.6 ui src/main/resources/webapp diff --git a/client/client-editor/pom.xml b/client/client-editor/pom.xml index 3e250e0f4..9b4d53fab 100644 --- a/client/client-editor/pom.xml +++ b/client/client-editor/pom.xml @@ -122,7 +122,6 @@ org.apache.maven.plugins maven-resources-plugin - 3.1.0 copy-common-resources-to-jar @@ -163,7 +162,6 @@ org.apache.maven.plugins maven-shade-plugin - 2.4.3 package @@ -212,7 +210,6 @@ org.apache.maven.plugins maven-war-plugin - 2.6 ui src/main/resources/webapp diff --git a/client/client-full/pom.xml b/client/client-full/pom.xml index 788bb1534..e2605766e 100644 --- a/client/client-full/pom.xml +++ b/client/client-full/pom.xml @@ -109,7 +109,6 @@ org.apache.maven.plugins maven-shade-plugin - 2.4.3 package @@ -158,7 +157,6 @@ org.apache.maven.plugins maven-war-plugin - 2.6 ui target/classes/webapp diff --git a/client/client-monitoring/pom.xml b/client/client-monitoring/pom.xml index 274ac23f3..225c7e65b 100644 --- a/client/client-monitoring/pom.xml +++ b/client/client-monitoring/pom.xml @@ -91,7 +91,6 @@ org.apache.maven.plugins maven-resources-plugin - 3.1.0 copy-common-resources-to-jar @@ -132,7 +131,6 @@ org.apache.maven.plugins maven-shade-plugin - 2.4.3 package @@ -181,7 +179,6 @@ org.apache.maven.plugins maven-war-plugin - 2.6 ui src/main/resources/webapp diff --git a/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java b/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java index 042b2c22a..56368aeb4 100644 --- a/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java +++ b/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java @@ -108,7 +108,7 @@ public abstract class AbstractDistributor implements Distributor { } /** - * Set the static lock manager + * Set the static lock manager. * @param incomingLockManager the lock manager value */ private static void setLockManager(final LockManager incomingLockManager) { @@ -116,7 +116,7 @@ public abstract class AbstractDistributor implements Distributor { } /** - * Set the static flush timer + * Set the static flush timer. * @param incomingFlushTimer the flush timer value */ private static void setFlushTimer(final DistributorFlushTimerTask incomingFlushTimer) { diff --git a/context/context-test-utils/src/test/java/org/onap/policy/apex/context/test/persistence/TestPersistentContextInstantiation.java b/context/context-test-utils/src/test/java/org/onap/policy/apex/context/test/persistence/TestPersistentContextInstantiation.java index 290f22794..a659326a0 100644 --- a/context/context-test-utils/src/test/java/org/onap/policy/apex/context/test/persistence/TestPersistentContextInstantiation.java +++ b/context/context-test-utils/src/test/java/org/onap/policy/apex/context/test/persistence/TestPersistentContextInstantiation.java @@ -126,9 +126,11 @@ public class TestPersistentContextInstantiation { final AxArtifactKey distributorKey = new AxArtifactKey("AbstractDistributor", "0.0.1"); final Distributor contextDistributor = new DistributorFactory().getDistributor(distributorKey); - final AxArtifactKey[] usedArtifactStackArray = - { new AxArtifactKey("testC-top", "0.0.1"), new AxArtifactKey("testC-next", "0.0.1"), - new AxArtifactKey("testC-bot", "0.0.1") }; + final AxArtifactKey[] usedArtifactStackArray = { + new AxArtifactKey("testC-top", "0.0.1"), + new AxArtifactKey("testC-next", "0.0.1"), + new AxArtifactKey("testC-bot", "0.0.1") + }; final DaoParameters DaoParameters = new DaoParameters(); DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); diff --git a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/ApexDeploymentException.java b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/ApexDeploymentException.java index e932bbd45..5944b9f0d 100644 --- a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/ApexDeploymentException.java +++ b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/ApexDeploymentException.java @@ -43,9 +43,9 @@ public class ApexDeploymentException extends ApexException { * Instantiates a new apex deployment exception. * * @param message the message - * @param e the e + * @param exception the e */ - public ApexDeploymentException(final String message, final Exception e) { - super(message, e); + public ApexDeploymentException(final String message, final Exception exception) { + super(message, exception); } } diff --git a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/MessagingException.java b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/MessagingException.java index ef435b2a5..dfaf4629f 100644 --- a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/MessagingException.java +++ b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/MessagingException.java @@ -41,9 +41,9 @@ public class MessagingException extends Exception { * Instantiates a new messaging exception. * * @param message the message - * @param e the e + * @param exception the e */ - public MessagingException(final String message, final Exception e) { - super(message, e); + public MessagingException(final String message, final Exception exception) { + super(message, exception); } } diff --git a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/threading/ApplicationThreadFactory.java b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/threading/ApplicationThreadFactory.java index 45579c7ba..0d5f30737 100644 --- a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/threading/ApplicationThreadFactory.java +++ b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/threading/ApplicationThreadFactory.java @@ -78,12 +78,12 @@ public class ApplicationThreadFactory implements ThreadFactory { * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) */ @Override - public Thread newThread(final Runnable r) { + public Thread newThread(final Runnable runnable) { final Thread thisThread; if (stackSize > 0) { - thisThread = new Thread(group, r, name + ':' + nextThreadNumber.getAndIncrement(), stackSize); + thisThread = new Thread(group, runnable, name + ':' + nextThreadNumber.getAndIncrement(), stackSize); } else { - thisThread = new Thread(group, r, name + ':' + nextThreadNumber.getAndIncrement()); + thisThread = new Thread(group, runnable, name + ':' + nextThreadNumber.getAndIncrement()); } if (thisThread.isDaemon()) { thisThread.setDaemon(false); diff --git a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/xml/XPathReader.java b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/xml/XPathReader.java index f677e6b4a..bd2474339 100644 --- a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/xml/XPathReader.java +++ b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/xml/XPathReader.java @@ -45,7 +45,7 @@ public class XPathReader { private String xmlFileName = null; private InputStream xmlStream = null; private Document xmlDocument; - private XPath xPath; + private XPath xpath; /** * Construct Reader for the file passed in. @@ -89,7 +89,7 @@ public class XPathReader { return; } - xPath = XPathFactory.newInstance().newXPath(); + xpath = XPathFactory.newInstance().newXPath(); LOGGER.info("Initialized XPath reader"); } catch (final Exception ex) { LOGGER.error("Error parsing XML file/stream from XPath reading, reason :\n" + ex.getMessage()); @@ -105,7 +105,7 @@ public class XPathReader { */ public Object read(final String expression, final QName returnType) { try { - final XPathExpression xPathExpression = xPath.compile(expression); + final XPathExpression xPathExpression = xpath.compile(expression); return xPathExpression.evaluate(xmlDocument, returnType); } catch (final XPathExpressionException ex) { LOGGER.error("Failed to read XML file for XPath processing, reason:\n" + ex.getMessage()); diff --git a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Action.java b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Action.java index 62a2e0a75..00d8055be 100644 --- a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Action.java +++ b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Action.java @@ -29,7 +29,7 @@ package org.onap.policy.apex.core.protocols; public interface Action { /** - * This method returns a string representation of each action. + * Return a string representation of each action. * * @return the action string */ diff --git a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java index 73465cef6..95f786cad 100644 --- a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java +++ b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java @@ -146,15 +146,15 @@ public abstract class Message implements Serializable { * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(final Object o) { - if (this == o) { + public boolean equals(final Object object) { + if (this == object) { return true; } - if (o == null || getClass() != o.getClass()) { + if (object == null || getClass() != object.getClass()) { return false; } - final Message message = (Message) o; + final Message message = (Message) object; if (action != null ? !action.equals(message.action) : message.action != null) { return false; diff --git a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/engdep/messages/Response.java b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/engdep/messages/Response.java index 69e36baed..530e1aba7 100644 --- a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/engdep/messages/Response.java +++ b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/engdep/messages/Response.java @@ -99,18 +99,18 @@ public class Response extends Message { * @see org.onap.policy.apex.core.protocols.Message#equals(java.lang.Object) */ @Override - public boolean equals(final Object o) { - if (this == o) { + public boolean equals(final Object object) { + if (this == object) { return true; } - if (o == null || getClass() != o.getClass()) { + if (object == null || getClass() != object.getClass()) { return false; } - if (!super.equals(o)) { + if (!super.equals(object)) { return false; } - final Response response = (Response) o; + final Response response = (Response) object; if (successful != response.successful) { return false; diff --git a/examples/examples-aadm/pom.xml b/examples/examples-aadm/pom.xml index 272aee8fd..0dd91dcde 100644 --- a/examples/examples-aadm/pom.xml +++ b/examples/examples-aadm/pom.xml @@ -80,7 +80,7 @@ -classpath - org.onap.policy.apex.examples.aadm.model.AADMDomainModelSaver + org.onap.policy.apex.examples.aadm.model.AadmDomainModelSaver ${project.build.directory}/classes/examples/models/AADM diff --git a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ENodeBStatus.java b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ENodeBStatus.java index 1f3cf5185..70af74ab9 100644 --- a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ENodeBStatus.java +++ b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ENodeBStatus.java @@ -56,7 +56,7 @@ public class ENodeBStatus implements Serializable { * * @return the number of Denial Of Service incidents on the eNodeB */ - public long getDOSCount() { + public long getDosCount() { return dosCount; } @@ -65,7 +65,7 @@ public class ENodeBStatus implements Serializable { * * @param incomingDosCount the number of Denial Of Service incidents on the eNodeB */ - public void setDOSCount(final long incomingDosCount) { + public void setDosCount(final long incomingDosCount) { this.dosCount = incomingDosCount; } @@ -74,7 +74,7 @@ public class ENodeBStatus implements Serializable { * * @return the long */ - public long incrementDOSCount() { + public long incrementDosCount() { return ++dosCount; } @@ -83,7 +83,7 @@ public class ENodeBStatus implements Serializable { * * @return the long */ - public long decrementDOSCount() { + public long decrementDosCount() { return --dosCount; } diff --git a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IMSIStatus.java b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IMSIStatus.java deleted file mode 100644 index 8f89d4c15..000000000 --- a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IMSIStatus.java +++ /dev/null @@ -1,175 +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.aadm.concepts; - -import java.io.Serializable; - -/** - * The Class IMSIStatus holds the status of an IMSI in the AADM domain. - */ -public class IMSIStatus implements Serializable { - private static final long serialVersionUID = 2852523814242234172L; - - private static final long TIME_NOT_SET = 0; - - private final String imsi; - - private boolean anomalous = false; - private long anomalousTime = TIME_NOT_SET; - private String enodeBId; - private long blackListedTime = TIME_NOT_SET; - private long blockingCount = 0; - - /** - * Initiate an IMSI status instance with an IMSI value. - * - * @param imsi the IMSI value - */ - public IMSIStatus(final String imsi) { - this.imsi = imsi; - } - - /** - * Gets the IMSI value. - * - * @return the IMSI value - */ - public String getIMSI() { - return imsi; - } - - /** - * Gets the anomalous flag. - * - * @return the anomalous flag - */ - public boolean getAnomalous() { - return anomalous; - } - - /** - * Sets the anomalous flag. - * - * @param anomalous the anomalous flag - */ - public void setAnomalous(final boolean anomalous) { - this.anomalous = anomalous; - } - - /** - * Gets the time of the most recent anomolous event. - * - * @return the time of the most recent anomolous event - */ - public long getAnomolousTime() { - return anomalousTime; - } - - /** - * Sets the time of the most recent anomolous event. - * - * @param incomingAnomalousTime the time of the most recent anomolous event - */ - public void setAnomolousTime(final long incomingAnomalousTime) { - this.anomalousTime = incomingAnomalousTime; - } - - /** - * Gets the eNodeB ID to which the IMSI is attached. - * - * @return theeNodeB ID to which the IMSI is attached - */ - public String getENodeBID() { - return enodeBId; - } - - /** - * Sets the eNodeB ID to which the IMSI is attached. - * - * @param incomingENodeBID the eNodeB ID to which the IMSI is attached - */ - public void setENodeBID(final String incomingENodeBID) { - this.enodeBId = incomingENodeBID; - } - - /** - * Checks if the eNodeB ID to which the IMSI is attached is set. - * - * @return true, if eNodeB ID to which the IMSI is attached is set - */ - public boolean checkSetENodeBID() { - return (enodeBId != null); - } - - /** - * Gets the time at which the IMSI was blacklisted. - * - * @return the time at which the IMSI was blacklisted - */ - public long getBlacklistedTime() { - return blackListedTime; - } - - /** - * Sets the time at which the IMSI was blacklisted. - * - * @param incomingBlackListedTime the time at which the IMSI was blacklisted - */ - public void setBlacklistedTime(final long incomingBlackListedTime) { - this.blackListedTime = incomingBlackListedTime; - } - - /** - * Gets the number of times this IMSI was blocked. - * - * @return the number of times this IMSI was blocked - */ - public long getBlockingCount() { - return blockingCount; - } - - /** - * Sets the number of times this IMSI was blocked. - * - * @param blockingCount the number of times this IMSI was blocked - */ - public void setBlockingCount(final long blockingCount) { - this.blockingCount = blockingCount; - } - - /** - * Increment the number of times this IMSI was blocked. - * - * @return the incremented number of times this IMSI was blocked - */ - public long incrementBlockingCount() { - return ++blockingCount; - } - - /** - * Decrement the number of times this IMSI was blocked. - * - * @return the decremented number of times this IMSI was blocked - */ - public long decrementBlockingCount() { - return --blockingCount; - } -} diff --git a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IPAddressStatus.java b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IPAddressStatus.java deleted file mode 100644 index fc3780f17..000000000 --- a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IPAddressStatus.java +++ /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========================================================= - */ - -package org.onap.policy.apex.examples.aadm.concepts; - -import java.io.Serializable; - -/** - * The Class IPAddressStatus holds the status of an IP address in the AADM domain. - */ -public class IPAddressStatus implements Serializable { - private static final long serialVersionUID = -7402022458317593252L; - - private final String ipAddress; - - private String imsi; - - /** - * The Constructor sets up the IP address status instance. - * - * @param ipAddress the ip address - */ - public IPAddressStatus(final String ipAddress) { - this.ipAddress = ipAddress; - } - - /** - * Gets the IP address. - * - * @return the IP address - */ - public String getIPAddress() { - return ipAddress; - } - - /** - * Gets the IMSI. - * - * @return the imsi - */ - public String getIMSI() { - return imsi; - } - - /** - * Sets the IMSI. - * - * @param incomingImsi the imsi - */ - public void setIMSI(final String incomingImsi) { - this.imsi = incomingImsi; - } - - /** - * Check set IMSI. - * - * @return true, if check set IMSI - */ - public boolean checkSetIMSI() { - return (imsi != null); - } -} diff --git a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ImsiStatus.java b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ImsiStatus.java new file mode 100644 index 000000000..4b7def097 --- /dev/null +++ b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/ImsiStatus.java @@ -0,0 +1,175 @@ +/*- + * ============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.aadm.concepts; + +import java.io.Serializable; + +/** + * The Class IMSIStatus holds the status of an IMSI in the AADM domain. + */ +public class ImsiStatus implements Serializable { + private static final long serialVersionUID = 2852523814242234172L; + + private static final long TIME_NOT_SET = 0; + + private final String imsi; + + private boolean anomalous = false; + private long anomalousTime = TIME_NOT_SET; + private String enodeBId; + private long blackListedTime = TIME_NOT_SET; + private long blockingCount = 0; + + /** + * Initiate an IMSI status instance with an IMSI value. + * + * @param imsi the IMSI value + */ + public ImsiStatus(final String imsi) { + this.imsi = imsi; + } + + /** + * Gets the IMSI value. + * + * @return the IMSI value + */ + public String getImsi() { + return imsi; + } + + /** + * Gets the anomalous flag. + * + * @return the anomalous flag + */ + public boolean getAnomalous() { + return anomalous; + } + + /** + * Sets the anomalous flag. + * + * @param anomalous the anomalous flag + */ + public void setAnomalous(final boolean anomalous) { + this.anomalous = anomalous; + } + + /** + * Gets the time of the most recent anomolous event. + * + * @return the time of the most recent anomolous event + */ + public long getAnomolousTime() { + return anomalousTime; + } + + /** + * Sets the time of the most recent anomolous event. + * + * @param incomingAnomalousTime the time of the most recent anomolous event + */ + public void setAnomolousTime(final long incomingAnomalousTime) { + this.anomalousTime = incomingAnomalousTime; + } + + /** + * Gets the eNodeB ID to which the IMSI is attached. + * + * @return theeNodeB ID to which the IMSI is attached + */ + public String getENodeBId() { + return enodeBId; + } + + /** + * Sets the eNodeB ID to which the IMSI is attached. + * + * @param incomingENodeBId the eNodeB ID to which the IMSI is attached + */ + public void setENodeBId(final String incomingENodeBId) { + this.enodeBId = incomingENodeBId; + } + + /** + * Checks if the eNodeB ID to which the IMSI is attached is set. + * + * @return true, if eNodeB ID to which the IMSI is attached is set + */ + public boolean checkSetENodeBId() { + return (enodeBId != null); + } + + /** + * Gets the time at which the IMSI was blacklisted. + * + * @return the time at which the IMSI was blacklisted + */ + public long getBlacklistedTime() { + return blackListedTime; + } + + /** + * Sets the time at which the IMSI was blacklisted. + * + * @param incomingBlackListedTime the time at which the IMSI was blacklisted + */ + public void setBlacklistedTime(final long incomingBlackListedTime) { + this.blackListedTime = incomingBlackListedTime; + } + + /** + * Gets the number of times this IMSI was blocked. + * + * @return the number of times this IMSI was blocked + */ + public long getBlockingCount() { + return blockingCount; + } + + /** + * Sets the number of times this IMSI was blocked. + * + * @param blockingCount the number of times this IMSI was blocked + */ + public void setBlockingCount(final long blockingCount) { + this.blockingCount = blockingCount; + } + + /** + * Increment the number of times this IMSI was blocked. + * + * @return the incremented number of times this IMSI was blocked + */ + public long incrementBlockingCount() { + return ++blockingCount; + } + + /** + * Decrement the number of times this IMSI was blocked. + * + * @return the decremented number of times this IMSI was blocked + */ + public long decrementBlockingCount() { + return --blockingCount; + } +} diff --git a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IpAddressStatus.java b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IpAddressStatus.java new file mode 100644 index 000000000..689865b16 --- /dev/null +++ b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/concepts/IpAddressStatus.java @@ -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========================================================= + */ + +package org.onap.policy.apex.examples.aadm.concepts; + +import java.io.Serializable; + +/** + * The Class IPAddressStatus holds the status of an IP address in the AADM domain. + */ +public class IpAddressStatus implements Serializable { + private static final long serialVersionUID = -7402022458317593252L; + + private final String ipAddress; + + private String imsi; + + /** + * The Constructor sets up the IP address status instance. + * + * @param ipAddress the ip address + */ + public IpAddressStatus(final String ipAddress) { + this.ipAddress = ipAddress; + } + + /** + * Gets the IP address. + * + * @return the IP address + */ + public String getIpAddress() { + return ipAddress; + } + + /** + * Gets the IMSI. + * + * @return the imsi + */ + public String getImsi() { + return imsi; + } + + /** + * Sets the IMSI. + * + * @param incomingImsi the imsi + */ + public void setImsi(final String incomingImsi) { + this.imsi = incomingImsi; + } + + /** + * Check set IMSI. + * + * @return true, if check set IMSI + */ + public boolean checkSetImsi() { + return (imsi != null); + } +} 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 deleted file mode 100644 index 9a2d50626..000000000 --- a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AADMDomainModelFactory.java +++ /dev/null @@ -1,703 +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.aadm.model; - -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.AxTaskSelectionLogic; -import org.onap.policy.apex.model.policymodel.concepts.AxTasks; -import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; - -/** - * The Class AADMDomainModelFactory. - */ -public class AADMDomainModelFactory { - /** - * Gets the AADM policy model. - * - * @return the AADM policy model - */ - // CHECKSTYLE:OFF: checkstyle - 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")); - aadmContextSchemas.getSchemasMap().put(imsi.getKey(), imsi); - aadmContextSchemas.getSchemasMap().put(ueIPAddress.getKey(), ueIPAddress); - aadmContextSchemas.getSchemasMap().put(nwIPAddress.getKey(), nwIPAddress); - aadmContextSchemas.getSchemasMap().put(dosFlag.getKey(), dosFlag); - aadmContextSchemas.getSchemasMap().put(roundTripTime.getKey(), roundTripTime); - aadmContextSchemas.getSchemasMap().put(applicationName.getKey(), applicationName); - aadmContextSchemas.getSchemasMap().put(protocolGroup.getKey(), protocolGroup); - aadmContextSchemas.getSchemasMap().put(eNodeBID.getKey(), eNodeBID); - aadmContextSchemas.getSchemasMap().put(httpHostClass.getKey(), httpHostClass); - aadmContextSchemas.getSchemasMap().put(tcpOnFlag.getKey(), tcpOnFlag); - aadmContextSchemas.getSchemasMap().put(probeOnFlag.getKey(), probeOnFlag); - aadmContextSchemas.getSchemasMap().put(blacklistOnFlag.getKey(), blacklistOnFlag); - aadmContextSchemas.getSchemasMap().put(averageThroughput.getKey(), averageThroughput); - aadmContextSchemas.getSchemasMap().put(serviceRequestCount.getKey(), serviceRequestCount); - aadmContextSchemas.getSchemasMap().put(attchCount.getKey(), attchCount); - aadmContextSchemas.getSchemasMap().put(subscriberCount.getKey(), subscriberCount); - aadmContextSchemas.getSchemasMap().put(averageServiceRequest.getKey(), averageServiceRequest); - aadmContextSchemas.getSchemasMap().put(averageAttach.getKey(), averageAttach); - aadmContextSchemas.getSchemasMap().put(actionTask.getKey(), actionTask); - aadmContextSchemas.getSchemasMap().put(version.getKey(), version); - aadmContextSchemas.getSchemasMap().put(profile.getKey(), profile); - aadmContextSchemas.getSchemasMap().put(threshold.getKey(), threshold); - aadmContextSchemas.getSchemasMap().put(triggerSpec.getKey(), triggerSpec); - aadmContextSchemas.getSchemasMap().put(periodicEventCount.getKey(), periodicEventCount); - 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"); - 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())); - 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())); - aadmEvent.getParameterMap().put("protocol_group", - 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())); - aadmEvent.getParameterMap().put("SGW_IP_ADDRESS", - 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())); - aadmEvent.getParameterMap().put("SERVICE_REQUEST_COUNT", new AxField( - 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())); - 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"); - aadmXStreamActEvent.setSource("Apex"); - aadmXStreamActEvent.setTarget("External"); - 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())); - 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"); - 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"); - 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"); - sapcBlacklistSubscriberEvent.setSource("Apex"); - sapcBlacklistSubscriberEvent.setTarget("External"); - 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"); - 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_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())); - - final AxEvents aadmEvents = new AxEvents(new AxArtifactKey("AADMEvents", "0.0.1")); - aadmEvents.getEventMap().put(aadmEvent.getKey(), aadmEvent); - aadmEvents.getEventMap().put(aadmXStreamActEvent.getKey(), aadmXStreamActEvent); - aadmEvents.getEventMap().put(vMMEEvent.getKey(), vMMEEvent); - aadmEvents.getEventMap().put(sapcEvent.getKey(), sapcEvent); - aadmEvents.getEventMap().put(sapcBlacklistSubscriberEvent.getKey(), sapcBlacklistSubscriberEvent); - 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"); - 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 ipAddressStatusAlbum = new AxContextAlbum( - new AxArtifactKey("IPAddressStatusAlbum", "0.0.1"), "APPLICATION", true, ipAddressStatus.getKey()); - - final AxContextAlbums aadmAlbums = new AxContextAlbums(new AxArtifactKey("AADMContext", "0.0.1")); - 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 AxTask aadmMatchTask = new AxTask(new AxArtifactKey("AADMMatchTask", "0.0.1")); - 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)); - - final AxTask aadmEstablishTask = new AxTask(new AxArtifactKey("AADMEstablishTask", "0.0.1")); - aadmEstablishTask.duplicateInputFields(aadmEvent.getParameterMap()); - aadmEstablishTask.duplicateOutputFields(aadmEvent.getParameterMap()); - logicReader.setDefaultLogic("Default_TaskLogic"); - aadmEstablishTask.setTaskLogic(new AxTaskLogic(aadmEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask aadmDecideTask = new AxTask(new AxArtifactKey("AADMDecideTask", "0.0.1")); - aadmDecideTask.duplicateInputFields(aadmEvent.getParameterMap()); - aadmDecideTask.duplicateOutputFields(aadmEvent.getParameterMap()); - aadmDecideTask.setTaskLogic(new AxTaskLogic(aadmDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - logicReader.setDefaultLogic(null); - - final AxTask aadmDoSSuggestionActTask = new AxTask(new AxArtifactKey("AADMDoSSuggestionActTask", "0.0.1")); - 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)); - - final AxTask aadmNoActTask = new AxTask(new AxArtifactKey("AADMNoActTask", "0.0.1")); - aadmNoActTask.duplicateInputFields(aadmEvent.getParameterMap()); - aadmNoActTask.duplicateOutputFields(aadmXStreamActEvent.getParameterMap()); - aadmNoActTask.setTaskLogic(new AxTaskLogic(aadmNoActTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask aadmDoSProvenActTask = new AxTask(new AxArtifactKey("AADMDoSProvenActTask", "0.0.1")); - 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)); - - final AxTask vMMEMatchTask = new AxTask(new AxArtifactKey("VMMEMatchTask", "0.0.1")); - vMMEMatchTask.duplicateInputFields(vMMEEvent.getParameterMap()); - vMMEMatchTask.duplicateOutputFields(vMMEEvent.getParameterMap()); - vMMEMatchTask.setTaskLogic(new AxTaskLogic(vMMEMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask vMMEEstablishTask = new AxTask(new AxArtifactKey("VMMEEstablishTask", "0.0.1")); - vMMEEstablishTask.duplicateInputFields(vMMEEvent.getParameterMap()); - vMMEEstablishTask.duplicateOutputFields(vMMEEvent.getParameterMap()); - logicReader.setDefaultLogic("Default_TaskLogic"); - vMMEEstablishTask.setTaskLogic(new AxTaskLogic(vMMEEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask vMMEDecideTask = new AxTask(new AxArtifactKey("VMMEDecideTask", "0.0.1")); - vMMEDecideTask.duplicateInputFields(vMMEEvent.getParameterMap()); - vMMEDecideTask.duplicateOutputFields(vMMEEvent.getParameterMap()); - vMMEDecideTask.setTaskLogic(new AxTaskLogic(vMMEDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask vMMENoActTask = new AxTask(new AxArtifactKey("VMMENoActTask", "0.0.1")); - vMMENoActTask.duplicateInputFields(vMMEEvent.getParameterMap()); - vMMENoActTask.duplicateOutputFields(vMMEEvent.getParameterMap()); - vMMENoActTask.setTaskLogic(new AxTaskLogic(vMMENoActTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask vMMEActTask = new AxTask(new AxArtifactKey("VMMEActTask", "0.0.1")); - vMMEActTask.duplicateInputFields(vMMEEvent.getParameterMap()); - vMMEActTask.duplicateOutputFields(vMMEEvent.getParameterMap()); - logicReader.setDefaultLogic(null); - vMMEActTask.setTaskLogic(new AxTaskLogic(vMMEActTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask sapcMatchTask = new AxTask(new AxArtifactKey("SAPCMatchTask", "0.0.1")); - sapcMatchTask.duplicateInputFields(sapcEvent.getParameterMap()); - sapcMatchTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); - sapcMatchTask.setTaskLogic(new AxTaskLogic(sapcMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask sapcEstablishTask = new AxTask(new AxArtifactKey("SAPCEstablishTask", "0.0.1")); - sapcEstablishTask.duplicateInputFields(sapcEvent.getParameterMap()); - sapcEstablishTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); - logicReader.setDefaultLogic("Default_TaskLogic"); - sapcEstablishTask.setTaskLogic(new AxTaskLogic(sapcEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask sapcDecideTask = new AxTask(new AxArtifactKey("SAPCDecideTask", "0.0.1")); - sapcDecideTask.duplicateInputFields(sapcEvent.getParameterMap()); - sapcDecideTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); - sapcDecideTask.setTaskLogic(new AxTaskLogic(sapcDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask sapcActTask = new AxTask(new AxArtifactKey("SAPCActTask", "0.0.1")); - 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)); - - logicReader.setDefaultLogic("Default_TaskLogic"); - - final AxTask periodicMatchTask = new AxTask(new AxArtifactKey("PeriodicMatchTask", "0.0.1")); - periodicMatchTask.duplicateInputFields(periodicEvent.getParameterMap()); - periodicMatchTask.duplicateOutputFields(periodicEvent.getParameterMap()); - periodicMatchTask.setTaskLogic(new AxTaskLogic(periodicMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask periodicEstablishTask = new AxTask(new AxArtifactKey("PeriodicEstablishTask", "0.0.1")); - periodicEstablishTask.duplicateInputFields(periodicEvent.getParameterMap()); - periodicEstablishTask.duplicateOutputFields(periodicEvent.getParameterMap()); - periodicEstablishTask - .setTaskLogic(new AxTaskLogic(periodicEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask periodicDecideTask = new AxTask(new AxArtifactKey("PeriodicDecideTask", "0.0.1")); - periodicDecideTask.duplicateInputFields(periodicEvent.getParameterMap()); - periodicDecideTask.duplicateOutputFields(periodicEvent.getParameterMap()); - periodicDecideTask.setTaskLogic(new AxTaskLogic(periodicDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); - - final AxTask periodicActTask = new AxTask(new AxArtifactKey("PeriodicActTask", "0.0.1")); - 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)); - - final AxTasks aadmTasks = new AxTasks(new AxArtifactKey("AADMTasks", "0.0.1")); - aadmTasks.getTaskMap().put(aadmMatchTask.getKey(), aadmMatchTask); - aadmTasks.getTaskMap().put(aadmEstablishTask.getKey(), aadmEstablishTask); - aadmTasks.getTaskMap().put(aadmDecideTask.getKey(), aadmDecideTask); - aadmTasks.getTaskMap().put(aadmDoSSuggestionActTask.getKey(), aadmDoSSuggestionActTask); - aadmTasks.getTaskMap().put(aadmNoActTask.getKey(), aadmNoActTask); - aadmTasks.getTaskMap().put(aadmDoSProvenActTask.getKey(), aadmDoSProvenActTask); - aadmTasks.getTaskMap().put(vMMEMatchTask.getKey(), vMMEMatchTask); - aadmTasks.getTaskMap().put(vMMEEstablishTask.getKey(), vMMEEstablishTask); - aadmTasks.getTaskMap().put(vMMEDecideTask.getKey(), vMMEDecideTask); - aadmTasks.getTaskMap().put(vMMENoActTask.getKey(), vMMENoActTask); - aadmTasks.getTaskMap().put(vMMEActTask.getKey(), vMMEActTask); - aadmTasks.getTaskMap().put(sapcMatchTask.getKey(), sapcMatchTask); - aadmTasks.getTaskMap().put(sapcEstablishTask.getKey(), sapcEstablishTask); - aadmTasks.getTaskMap().put(sapcDecideTask.getKey(), sapcDecideTask); - aadmTasks.getTaskMap().put(sapcActTask.getKey(), sapcActTask); - aadmTasks.getTaskMap().put(periodicMatchTask.getKey(), periodicMatchTask); - aadmTasks.getTaskMap().put(periodicEstablishTask.getKey(), periodicEstablishTask); - aadmTasks.getTaskMap().put(periodicDecideTask.getKey(), periodicDecideTask); - aadmTasks.getTaskMap().put(periodicActTask.getKey(), periodicActTask); - - // Policies - logicReader.setDefaultLogic(null); - - final AxPolicy aadmPolicy = new AxPolicy(new AxArtifactKey("AADMPolicy", "0.0.1")); - 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()); - 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)); - aadmActState.setDefaultTask(aadmNoActTask.getKey()); - aadmActState.getTaskReferences().put(aadmNoActTask.getKey(), new AxStateTaskReference(aadmActState.getKey(), - aadmNoActTask.getKey(), AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); - aadmActState.getTaskReferences().put(aadmDoSSuggestionActTask.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())); - - logicReader.setDefaultLogic("Default_TaskSelectionLogic"); - - 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()); - aadmDecideState.getStateOutputs().put(aadmDec2Act.getKey().getLocalName(), aadmDec2Act); - aadmDecideState.setTaskSelectionLogic( - new AxTaskSelectionLogic(aadmDecideState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); - aadmDecideState.setDefaultTask(aadmDecideTask.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")); - aadmEstablishState.setTrigger(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.setDefaultTask(aadmEstablishTask.getKey()); - aadmEstablishState.getTaskReferences().put(aadmEstablishTask.getKey(), - new AxStateTaskReference(aadmEstablishState.getKey(), aadmEstablishTask.getKey(), - AxStateTaskOutputType.DIRECT, aadmEst2Dec.getKey())); - - 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()); - aadmMatchState.getStateOutputs().put(aadmMat2Est.getKey().getLocalName(), aadmMat2Est); - aadmMatchState.setTaskSelectionLogic( - new AxTaskSelectionLogic(aadmMatchState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); - aadmMatchState.setDefaultTask(aadmMatchTask.getKey()); - aadmMatchState.getTaskReferences().put(aadmMatchTask.getKey(), new AxStateTaskReference(aadmMatchState.getKey(), - aadmMatchTask.getKey(), AxStateTaskOutputType.DIRECT, aadmMat2Est.getKey())); - - aadmPolicy.setFirstState(aadmMatchState.getKey().getLocalName()); - aadmPolicy.getStateMap().put(aadmMatchState.getKey().getLocalName(), aadmMatchState); - aadmPolicy.getStateMap().put(aadmEstablishState.getKey().getLocalName(), aadmEstablishState); - 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")); - 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()); - 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())); - vMMEActState.getTaskReferences().put(vMMENoActTask.getKey(), new AxStateTaskReference(vMMEActState.getKey(), - vMMENoActTask.getKey(), AxStateTaskOutputType.DIRECT, vMMEAct2Out.getKey())); - - 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()); - 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())); - - 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()); - 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())); - - 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()); - 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())); - - vMMEPolicy.setFirstState(vMMEMatchState.getKey().getLocalName()); - vMMEPolicy.getStateMap().put(vMMEMatchState.getKey().getLocalName(), vMMEMatchState); - vMMEPolicy.getStateMap().put(vMMEEstablishState.getKey().getLocalName(), vMMEEstablishState); - 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")); - 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()); - 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())); - - 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()); - 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())); - - 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()); - 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())); - - 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()); - 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())); - - sapcPolicy.setFirstState(sapcMatchState.getKey().getLocalName()); - sapcPolicy.getStateMap().put(sapcMatchState.getKey().getLocalName(), sapcMatchState); - sapcPolicy.getStateMap().put(sapcEstablishState.getKey().getLocalName(), sapcEstablishState); - 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")); - 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()); - 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())); - - 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()); - 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())); - - 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()); - 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())); - - 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()); - 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())); - - periodicPolicy.setFirstState(periodicMatchState.getKey().getLocalName()); - periodicPolicy.getStateMap().put(periodicMatchState.getKey().getLocalName(), periodicMatchState); - periodicPolicy.getStateMap().put(periodicEstablishState.getKey().getLocalName(), periodicEstablishState); - 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")); - 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")); - aadmPolicyModel.setPolicies(aadmPolicies); - aadmPolicyModel.setEvents(aadmEvents); - aadmPolicyModel.setTasks(aadmTasks); - aadmPolicyModel.setAlbums(aadmAlbums); - aadmPolicyModel.setSchemas(aadmContextSchemas); - aadmPolicyModel.setKeyInformation(keyInformation); - aadmPolicyModel.getKeyInformation().generateKeyInfo(aadmPolicyModel); - - final AxValidationResult result = aadmPolicyModel.validate(new AxValidationResult()); - if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.VALID)) { - throw new ApexRuntimeException("model " + aadmPolicyModel.getId() + " is not valid" + result); - } - return aadmPolicyModel; - } -} 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 deleted file mode 100644 index a25a0e983..000000000 --- a/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AADMDomainModelSaver.java +++ /dev/null @@ -1,57 +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.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; - -/** - * This class saves sample domain models to disk in XML and JSON format. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public final class AADMDomainModelSaver { - /** - * Private default constructor to prevent subclassing. - */ - private AADMDomainModelSaver() {} - - /** - * Write the AADM model 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: " + AADMDomainModelSaver.class.getCanonicalName() + " modelDirectory"); - return; - } - - // Save Java model - final AxPolicyModel aadmPolicyModel = new AADMDomainModelFactory().getAADMPolicyModel(); - final ApexModelSaver aadmModelSaver = - new ApexModelSaver<>(AxPolicyModel.class, aadmPolicyModel, args[0]); - aadmModelSaver.apexModelWriteJson(); - aadmModelSaver.apexModelWriteXml(); - } -} 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 new file mode 100644 index 000000000..376643211 --- /dev/null +++ b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelFactory.java @@ -0,0 +1,703 @@ +/*- + * ============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.aadm.model; + +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.AxTaskSelectionLogic; +import org.onap.policy.apex.model.policymodel.concepts.AxTasks; +import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; + +/** + * The Class AADMDomainModelFactory. + */ +public class AadmDomainModelFactory { + /** + * Gets the AADM policy model. + * + * @return the AADM policy model + */ + // CHECKSTYLE:OFF: checkstyle + 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")); + aadmContextSchemas.getSchemasMap().put(imsi.getKey(), imsi); + aadmContextSchemas.getSchemasMap().put(ueIpAddress.getKey(), ueIpAddress); + aadmContextSchemas.getSchemasMap().put(nwIpAddress.getKey(), nwIpAddress); + aadmContextSchemas.getSchemasMap().put(dosFlag.getKey(), dosFlag); + aadmContextSchemas.getSchemasMap().put(roundTripTime.getKey(), roundTripTime); + aadmContextSchemas.getSchemasMap().put(applicationName.getKey(), applicationName); + aadmContextSchemas.getSchemasMap().put(protocolGroup.getKey(), protocolGroup); + aadmContextSchemas.getSchemasMap().put(eNodeBId.getKey(), eNodeBId); + aadmContextSchemas.getSchemasMap().put(httpHostClass.getKey(), httpHostClass); + aadmContextSchemas.getSchemasMap().put(tcpOnFlag.getKey(), tcpOnFlag); + aadmContextSchemas.getSchemasMap().put(probeOnFlag.getKey(), probeOnFlag); + aadmContextSchemas.getSchemasMap().put(blacklistOnFlag.getKey(), blacklistOnFlag); + aadmContextSchemas.getSchemasMap().put(averageThroughput.getKey(), averageThroughput); + aadmContextSchemas.getSchemasMap().put(serviceRequestCount.getKey(), serviceRequestCount); + aadmContextSchemas.getSchemasMap().put(attchCount.getKey(), attchCount); + aadmContextSchemas.getSchemasMap().put(subscriberCount.getKey(), subscriberCount); + aadmContextSchemas.getSchemasMap().put(averageServiceRequest.getKey(), averageServiceRequest); + aadmContextSchemas.getSchemasMap().put(averageAttach.getKey(), averageAttach); + aadmContextSchemas.getSchemasMap().put(actionTask.getKey(), actionTask); + aadmContextSchemas.getSchemasMap().put(version.getKey(), version); + aadmContextSchemas.getSchemasMap().put(profile.getKey(), profile); + aadmContextSchemas.getSchemasMap().put(threshold.getKey(), threshold); + aadmContextSchemas.getSchemasMap().put(triggerSpec.getKey(), triggerSpec); + aadmContextSchemas.getSchemasMap().put(periodicEventCount.getKey(), periodicEventCount); + 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"); + 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())); + 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())); + aadmEvent.getParameterMap().put("protocol_group", + 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())); + aadmEvent.getParameterMap().put("SGW_IP_ADDRESS", + 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())); + aadmEvent.getParameterMap().put("SERVICE_REQUEST_COUNT", new AxField( + 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())); + 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"); + aadmXStreamActEvent.setSource("Apex"); + aadmXStreamActEvent.setTarget("External"); + 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())); + 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"); + 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"); + 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"); + sapcBlacklistSubscriberEvent.setSource("Apex"); + sapcBlacklistSubscriberEvent.setTarget("External"); + 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"); + 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_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())); + + final AxEvents aadmEvents = new AxEvents(new AxArtifactKey("AADMEvents", "0.0.1")); + aadmEvents.getEventMap().put(aadmEvent.getKey(), aadmEvent); + aadmEvents.getEventMap().put(aadmXStreamActEvent.getKey(), aadmXStreamActEvent); + aadmEvents.getEventMap().put(vMmeEvent.getKey(), vMmeEvent); + aadmEvents.getEventMap().put(sapcEvent.getKey(), sapcEvent); + aadmEvents.getEventMap().put(sapcBlacklistSubscriberEvent.getKey(), sapcBlacklistSubscriberEvent); + 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"); + 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 ipAddressStatusAlbum = new AxContextAlbum( + new AxArtifactKey("IPAddressStatusAlbum", "0.0.1"), "APPLICATION", true, ipAddressStatus.getKey()); + + final AxContextAlbums aadmAlbums = new AxContextAlbums(new AxArtifactKey("AADMContext", "0.0.1")); + 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 AxTask aadmMatchTask = new AxTask(new AxArtifactKey("AADMMatchTask", "0.0.1")); + 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)); + + final AxTask aadmEstablishTask = new AxTask(new AxArtifactKey("AADMEstablishTask", "0.0.1")); + aadmEstablishTask.duplicateInputFields(aadmEvent.getParameterMap()); + aadmEstablishTask.duplicateOutputFields(aadmEvent.getParameterMap()); + logicReader.setDefaultLogic("Default_TaskLogic"); + aadmEstablishTask.setTaskLogic(new AxTaskLogic(aadmEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask aadmDecideTask = new AxTask(new AxArtifactKey("AADMDecideTask", "0.0.1")); + aadmDecideTask.duplicateInputFields(aadmEvent.getParameterMap()); + aadmDecideTask.duplicateOutputFields(aadmEvent.getParameterMap()); + aadmDecideTask.setTaskLogic(new AxTaskLogic(aadmDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + logicReader.setDefaultLogic(null); + + final AxTask aadmDoSSuggestionActTask = new AxTask(new AxArtifactKey("AADMDoSSuggestionActTask", "0.0.1")); + 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)); + + final AxTask aadmNoActTask = new AxTask(new AxArtifactKey("AADMNoActTask", "0.0.1")); + aadmNoActTask.duplicateInputFields(aadmEvent.getParameterMap()); + aadmNoActTask.duplicateOutputFields(aadmXStreamActEvent.getParameterMap()); + aadmNoActTask.setTaskLogic(new AxTaskLogic(aadmNoActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask aadmDoSProvenActTask = new AxTask(new AxArtifactKey("AADMDoSProvenActTask", "0.0.1")); + 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)); + + final AxTask vMmeMatchTask = new AxTask(new AxArtifactKey("VMMEMatchTask", "0.0.1")); + vMmeMatchTask.duplicateInputFields(vMmeEvent.getParameterMap()); + vMmeMatchTask.duplicateOutputFields(vMmeEvent.getParameterMap()); + vMmeMatchTask.setTaskLogic(new AxTaskLogic(vMmeMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask vMmeEstablishTask = new AxTask(new AxArtifactKey("VMMEEstablishTask", "0.0.1")); + vMmeEstablishTask.duplicateInputFields(vMmeEvent.getParameterMap()); + vMmeEstablishTask.duplicateOutputFields(vMmeEvent.getParameterMap()); + logicReader.setDefaultLogic("Default_TaskLogic"); + vMmeEstablishTask.setTaskLogic(new AxTaskLogic(vMmeEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask vMmeDecideTask = new AxTask(new AxArtifactKey("VMMEDecideTask", "0.0.1")); + vMmeDecideTask.duplicateInputFields(vMmeEvent.getParameterMap()); + vMmeDecideTask.duplicateOutputFields(vMmeEvent.getParameterMap()); + vMmeDecideTask.setTaskLogic(new AxTaskLogic(vMmeDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask vMmeNoActTask = new AxTask(new AxArtifactKey("VMMENoActTask", "0.0.1")); + vMmeNoActTask.duplicateInputFields(vMmeEvent.getParameterMap()); + vMmeNoActTask.duplicateOutputFields(vMmeEvent.getParameterMap()); + vMmeNoActTask.setTaskLogic(new AxTaskLogic(vMmeNoActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask vMmeActTask = new AxTask(new AxArtifactKey("VMMEActTask", "0.0.1")); + vMmeActTask.duplicateInputFields(vMmeEvent.getParameterMap()); + vMmeActTask.duplicateOutputFields(vMmeEvent.getParameterMap()); + logicReader.setDefaultLogic(null); + vMmeActTask.setTaskLogic(new AxTaskLogic(vMmeActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask sapcMatchTask = new AxTask(new AxArtifactKey("SAPCMatchTask", "0.0.1")); + sapcMatchTask.duplicateInputFields(sapcEvent.getParameterMap()); + sapcMatchTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); + sapcMatchTask.setTaskLogic(new AxTaskLogic(sapcMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask sapcEstablishTask = new AxTask(new AxArtifactKey("SAPCEstablishTask", "0.0.1")); + sapcEstablishTask.duplicateInputFields(sapcEvent.getParameterMap()); + sapcEstablishTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); + logicReader.setDefaultLogic("Default_TaskLogic"); + sapcEstablishTask.setTaskLogic(new AxTaskLogic(sapcEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask sapcDecideTask = new AxTask(new AxArtifactKey("SAPCDecideTask", "0.0.1")); + sapcDecideTask.duplicateInputFields(sapcEvent.getParameterMap()); + sapcDecideTask.duplicateOutputFields(sapcBlacklistSubscriberEvent.getParameterMap()); + sapcDecideTask.setTaskLogic(new AxTaskLogic(sapcDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask sapcActTask = new AxTask(new AxArtifactKey("SAPCActTask", "0.0.1")); + 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)); + + logicReader.setDefaultLogic("Default_TaskLogic"); + + final AxTask periodicMatchTask = new AxTask(new AxArtifactKey("PeriodicMatchTask", "0.0.1")); + periodicMatchTask.duplicateInputFields(periodicEvent.getParameterMap()); + periodicMatchTask.duplicateOutputFields(periodicEvent.getParameterMap()); + periodicMatchTask.setTaskLogic(new AxTaskLogic(periodicMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask periodicEstablishTask = new AxTask(new AxArtifactKey("PeriodicEstablishTask", "0.0.1")); + periodicEstablishTask.duplicateInputFields(periodicEvent.getParameterMap()); + periodicEstablishTask.duplicateOutputFields(periodicEvent.getParameterMap()); + periodicEstablishTask + .setTaskLogic(new AxTaskLogic(periodicEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask periodicDecideTask = new AxTask(new AxArtifactKey("PeriodicDecideTask", "0.0.1")); + periodicDecideTask.duplicateInputFields(periodicEvent.getParameterMap()); + periodicDecideTask.duplicateOutputFields(periodicEvent.getParameterMap()); + periodicDecideTask.setTaskLogic(new AxTaskLogic(periodicDecideTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask periodicActTask = new AxTask(new AxArtifactKey("PeriodicActTask", "0.0.1")); + 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)); + + final AxTasks aadmTasks = new AxTasks(new AxArtifactKey("AADMTasks", "0.0.1")); + aadmTasks.getTaskMap().put(aadmMatchTask.getKey(), aadmMatchTask); + aadmTasks.getTaskMap().put(aadmEstablishTask.getKey(), aadmEstablishTask); + aadmTasks.getTaskMap().put(aadmDecideTask.getKey(), aadmDecideTask); + aadmTasks.getTaskMap().put(aadmDoSSuggestionActTask.getKey(), aadmDoSSuggestionActTask); + aadmTasks.getTaskMap().put(aadmNoActTask.getKey(), aadmNoActTask); + aadmTasks.getTaskMap().put(aadmDoSProvenActTask.getKey(), aadmDoSProvenActTask); + aadmTasks.getTaskMap().put(vMmeMatchTask.getKey(), vMmeMatchTask); + aadmTasks.getTaskMap().put(vMmeEstablishTask.getKey(), vMmeEstablishTask); + aadmTasks.getTaskMap().put(vMmeDecideTask.getKey(), vMmeDecideTask); + aadmTasks.getTaskMap().put(vMmeNoActTask.getKey(), vMmeNoActTask); + aadmTasks.getTaskMap().put(vMmeActTask.getKey(), vMmeActTask); + aadmTasks.getTaskMap().put(sapcMatchTask.getKey(), sapcMatchTask); + aadmTasks.getTaskMap().put(sapcEstablishTask.getKey(), sapcEstablishTask); + aadmTasks.getTaskMap().put(sapcDecideTask.getKey(), sapcDecideTask); + aadmTasks.getTaskMap().put(sapcActTask.getKey(), sapcActTask); + aadmTasks.getTaskMap().put(periodicMatchTask.getKey(), periodicMatchTask); + aadmTasks.getTaskMap().put(periodicEstablishTask.getKey(), periodicEstablishTask); + aadmTasks.getTaskMap().put(periodicDecideTask.getKey(), periodicDecideTask); + aadmTasks.getTaskMap().put(periodicActTask.getKey(), periodicActTask); + + // Policies + logicReader.setDefaultLogic(null); + + final AxPolicy aadmPolicy = new AxPolicy(new AxArtifactKey("AADMPolicy", "0.0.1")); + 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()); + 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)); + aadmActState.setDefaultTask(aadmNoActTask.getKey()); + aadmActState.getTaskReferences().put(aadmNoActTask.getKey(), new AxStateTaskReference(aadmActState.getKey(), + aadmNoActTask.getKey(), AxStateTaskOutputType.DIRECT, aadmAct2Out.getKey())); + aadmActState.getTaskReferences().put(aadmDoSSuggestionActTask.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())); + + logicReader.setDefaultLogic("Default_TaskSelectionLogic"); + + 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()); + aadmDecideState.getStateOutputs().put(aadmDec2Act.getKey().getLocalName(), aadmDec2Act); + aadmDecideState.setTaskSelectionLogic( + new AxTaskSelectionLogic(aadmDecideState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + aadmDecideState.setDefaultTask(aadmDecideTask.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")); + aadmEstablishState.setTrigger(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.setDefaultTask(aadmEstablishTask.getKey()); + aadmEstablishState.getTaskReferences().put(aadmEstablishTask.getKey(), + new AxStateTaskReference(aadmEstablishState.getKey(), aadmEstablishTask.getKey(), + AxStateTaskOutputType.DIRECT, aadmEst2Dec.getKey())); + + 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()); + aadmMatchState.getStateOutputs().put(aadmMat2Est.getKey().getLocalName(), aadmMat2Est); + aadmMatchState.setTaskSelectionLogic( + new AxTaskSelectionLogic(aadmMatchState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + aadmMatchState.setDefaultTask(aadmMatchTask.getKey()); + aadmMatchState.getTaskReferences().put(aadmMatchTask.getKey(), new AxStateTaskReference(aadmMatchState.getKey(), + aadmMatchTask.getKey(), AxStateTaskOutputType.DIRECT, aadmMat2Est.getKey())); + + aadmPolicy.setFirstState(aadmMatchState.getKey().getLocalName()); + aadmPolicy.getStateMap().put(aadmMatchState.getKey().getLocalName(), aadmMatchState); + aadmPolicy.getStateMap().put(aadmEstablishState.getKey().getLocalName(), aadmEstablishState); + 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")); + 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()); + 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())); + vMmeActState.getTaskReferences().put(vMmeNoActTask.getKey(), new AxStateTaskReference(vMmeActState.getKey(), + vMmeNoActTask.getKey(), AxStateTaskOutputType.DIRECT, vMmeAct2Out.getKey())); + + 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()); + 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())); + + 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()); + 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())); + + 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()); + 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())); + + vMmePolicy.setFirstState(vMmeMatchState.getKey().getLocalName()); + vMmePolicy.getStateMap().put(vMmeMatchState.getKey().getLocalName(), vMmeMatchState); + vMmePolicy.getStateMap().put(vMmeEstablishState.getKey().getLocalName(), vMmeEstablishState); + 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")); + 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()); + 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())); + + 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()); + 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())); + + 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()); + 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())); + + 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()); + 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())); + + sapcPolicy.setFirstState(sapcMatchState.getKey().getLocalName()); + sapcPolicy.getStateMap().put(sapcMatchState.getKey().getLocalName(), sapcMatchState); + sapcPolicy.getStateMap().put(sapcEstablishState.getKey().getLocalName(), sapcEstablishState); + 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")); + 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()); + 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())); + + 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()); + 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())); + + 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()); + 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())); + + 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()); + 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())); + + periodicPolicy.setFirstState(periodicMatchState.getKey().getLocalName()); + periodicPolicy.getStateMap().put(periodicMatchState.getKey().getLocalName(), periodicMatchState); + periodicPolicy.getStateMap().put(periodicEstablishState.getKey().getLocalName(), periodicEstablishState); + 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")); + 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")); + aadmPolicyModel.setPolicies(aadmPolicies); + aadmPolicyModel.setEvents(aadmEvents); + aadmPolicyModel.setTasks(aadmTasks); + aadmPolicyModel.setAlbums(aadmAlbums); + aadmPolicyModel.setSchemas(aadmContextSchemas); + aadmPolicyModel.setKeyInformation(keyInformation); + aadmPolicyModel.getKeyInformation().generateKeyInfo(aadmPolicyModel); + + final AxValidationResult result = aadmPolicyModel.validate(new AxValidationResult()); + if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.VALID)) { + throw new ApexRuntimeException("model " + aadmPolicyModel.getId() + " is not valid" + result); + } + return aadmPolicyModel; + } +} 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 new file mode 100644 index 000000000..5a3afd901 --- /dev/null +++ b/examples/examples-aadm/src/main/java/org/onap/policy/apex/examples/aadm/model/AadmDomainModelSaver.java @@ -0,0 +1,57 @@ +/*- + * ============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.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; + +/** + * This class saves sample domain models to disk in XML and JSON format. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public final class AadmDomainModelSaver { + /** + * Private default constructor to prevent subclassing. + */ + private AadmDomainModelSaver() {} + + /** + * Write the AADM model 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: " + AadmDomainModelSaver.class.getCanonicalName() + " modelDirectory"); + return; + } + + // Save Java model + final AxPolicyModel aadmPolicyModel = new AadmDomainModelFactory().getAadmPolicyModel(); + final ApexModelSaver aadmModelSaver = + new ApexModelSaver<>(AxPolicyModel.class, aadmPolicyModel, args[0]); + aadmModelSaver.apexModelWriteJson(); + aadmModelSaver.apexModelWriteXml(); + } +} diff --git a/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutJsonEvent.json b/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutJsonEvent.json index c43f41353..427dea352 100644 --- a/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutJsonEvent.json +++ b/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } diff --git a/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutXmlEvent.json b/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutXmlEvent.json index 294da2483..3658b09a2 100644 --- a/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutXmlEvent.json +++ b/examples/examples-aadm/src/main/resources/examples/config/AADM/Stdin2StdoutXmlEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -24,7 +24,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } }, @@ -38,7 +38,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } } 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 index 078841792..225a0da4d 100644 --- 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 @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; -import org.onap.policy.apex.examples.aadm.concepts.IMSIStatus; +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; logger.debug(subject.id + ":" + subject.taskName + " execution logic"); logger.debug(inFields); @@ -44,10 +44,10 @@ else{ outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; } -IMSIStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); logger.debug(imsiStatus); -ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBID()); +ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); eNodeBStatus.setBeingProbed(false); leaveProbingOn = false; @@ -62,14 +62,14 @@ if (!leaveProbingOn) { outFields["TCP_ON"] = false; } -eNodeBStatus.decrementDOSCount(); -logger.debug(eNodeBStatus.getENodeB() + ": dosCount is " + eNodeBStatus.getDOSCount()); +eNodeBStatus.decrementDosCount(); +logger.debug(eNodeBStatus.getENodeB() + ": dosCount is " + eNodeBStatus.getDosCount()); imsiStatus.setAnomalous(false); -logger.debug("imsi: " + imsiStatus.getIMSI() + " anamalous " + imsiStatus.getAnomalous()); +logger.debug("imsi: " + imsiStatus.getImsi() + " anamalous " + imsiStatus.getAnomalous()); -getContextAlbum("IMSIStatusAlbum") .put(imsiStatus.getIMSI(), imsiStatus); +getContextAlbum("IMSIStatusAlbum") .put(imsiStatus.getImsi(), imsiStatus); getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); outFields["THRESHOLD"] = 0; 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 index d04f9425e..63ac8d0ba 100644 --- 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 @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; -import org.onap.policy.apex.examples.aadm.concepts.IMSIStatus; +import org.onap.policy.apex.examples.aadm.concepts.ImsiStatus; logger.debug(subject.id + ":" + subject.taskName + " execution logic"); logger.debug(inFields); @@ -42,16 +42,16 @@ else { outFields["NW_IP"] = inFields["SGW_IP_ADDRESS"]; } -IMSIStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); logger.debug(imsiStatus); -ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBID()); +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 (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 (imsiStatus.getENodeBId() != null) { + eNodeBStatus.decrementDosCount(); } // if user became non anomalous return action @@ -79,20 +79,20 @@ if (imsiStatus.getENodeBID() != null && !imsiStatus.getENodeBID().equals(inField 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"]); +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()); +ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId()); if (eNodeBStatus == null) { - eNodeBStatus = new ENodeBStatus(imsiStatus.getENodeBID()); + eNodeBStatus = new ENodeBStatus(imsiStatus.getENodeBId()); getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); - logger.debug("new eNodeB added " + getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBID())); + logger.debug("new eNodeB added " + getContextAlbum("ENodeBStatusAlbum").get(imsiStatus.getENodeBId())); } -eNodeBStatus.incrementDOSCount(); +eNodeBStatus.incrementDosCount(); getContextAlbum("ENodeBStatusAlbum").put(eNodeBStatus.getENodeB(), eNodeBStatus); -logger.debug(eNodeBStatus.getENodeB() + ": dosCount incremented to " + eNodeBStatus.getDOSCount()); +logger.debug(eNodeBStatus.getENodeB() + ": dosCount incremented to " + eNodeBStatus.getDosCount()); outFields["PROBE_ON"] = true; outFields["TCP_ON"] = 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 index bb38034af..24ad9bb0a 100644 --- 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 @@ -18,8 +18,8 @@ * ============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; +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); @@ -46,22 +46,22 @@ if (eNodeBID == null ) { return false; } -IPAddressStatus ipAddressStatus = getContextAlbum("IPAddressStatusAlbum").get(ipAddress); +IpAddressStatus ipAddressStatus = getContextAlbum("IPAddressStatusAlbum").get(ipAddress); if (ipAddressStatus == null) { - ipAddressStatus = new IPAddressStatus(ipAddress); - ipAddressStatus.setIMSI(imsi); - getContextAlbum("IPAddressStatusAlbum").put(ipAddressStatus.getIPAddress(), ipAddressStatus); + 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); +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)imsi); if (imsiStatus == null) { - imsiStatus = new IMSIStatus(imsi); - imsiStatus.setENodeBID(eNodeBID); - getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getIMSI(), imsiStatus); + imsiStatus = new ImsiStatus(imsi); + imsiStatus.setENodeBId(eNodeBID); + getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); logger.debug("added new IMSI " + imsi + " to IMSI status map") } 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 index 2d0d45bdf..9c71db50a 100644 --- 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 @@ -17,7 +17,7 @@ * 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.ImsiStatus; import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; logger.debug(subject.id + ":" + subject.stateName + " execution logic"); @@ -25,7 +25,7 @@ logger.debug(inFields); logger.debug("inFields[SERVICE_REQUEST_COUNT]=" + inFields["SERVICE_REQUEST_COUNT"]); -IMSIStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); if (imsiStatus.getBlockingCount() > 1) { subject.getTaskKey("AADMNoActTask").copyTo(selectedTask); @@ -33,7 +33,7 @@ if (imsiStatus.getBlockingCount() > 1) { return false; } -logger.debug("imsi: " + imsiStatus.getIMSI() + " anamalous " + imsiStatus.getAnomalous()); +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()) { @@ -49,7 +49,7 @@ ENodeBStatus eNodeBStatus = getContextAlbum("ENodeBStatusAlbum").get((String)inF 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 && + eNodeBStatus != null && eNodeBStatus.getDosCount() > 100 && inFields["NUM_SUBSCRIBERS"] != null && inFields["NUM_SUBSCRIBERS"] > 100) { logger.debug("inside NUM_SUBSCRIBERS"); subject.getTaskKey("AADMDoSProvenActTask").copyTo(selectedTask); 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 index 115ac5477..6a2c598b0 100644 --- 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 @@ -17,15 +17,15 @@ * 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.ImsiStatus; logger.debug(subject.id + ":" + subject.taskName + " execution logic"); logger.debug(inFields); -for (IMSIStatus imsiStatus : getContextAlbum("IMSIStatusAlbum").values()) { +for (ImsiStatus imsiStatus : getContextAlbum("IMSIStatusAlbum").values()) { if ((System.currentTimeMillis() - imsiStatus.getBlacklistedTime()) > 180000) { imsiStatus.setBlacklistedTime(0); - getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getIMSI(), imsiStatus); + getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); } } 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 index 7ceaa2abe..b0c6c3158 100644 --- 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 @@ -17,7 +17,7 @@ * 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.ImsiStatus; logger.debug(subject.id + ":" + subject.taskName + " execution logic"); logger.debug(inFields); @@ -38,7 +38,7 @@ if (outFields["IMSI"] == 0 && inFields["IMSI_IP"] != null && inFields["IMSI_IP"] return true; } -IMSIStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); +ImsiStatus imsiStatus = getContextAlbum("IMSIStatusAlbum").get((String)inFields["IMSI"]); logger.debug(imsiStatus); if (imsiStatus.getBlockingCount() > 1) { @@ -62,8 +62,8 @@ if (imsiStatus.getBlockingCount() > 0 && imsiStatus.getBlacklistedTime() != 0) { imsiStatus.incrementBlockingCount(); imsiStatus.setBlacklistedTime(System.currentTimeMillis()); -logger.debug("Bocking count for IMSI: " + imsiStatus.getIMSI() + " is: " + imsiStatus.getBlockingCount()); -getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getIMSI(), imsiStatus); +logger.debug("Bocking count for IMSI: " + imsiStatus.getImsi() + " is: " + imsiStatus.getBlockingCount()); +getContextAlbum("IMSIStatusAlbum").put(imsiStatus.getImsi(), imsiStatus); outFields["PROFILE"] = "ServiceA"; outFields["BLACKLIST_ON"] = true; diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModel.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModel.java deleted file mode 100644 index ba992b522..000000000 --- a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModel.java +++ /dev/null @@ -1,85 +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.aadm; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -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.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestAADMModel { - private Connection connection; - TestApexModel testApexModel; - - /** - * Sets up embedded Derby database and the AADM model for the tests. - * @throws Exception exception to be thrown while setting up the database connection - */ - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel(AxPolicyModel.class, new TestAADMModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @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("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); - DaoParameters.setPersistenceUnit("AADMModelTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } - - private static final String VALID_MODEL_STRING = "***validation of model successful***"; -} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModelCreator.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModelCreator.java deleted file mode 100644 index 421a45a15..000000000 --- a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMModelCreator.java +++ /dev/null @@ -1,57 +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.aadm; - -import org.onap.policy.apex.examples.aadm.model.AADMDomainModelFactory; -import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -/** - * This class implements Interface TestApexModelCreator to support AADM model. - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestAADMModelCreator implements TestApexModelCreator { - - @Override - public AxPolicyModel getModel() { - return new AADMDomainModelFactory().getAADMPolicyModel(); - } - - @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/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMUseCase.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMUseCase.java deleted file mode 100644 index 21f240ba8..000000000 --- a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAADMUseCase.java +++ /dev/null @@ -1,455 +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.aadm; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -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.core.engine.event.EnEvent; -import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; -import org.onap.policy.apex.examples.aadm.model.AADMDomainModelFactory; -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.plugins.executor.mvel.MVELExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class tests AADM use case. - * @author Sergey Sachkov (sergey.sachkov@ericsson.com) - * - */ -public class TestAADMUseCase { - private static final XLogger logger = XLoggerFactory.getXLogger(TestAADMUseCase.class); - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - /** - * Test AADM use case setup. - */ - @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 aadm case. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testAADMCase() throws ApexException, InterruptedException, IOException { - final AxPolicyModel apexPolicyModel = new AADMDomainModelFactory().getAADMPolicyModel(); - assertNotNull(apexPolicyModel); - final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); - - final ApexEngineImpl apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key); - final TestApexActionListener listener = new TestApexActionListener("Test"); - apexEngine.addEventListener("listener", listener); - apexEngine.updateModel(apexPolicyModel); - apexEngine.start(); - - final AxEvent axEvent = getTriggerEvent(apexPolicyModel); - assertNotNull(axEvent); - - // getting number of connections send it to policy, expecting probe action - logger.info("Sending too many connections trigger "); - EnEvent event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - apexEngine.handleEvent(event); - EnEvent result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - // no DOS_IN_eNodeB set so return probe action - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - final ContextAlbum eNodeBStatusAlbum = apexEngine.getInternalContext().get("ENodeBStatusAlbum"); - final ENodeBStatus eNodeBStatus = (ENodeBStatus) eNodeBStatusAlbum.get("123"); - eNodeBStatus.setDOSCount(101); - eNodeBStatusAlbum.put(eNodeBStatus.getENodeB(), eNodeBStatus); - - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 101); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 99.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - // DOS_IN_eNodeB set to be more than throughput so return act action - assertTrue(result.get("ACTTASK").equals("act")); - // only one imsi was sent to process, so stop probe and tcp - assertTrue(!(boolean) result.get("TCP_ON")); - assertTrue(!(boolean) result.get("PROBE_ON")); - assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDOSCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDOSCount(99); - - // getting number of connections send it to policy, expecting probe action - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 99); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDOSCount()); - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDOSCount(99); - - // tcp correlation return positive dos - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); - event.put("DoS", false); - event.put("NUM_SUBSCRIBERS", 0); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SERVICE_REQUEST_COUNT", 0); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("UE_IP_ADDRESS", ""); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("act")); - assertTrue(!(boolean) result.get("TCP_ON")); - assertTrue(!(boolean) result.get("PROBE_ON")); - assertEquals(98, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDOSCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDOSCount(101); - - // user moving enodeB - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("act")); - assertTrue(!(boolean) result.get("TCP_ON")); - assertTrue(!(boolean) result.get("PROBE_ON")); - assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDOSCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("ENODEB_ID", new Long(124)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("IMSI_IP", ""); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDOSCount()); - assertEquals(1, ((ENodeBStatus) eNodeBStatusAlbum.get("124")).getDOSCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - // End of user moving enodeB - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDOSCount(101); - - // user becomes non anomalous - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDOSCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); - event.put("DoS", false); - event.put("IMSI_IP", ""); - event.put("NUM_SUBSCRIBERS", 0); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDOSCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - // End of user becomes non anomalous - apexEngine.handleEvent(result); - result = listener.getResult(); - assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); - assertTrue(result.get("PROFILE").equals("ServiceA")); - assertTrue(result.get("BLACKLIST_ON").equals(true)); - - event = apexEngine.createEvent(new AxArtifactKey("PeriodicEvent", "0.0.1")); - event.put("PERIODIC_EVENT_COUNT", (long) 100); - event.put("PERIODIC_DELAY", (long) 1000); - event.put("PERIODIC_FIRST_TIME", System.currentTimeMillis()); - event.put("PERIODIC_CURRENT_TIME", System.currentTimeMillis()); - event.put("PERIODIC_LAST_TIME", System.currentTimeMillis()); - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertEquals(0L, result.get("IMSI")); - assertTrue(result.get("PROFILE").equals("ServiceA")); - assertTrue(result.get("BLACKLIST_ON").equals(false)); - - apexEngine.stop(); - } - - /** - * Test vpn cleardown. - */ - @After - public void testAADMCleardown() {} - - /** - * Gets the trigger event. - * - * @param apexModel the apex model - * @return the trigger event - */ - private AxEvent getTriggerEvent(final AxPolicyModel apexPolicyModel) { - for (final AxEvent axEvent : apexPolicyModel.getEvents().getEventMap().values()) { - if (axEvent.getKey().getId().equals("AADMEvent:0.0.1")) { - return axEvent; - } - } - return null; - } -} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java index b67bb6245..bbcbaab03 100644 --- a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java +++ b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java @@ -44,7 +44,7 @@ public class TestAadmDbWrite { Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - testApexModel = new TestApexModel(AxPolicyModel.class, new TestAADMModelCreator()); + testApexModel = new TestApexModel(AxPolicyModel.class, new TestAadmModelCreator()); } @After diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java new file mode 100644 index 000000000..1ac1e9829 --- /dev/null +++ b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java @@ -0,0 +1,85 @@ +/*- + * ============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.aadm; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +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.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class TestAadmModel { + private Connection connection; + TestApexModel testApexModel; + + /** + * Sets up embedded Derby database and the AADM model for the tests. + * @throws Exception exception to be thrown while setting up the database connection + */ + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel(AxPolicyModel.class, new TestAadmModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @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("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + DaoParameters.setPersistenceUnit("AADMModelTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } + + private static final String VALID_MODEL_STRING = "***validation of model successful***"; +} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModelCreator.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModelCreator.java new file mode 100644 index 000000000..7f34bff59 --- /dev/null +++ b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModelCreator.java @@ -0,0 +1,57 @@ +/*- + * ============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.aadm; + +import org.onap.policy.apex.examples.aadm.model.AadmDomainModelFactory; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +/** + * This class implements Interface TestApexModelCreator to support AADM model. + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestAadmModelCreator implements TestApexModelCreator { + + @Override + public AxPolicyModel getModel() { + return new AadmDomainModelFactory().getAadmPolicyModel(); + } + + @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/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java new file mode 100644 index 000000000..579bf3484 --- /dev/null +++ b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java @@ -0,0 +1,459 @@ +/*- + * ============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.aadm; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +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.core.engine.event.EnEvent; +import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; +import org.onap.policy.apex.examples.aadm.model.AadmDomainModelFactory; +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.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +// TODO: Auto-generated Javadoc +/** + * This class tests AADM use case. + * @author Sergey Sachkov (sergey.sachkov@ericsson.com) + * + */ +public class TestAadmUseCase { + private static final XLogger logger = XLoggerFactory.getXLogger(TestAadmUseCase.class); + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Test AADM use case setup. + */ + @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 aadm case. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testAadmCase() throws ApexException, InterruptedException, IOException { + final AxPolicyModel apexPolicyModel = new AadmDomainModelFactory().getAadmPolicyModel(); + assertNotNull(apexPolicyModel); + final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); + + final ApexEngineImpl apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key); + final TestApexActionListener listener = new TestApexActionListener("Test"); + apexEngine.addEventListener("listener", listener); + apexEngine.updateModel(apexPolicyModel); + apexEngine.start(); + + final AxEvent axEvent = getTriggerEvent(apexPolicyModel); + assertNotNull(axEvent); + + // getting number of connections send it to policy, expecting probe action + logger.info("Sending too many connections trigger "); + EnEvent event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + apexEngine.handleEvent(event); + EnEvent result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + // no DOS_IN_eNodeB set so return probe action + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + final ContextAlbum eNodeBStatusAlbum = apexEngine.getInternalContext().get("ENodeBStatusAlbum"); + final ENodeBStatus eNodeBStatus = (ENodeBStatus) eNodeBStatusAlbum.get("123"); + eNodeBStatus.setDosCount(101); + eNodeBStatusAlbum.put(eNodeBStatus.getENodeB(), eNodeBStatus); + + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 101); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 99.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + // DOS_IN_eNodeB set to be more than throughput so return act action + assertTrue(result.get("ACTTASK").equals("act")); + // only one imsi was sent to process, so stop probe and tcp + assertTrue(!(boolean) result.get("TCP_ON")); + assertTrue(!(boolean) result.get("PROBE_ON")); + assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(99); + + // getting number of connections send it to policy, expecting probe action + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 99); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(99); + + // tcp correlation return positive dos + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); + event.put("DoS", false); + event.put("NUM_SUBSCRIBERS", 0); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SERVICE_REQUEST_COUNT", 0); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("UE_IP_ADDRESS", ""); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("act")); + assertTrue(!(boolean) result.get("TCP_ON")); + assertTrue(!(boolean) result.get("PROBE_ON")); + assertEquals(98, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(101); + + // user moving enodeB + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("act")); + assertTrue(!(boolean) result.get("TCP_ON")); + assertTrue(!(boolean) result.get("PROBE_ON")); + assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("ENODEB_ID", new Long(124)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("IMSI_IP", ""); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + assertEquals(1, ((ENodeBStatus) eNodeBStatusAlbum.get("124")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + // End of user moving enodeB + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(101); + + // user becomes non anomalous + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); + event.put("DoS", false); + event.put("IMSI_IP", ""); + event.put("NUM_SUBSCRIBERS", 0); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + // End of user becomes non anomalous + apexEngine.handleEvent(result); + result = listener.getResult(); + assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); + assertTrue(result.get("PROFILE").equals("ServiceA")); + assertTrue(result.get("BLACKLIST_ON").equals(true)); + + event = apexEngine.createEvent(new AxArtifactKey("PeriodicEvent", "0.0.1")); + event.put("PERIODIC_EVENT_COUNT", (long) 100); + event.put("PERIODIC_DELAY", (long) 1000); + event.put("PERIODIC_FIRST_TIME", System.currentTimeMillis()); + event.put("PERIODIC_CURRENT_TIME", System.currentTimeMillis()); + event.put("PERIODIC_LAST_TIME", System.currentTimeMillis()); + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertEquals(0L, result.get("IMSI")); + assertTrue(result.get("PROFILE").equals("ServiceA")); + assertTrue(result.get("BLACKLIST_ON").equals(false)); + + apexEngine.stop(); + } + + /** + * Test vpn cleardown. + */ + @After + public void testAadmCleardown() {} + + /** + * Gets the trigger event. + * + * @param apexPolicyModel the apex policy model + * @return the trigger event + */ + private AxEvent getTriggerEvent(final AxPolicyModel apexPolicyModel) { + for (final AxEvent axEvent : apexPolicyModel.getEvents().getEventMap().values()) { + if (axEvent.getKey().getId().equals("AADMEvent:0.0.1")) { + return axEvent; + } + } + return null; + } +} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java index 4b66eb116..cb7e3c824 100644 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java @@ -44,7 +44,7 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; -import org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; import org.onap.policy.common.parameters.ParameterService; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -66,6 +66,9 @@ public class TestAnomalyDetectionTslUseCase { private ContextParameters contextParameters; private EngineParameters engineParameters; + /** + * Before test. + */ @Before public void beforeTest() { schemaParameters = new SchemaParameters(); @@ -88,11 +91,14 @@ public class TestAnomalyDetectionTslUseCase { ParameterService.register(contextParameters.getPersistorParameters()); engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); ParameterService.register(engineParameters); } + /** + * After test. + */ @After public void afterTest() { ParameterService.deregister(engineParameters); @@ -105,6 +111,13 @@ public class TestAnomalyDetectionTslUseCase { ParameterService.deregister(schemaParameters); } + /** + * Test anomaly detection tsl. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ @Test // once through the long running test below public void testAnomalyDetectionTsl() throws ApexException, InterruptedException, IOException { @@ -170,7 +183,7 @@ public class TestAnomalyDetectionTslUseCase { final AxArtifactKey key = new AxArtifactKey("AnomalyTSLApexEngine", "0.0.1"); final EngineParameters parameters = new EngineParameters(); - parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + parameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); @@ -205,6 +218,14 @@ public class TestAnomalyDetectionTslUseCase { Thread.sleep(1000); } + /** + * The main method. + * + * @param args the arguments + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ public static void main(final String[] args) throws ApexException, InterruptedException, IOException { new TestAnomalyDetectionTslUseCase().testAnomalyDetectionTslmain(); } diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java index 632ae623e..3052c31a7 100644 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java @@ -44,11 +44,12 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; -import org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; import org.onap.policy.common.parameters.ParameterService; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +// TODO: Auto-generated Javadoc /** * Test Auto learning in TSL. * @@ -64,6 +65,9 @@ public class TestAutoLearnTslUseCase { private ContextParameters contextParameters; private EngineParameters engineParameters; + /** + * Before test. + */ @Before public void beforeTest() { schemaParameters = new SchemaParameters(); @@ -86,11 +90,14 @@ public class TestAutoLearnTslUseCase { ParameterService.register(contextParameters.getPersistorParameters()); engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); ParameterService.register(engineParameters); } + /** + * After test. + */ @After public void afterTest() { ParameterService.deregister(engineParameters); @@ -103,6 +110,13 @@ public class TestAutoLearnTslUseCase { ParameterService.deregister(schemaParameters); } + /** + * Test auto learn tsl. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ @Test // once through the long running test below public void testAutoLearnTsl() throws ApexException, InterruptedException, IOException { @@ -167,7 +181,7 @@ public class TestAutoLearnTslUseCase { final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); final EngineParameters parameters = new EngineParameters(); - parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + parameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); @@ -228,6 +242,14 @@ public class TestAutoLearnTslUseCase { } + /** + * The main method. + * + * @param args the arguments + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ public static void main(final String[] args) throws ApexException, InterruptedException, IOException { new TestAutoLearnTslUseCase().testAutoLearnTslMain(); } diff --git a/examples/examples-decisionmaker/pom.xml b/examples/examples-decisionmaker/pom.xml index 4bbbc775e..280e6bfd1 100644 --- a/examples/examples-decisionmaker/pom.xml +++ b/examples/examples-decisionmaker/pom.xml @@ -57,7 +57,7 @@ java - org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain + org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain compile --command-file=${project.basedir}/src/main/resources/policy/${policymodel.name}.apex diff --git a/examples/examples-myfirstpolicy/pom.xml b/examples/examples-myfirstpolicy/pom.xml index cc56d0b1f..7aa4f5bdf 100644 --- a/examples/examples-myfirstpolicy/pom.xml +++ b/examples/examples-myfirstpolicy/pom.xml @@ -97,7 +97,7 @@ - org.onap.policy.apex.examples.myfirstpolicy.model.MFPDomainModelSaver + org.onap.policy.apex.examples.myfirstpolicy.model.MfpDomainModelSaver ${project.build.directory}/classes/examples/models/MyFirstPolicy diff --git a/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelFactory.java b/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelFactory.java deleted file mode 100644 index 5e5bb913d..000000000 --- a/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelFactory.java +++ /dev/null @@ -1,86 +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.myfirstpolicy.model; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * A factory for creating MFPDomainModel objects. - * - * @author John Keeney (john.keeney@ericsson.com) - */ -public class MFPDomainModelFactory { - - private static final String MFP1PATH = "examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json"; - private static final String MFP1_ALT_PATH = "examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.alt.json"; - private static final String MFP2PATH = "examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.json"; - - /** - * Gets the MyFirstPolicy#1 policy model. - * - * @return the MyFirstPolicy#1 policy model - */ - public AxPolicyModel getMFP1PolicyModel() { - java.util.TimeZone.getTimeZone("gmt"); - try { - final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); - return reader.read(ResourceUtils.getResourceAsString(MFPDomainModelFactory.MFP1PATH)); - } catch (final Exception e) { - throw new ApexRuntimeException("Failed to build MyFirstPolicy from path: " + MFPDomainModelFactory.MFP1PATH, - e); - } - } - - /** - * Gets the MyFirstPolicy#1 policy model, with alternate JavaScript task logic. - * - * @return the MyFirstPolicy#1 policy model - */ - public AxPolicyModel getMFP1AltPolicyModel() { - java.util.TimeZone.getTimeZone("gmt"); - try { - final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); - return reader.read(ResourceUtils.getResourceAsString(MFPDomainModelFactory.MFP1_ALT_PATH)); - } catch (final Exception e) { - throw new ApexRuntimeException( - "Failed to build MyFirstPolicy_ALT from path: " + MFPDomainModelFactory.MFP1_ALT_PATH, e); - } - } - - /** - * Gets the MyFirstPolicy#1 policy model. - * - * @return the MyFirstPolicy#1 policy model - */ - public AxPolicyModel getMFP2PolicyModel() { - try { - final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); - return reader.read(ResourceUtils.getResourceAsString(MFPDomainModelFactory.MFP2PATH)); - } catch (final Exception e) { - throw new ApexRuntimeException("Failed to build MyFirstPolicy from path: " + MFPDomainModelFactory.MFP2PATH, - e); - } - } - -} diff --git a/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelSaver.java b/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelSaver.java deleted file mode 100644 index fb47f6cf9..000000000 --- a/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MFPDomainModelSaver.java +++ /dev/null @@ -1,62 +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.myfirstpolicy.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; - -/** - * The Class MFPDomainModelSaver. - * - * @author John Keeney (john.keeney@ericsson.com) - */ -public final class MFPDomainModelSaver { - - /** Private constructor to prevent instantiation. */ - private MFPDomainModelSaver() {} - - /** - * Write the MyFirstPolicy model to args[0]. - * - * @param args uses arg[0] for directory information - * @throws ApexException the apex exception - */ - public static void main(final String[] args) throws ApexException { - if (args.length != 1) { - System.err.println("usage: " + MFPDomainModelSaver.class.getCanonicalName() + " modelDirectory"); - return; - } - - // Save Java model - AxPolicyModel mfpPolicyModel = new MFPDomainModelFactory().getMFP1PolicyModel(); - ApexModelSaver mfpModelSaver = - new ApexModelSaver<>(AxPolicyModel.class, mfpPolicyModel, args[0] + "/1/"); - mfpModelSaver.apexModelWriteJson(); - mfpModelSaver.apexModelWriteXml(); - - mfpPolicyModel = new MFPDomainModelFactory().getMFP2PolicyModel(); - mfpModelSaver = new ApexModelSaver<>(AxPolicyModel.class, mfpPolicyModel, args[0] + "/2/"); - mfpModelSaver.apexModelWriteJson(); - mfpModelSaver.apexModelWriteXml(); - - } -} diff --git a/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelFactory.java b/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelFactory.java new file mode 100644 index 000000000..f81a22ee9 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelFactory.java @@ -0,0 +1,86 @@ +/*- + * ============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.myfirstpolicy.model; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * A factory for creating MFPDomainModel objects. + * + * @author John Keeney (john.keeney@ericsson.com) + */ +public class MfpDomainModelFactory { + + private static final String MFP1PATH = "examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json"; + private static final String MFP1_ALT_PATH = "examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.alt.json"; + private static final String MFP2PATH = "examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.json"; + + /** + * Gets the MyFirstPolicy#1 policy model. + * + * @return the MyFirstPolicy#1 policy model + */ + public AxPolicyModel getMfp1PolicyModel() { + java.util.TimeZone.getTimeZone("gmt"); + try { + final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); + return reader.read(ResourceUtils.getResourceAsString(MfpDomainModelFactory.MFP1PATH)); + } catch (final Exception e) { + throw new ApexRuntimeException("Failed to build MyFirstPolicy from path: " + MfpDomainModelFactory.MFP1PATH, + e); + } + } + + /** + * Gets the MyFirstPolicy#1 policy model, with alternate JavaScript task logic. + * + * @return the MyFirstPolicy#1 policy model + */ + public AxPolicyModel getMfp1AltPolicyModel() { + java.util.TimeZone.getTimeZone("gmt"); + try { + final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); + return reader.read(ResourceUtils.getResourceAsString(MfpDomainModelFactory.MFP1_ALT_PATH)); + } catch (final Exception e) { + throw new ApexRuntimeException( + "Failed to build MyFirstPolicy_ALT from path: " + MfpDomainModelFactory.MFP1_ALT_PATH, e); + } + } + + /** + * Gets the MyFirstPolicy#1 policy model. + * + * @return the MyFirstPolicy#1 policy model + */ + public AxPolicyModel getMfp2PolicyModel() { + try { + final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); + return reader.read(ResourceUtils.getResourceAsString(MfpDomainModelFactory.MFP2PATH)); + } catch (final Exception e) { + throw new ApexRuntimeException("Failed to build MyFirstPolicy from path: " + MfpDomainModelFactory.MFP2PATH, + e); + } + } + +} diff --git a/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelSaver.java b/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelSaver.java new file mode 100644 index 000000000..5122390a8 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/main/java/org/onap/policy/apex/examples/myfirstpolicy/model/MfpDomainModelSaver.java @@ -0,0 +1,62 @@ +/*- + * ============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.myfirstpolicy.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; + +/** + * The Class MFPDomainModelSaver. + * + * @author John Keeney (john.keeney@ericsson.com) + */ +public final class MfpDomainModelSaver { + + /** Private constructor to prevent instantiation. */ + private MfpDomainModelSaver() {} + + /** + * Write the MyFirstPolicy model to args[0]. + * + * @param args uses arg[0] for directory information + * @throws ApexException the apex exception + */ + public static void main(final String[] args) throws ApexException { + if (args.length != 1) { + System.err.println("usage: " + MfpDomainModelSaver.class.getCanonicalName() + " modelDirectory"); + return; + } + + // Save Java model + AxPolicyModel mfpPolicyModel = new MfpDomainModelFactory().getMfp1PolicyModel(); + ApexModelSaver mfpModelSaver = + new ApexModelSaver<>(AxPolicyModel.class, mfpPolicyModel, args[0] + "/1/"); + mfpModelSaver.apexModelWriteJson(); + mfpModelSaver.apexModelWriteXml(); + + mfpPolicyModel = new MfpDomainModelFactory().getMfp2PolicyModel(); + mfpModelSaver = new ApexModelSaver<>(AxPolicyModel.class, mfpPolicyModel, args[0] + "/2/"); + mfpModelSaver.apexModelWriteJson(); + mfpModelSaver.apexModelWriteXml(); + + } +} diff --git a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigFile2StdoutJsonEvent.json b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigFile2StdoutJsonEvent.json index fc81cd6a6..d8d53f8c9 100644 --- a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigFile2StdoutJsonEvent.json +++ b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigFile2StdoutJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" }, "JAVASCRIPT": { "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters" diff --git a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json index 27bd0a6a9..338e1df99 100644 --- a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json +++ b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" }, "JAVASCRIPT": { "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters" diff --git a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigWs2WsServerJsonEvent.json b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigWs2WsServerJsonEvent.json index c4cf72171..9d438a4ec 100644 --- a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigWs2WsServerJsonEvent.json +++ b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigWs2WsServerJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" }, "JAVASCRIPT": { "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters" @@ -21,7 +21,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 4000 @@ -36,7 +36,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 3000 diff --git a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigFile2StdoutJsonEvent.json b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigFile2StdoutJsonEvent.json index be8ae938a..d4dba4446 100644 --- a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigFile2StdoutJsonEvent.json +++ b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigFile2StdoutJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" }, "JAVASCRIPT": { "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters" diff --git a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json index 56e79b2f3..0853a9850 100644 --- a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json +++ b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" }, "JAVASCRIPT": { "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters" diff --git a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigWs2WsServerJsonEvent.json b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigWs2WsServerJsonEvent.json index 65612b6db..cd621e694 100644 --- a/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigWs2WsServerJsonEvent.json +++ b/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigWs2WsServerJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" }, "JAVASCRIPT": { "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters" @@ -21,7 +21,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 4000 @@ -36,7 +36,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 3000 diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java index 651bd9280..e425088ff 100644 --- a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java @@ -30,7 +30,7 @@ import java.util.Map.Entry; import org.junit.BeforeClass; import org.junit.Test; -import org.onap.policy.apex.examples.myfirstpolicy.model.MFPDomainModelFactory; +import org.onap.policy.apex.examples.myfirstpolicy.model.MfpDomainModelFactory; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; @@ -59,7 +59,7 @@ public class TestMfpLogic { */ @Test public void testMfp1TaskLogic() { - final AxPolicyModel apexPolicyModel = new MFPDomainModelFactory().getMFP1PolicyModel(); + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1PolicyModel(); assertNotNull(apexPolicyModel); final Map logics = new LinkedHashMap<>(); @@ -85,7 +85,7 @@ public class TestMfpLogic { */ @Test public void testMfp1AltTaskLogic() { - final AxPolicyModel apexPolicyModel = new MFPDomainModelFactory().getMFP1AltPolicyModel(); + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1AltPolicyModel(); assertNotNull(apexPolicyModel); final Map logics = new LinkedHashMap<>(); @@ -110,7 +110,7 @@ public class TestMfpLogic { */ @Test public void testMfp2TaskLogic() { - final AxPolicyModel apexPolicyModel = new MFPDomainModelFactory().getMFP2PolicyModel(); + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp2PolicyModel(); assertNotNull(apexPolicyModel); final Map logics = new LinkedHashMap<>(); diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java index 0d6b4737c..a63df03bc 100644 --- a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java @@ -27,7 +27,7 @@ import java.io.IOException; import org.junit.BeforeClass; import org.junit.Test; -import org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain; +import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; @@ -71,8 +71,8 @@ public class TestMfpModelCli { { "-c", "src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.apex", "-l", tempLogFile2.getAbsolutePath(), "-o", tempModelFile2.getAbsolutePath() }; - new ApexCLIEditorMain(testApexModel1CliArgs); - new ApexCLIEditorMain(testApexModel2CliArgs); + new ApexCommandLineEditorMain(testApexModel1CliArgs); + new ApexCommandLineEditorMain(testApexModel2CliArgs); final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); AxPolicyModel generatedmodel = reader.read(TextFileUtils.getTextFileAsString(tempModelFile1.getAbsolutePath())); diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCreator.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCreator.java index ebbdac7c2..d77405d9e 100644 --- a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCreator.java +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCreator.java @@ -20,7 +20,7 @@ package org.onap.policy.apex.examples.myfirstpolicy; -import org.onap.policy.apex.examples.myfirstpolicy.model.MFPDomainModelFactory; +import org.onap.policy.apex.examples.myfirstpolicy.model.MfpDomainModelFactory; import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; @@ -83,7 +83,7 @@ public abstract class TestMfpModelCreator implements TestApexModelCreatorjava - org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain + org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain compile --command-file=${project.basedir}/src/main/resources/policy/${policymodel.name}.apex diff --git a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSim.java b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSim.java deleted file mode 100644 index f6ae332a8..000000000 --- a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSim.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.domains.onap.vcpe; - -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.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; - -public class AAIAndGuardSim { - private static final String BASE_URI = "http://localhost:54321/AAIAndGuardSim"; - private HttpServer server; - - public AAIAndGuardSim() { - final ResourceConfig rc = new ResourceConfig(AAIAndGuardSimEndpoint.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); - - while (!server.isStarted()) { - ThreadUtilities.sleep(50); - } - } - - public void tearDown() throws Exception { - server.shutdown(); - } - - public static void main(final String[] args) throws Exception { - final AAIAndGuardSim sim = new AAIAndGuardSim(); - - while (true) { - try { - Thread.sleep(100); - } catch (final InterruptedException e) { - break; - } - } - sim.tearDown(); - } -} diff --git a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSimEndpoint.java b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSimEndpoint.java deleted file mode 100644 index 6c7f7db19..000000000 --- a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AAIAndGuardSimEndpoint.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.domains.onap.vcpe; - -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; - - -@Path("/sim") -public class AAIAndGuardSimEndpoint { - - private static int postMessagesReceived = 0; - private static int putMessagesReceived = 0; - private static int statMessagesReceived = 0; - private static int getMessagesReceived = 0; - - @Path("/pdp/api/Stats") - @GET - public Response serviceGetStats() { - statMessagesReceived++; - return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } - - @Path("/pdp/api/getDecision") - @POST - public Response serviceGuardPostRequest(final String jsonString) { - postMessagesReceived++; - - if (postMessagesReceived % 2 == 0) { - return Response.status(200).entity("{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}") - .build(); - } else { - return Response.status(200).entity("{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}") - .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/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java new file mode 100644 index 000000000..369e6172c --- /dev/null +++ b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java @@ -0,0 +1,76 @@ +/*- + * ============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.domains.onap.vcpe; + +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.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; + +/** + * The Class AaiAndGuardSim. + */ +public class AaiAndGuardSim { + private static final String BASE_URI = "http://localhost:54321/AAIAndGuardSim"; + private HttpServer server; + + /** + * Instantiates a new aai and guard sim. + */ + public AaiAndGuardSim() { + final ResourceConfig rc = new ResourceConfig(AaiAndGuardSimEndpoint.class); + server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); + + while (!server.isStarted()) { + ThreadUtilities.sleep(50); + } + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + public void tearDown() throws Exception { + server.shutdown(); + } + + /** + * The main method. + * + * @param args the arguments + * @throws Exception the exception + */ + public static void main(final String[] args) throws Exception { + final AaiAndGuardSim sim = new AaiAndGuardSim(); + + while (true) { + try { + Thread.sleep(100); + } catch (final InterruptedException e) { + break; + } + } + sim.tearDown(); + } +} diff --git a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.java b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.java new file mode 100644 index 000000000..e36ef4d11 --- /dev/null +++ b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.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.domains.onap.vcpe; + +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 AaiAndGuardSimEndpoint. + */ +@Path("/sim") +public class AaiAndGuardSimEndpoint { + + 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("/pdp/api/Stats") + @GET + public Response serviceGetStats() { + statMessagesReceived++; + return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } + + /** + * Service guard post request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/pdp/api/getDecision") + @POST + public Response serviceGuardPostRequest(final String jsonString) { + postMessagesReceived++; + + if (postMessagesReceived % 2 == 0) { + return Response.status(200).entity("{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}") + .build(); + } else { + return Response.status(200).entity("{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}") + .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/examples/examples-pcvs/src/main/java/org/onap/policy/apex/examples/pcvs/model/PcvsDomainModelFactory.java b/examples/examples-pcvs/src/main/java/org/onap/policy/apex/examples/pcvs/model/PcvsDomainModelFactory.java index 001886370..fa8903b62 100644 --- a/examples/examples-pcvs/src/main/java/org/onap/policy/apex/examples/pcvs/model/PcvsDomainModelFactory.java +++ b/examples/examples-pcvs/src/main/java/org/onap/policy/apex/examples/pcvs/model/PcvsDomainModelFactory.java @@ -22,7 +22,7 @@ package org.onap.policy.apex.examples.pcvs.model; import java.io.File; -import org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain; +import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; @@ -54,7 +54,7 @@ public class PcvsDomainModelFactory { new String[] {"-c", "src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/vpnsla.apex", "-wd", workingDirectory, "-o", full}; - final ApexCLIEditorMain cliEditor = new ApexCLIEditorMain(args); + final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(args); if (cliEditor.getErrorCount() > 0) { throw new ApexRuntimeException( "Apex CLI editor execution failed with " + cliEditor.getErrorCount() + " errors"); diff --git a/examples/examples-periodic/pom.xml b/examples/examples-periodic/pom.xml index 8894e71d7..fb8d43661 100644 --- a/examples/examples-periodic/pom.xml +++ b/examples/examples-periodic/pom.xml @@ -57,7 +57,7 @@ java - org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain + org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain compile --command-file=${project.basedir}/src/main/resources/policy/${policymodel.name}.apex diff --git a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat index c1f71459e..d00eec363 100644 --- a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat +++ b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat @@ -76,7 +76,7 @@ set APEX_APP_MAP[ws-echo]=java -jar %APEX_HOME%\lib\applications\simple-wsclient set APEX_APP_MAP[tpl-event-json]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -cp %CLASSPATH% %_CONFIG% org.onap.policy.apex.tools.model.generator.model2event.Application set APEX_APP_MAP[model-2-cli]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -cp %CLASSPATH% %_CONFIG% org.onap.policy.apex.tools.model.generator.model2cli.Application set APEX_APP_MAP[rest-editor]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -jar %APEX_HOME%\lib\applications\client-editor-%_VERSION%-editor.jar -set APEX_APP_MAP[cli-editor]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -cp %CLASSPATH% %_CONFIG% org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain +set APEX_APP_MAP[cli-editor]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -cp %CLASSPATH% %_CONFIG% org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain set APEX_APP_MAP[engine]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -cp %CLASSPATH% %_CONFIG% org.onap.policy.apex.service.engine.main.ApexMain set APEX_APP_MAP[eng-deployment]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -jar %APEX_HOME%\lib\applications\client-deployment-%_VERSION%-deployment.jar set APEX_APP_MAP[eng-monitoring]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -jar %APEX_HOME%\lib\applications\client-monitoring-%_VERSION%-monitoring.jar diff --git a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh index 246906b56..0bd5995bc 100755 --- a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh +++ b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh @@ -85,7 +85,7 @@ APEX_APP_MAP["ws-echo"]="java -jar $APEX_HOME/lib/applications/simple-wsclient-$ APEX_APP_MAP["tpl-event-json"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -cp ${CLASSPATH} $_config org.onap.policy.apex.tools.model.generator.model2event.Application" APEX_APP_MAP["model-2-cli"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -cp ${CLASSPATH} $_config org.onap.policy.apex.tools.model.generator.model2cli.Application" APEX_APP_MAP["rest-editor"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -jar $APEX_HOME/lib/applications/client-editor-$_version-editor.jar" -APEX_APP_MAP["cli-editor"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -cp ${CLASSPATH} $_config org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain" +APEX_APP_MAP["cli-editor"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -cp ${CLASSPATH} $_config org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain" APEX_APP_MAP["engine"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -cp ${CLASSPATH} $_config org.onap.policy.apex.service.engine.main.ApexMain" APEX_APP_MAP["eng-deployment"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -jar $APEX_HOME/lib/applications/client-deployment-$_version-deployment.jar" APEX_APP_MAP["eng-monitoring"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -jar $APEX_HOME/lib/applications/client-monitoring-$_version-monitoring.jar" diff --git a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributor.java b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributor.java index 9d35c30a8..123d834ff 100644 --- a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributor.java +++ b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributor.java @@ -20,6 +20,9 @@ package org.onap.policy.apex.plugins.context.distribution.hazelcast; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; + import java.util.Map; import org.onap.policy.apex.context.ContextException; @@ -28,9 +31,6 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; -import com.hazelcast.core.Hazelcast; -import com.hazelcast.core.HazelcastInstance; - /** * This context distributor distributes context across threads in multiple JVMs on multiple hosts. * It uses hazelcast to distribute maps. @@ -70,12 +70,20 @@ public class HazelcastContextDistributor extends AbstractDistributor { // Create the hazelcast instance if it does not already exist if (hazelcastInstance == null) { - hazelcastInstance = Hazelcast.newHazelcastInstance(); + setHazelcastInstance(Hazelcast.newHazelcastInstance()); } LOGGER.exit("init(" + key + ")"); } + /** + * Set the hazelcast instance statically. + * @param newHazelcastInstance the hazelcast instance + */ + private static void setHazelcastInstance(HazelcastInstance newHazelcastInstance) { + hazelcastInstance = newHazelcastInstance; + } + /* * (non-Javadoc) * @@ -101,6 +109,6 @@ public class HazelcastContextDistributor extends AbstractDistributor { if (hazelcastInstance != null) { hazelcastInstance.shutdown(); } - hazelcastInstance = null; + setHazelcastInstance(null); } } diff --git a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/test/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributorTest.java b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/test/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributorTest.java index c3c137349..9d7f003ee 100644 --- a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/test/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributorTest.java +++ b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-hazelcast/src/test/java/org/onap/policy/apex/plugins/context/distribution/hazelcast/HazelcastContextDistributorTest.java @@ -38,6 +38,9 @@ import org.onap.policy.common.parameters.ParameterService; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +/** + * The Class HazelcastContextDistributorTest. + */ public class HazelcastContextDistributorTest { private static final String HAZEL_CAST_PLUGIN_CLASS = HazelcastContextDistributor.class.getCanonicalName(); // Logger for this class @@ -46,6 +49,9 @@ public class HazelcastContextDistributorTest { private SchemaParameters schemaParameters; private ContextParameters contextParameters; + /** + * Before test. + */ @Before public void beforeTest() { contextParameters = new ContextParameters(); @@ -69,6 +75,9 @@ public class HazelcastContextDistributorTest { ParameterService.register(schemaParameters); } + /** + * After test. + */ @After public void afterTest() { ParameterService.deregister(schemaParameters); @@ -78,6 +87,14 @@ public class HazelcastContextDistributorTest { ParameterService.deregister(contextParameters.getPersistorParameters()); ParameterService.deregister(contextParameters); } + + /** + * Test context album update hazelcast. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ @Test public void testContextAlbumUpdateHazelcast() throws ApexModelException, IOException, ApexException { logger.debug("Running testContextAlbumUpdateHazelcast test . . ."); @@ -87,6 +104,13 @@ public class HazelcastContextDistributorTest { logger.debug("Ran testContextAlbumUpdateHazelcast test"); } + /** + * Test context instantiation hazelcast. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ @Test public void testContextInstantiationHazelcast() throws ApexModelException, IOException, ApexException { logger.debug("Running testContextInstantiationHazelcast test . . ."); @@ -96,6 +120,13 @@ public class HazelcastContextDistributorTest { logger.debug("Ran testContextInstantiationHazelcast test"); } + /** + * Test context update hazelcast. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ @Test public void testContextUpdateHazelcast() throws ApexModelException, IOException, ApexException { logger.debug("Running testContextUpdateHazelcast test . . ."); diff --git a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributor.java b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributor.java index c8b1cedce..e11f3da8b 100644 --- a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributor.java +++ b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributor.java @@ -22,7 +22,6 @@ package org.onap.policy.apex.plugins.context.distribution.infinispan; import java.util.Map; -import org.infinispan.Cache; import org.onap.policy.apex.context.ContextException; import org.onap.policy.apex.context.impl.distribution.AbstractDistributor; import org.onap.policy.apex.context.parameters.ContextParameterConstants; @@ -32,8 +31,8 @@ import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** - * This context distributor distributes context across threads in multiple JVMs on multiple hosts. - * It uses Infinispan to distribute maps. + * This context distributor distributes context across threads in multiple JVMs on multiple hosts. It uses Infinispan to + * distribute maps. * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -58,8 +57,7 @@ public class InfinispanContextDistributor extends AbstractDistributor { /* * (non-Javadoc) * - * @see - * org.onap.policy.apex.context.impl.distribution.AbstractContextDistributor#init(org.onap.policy.apex + * @see org.onap.policy.apex.context.impl.distribution.AbstractContextDistributor#init(org.onap.policy.apex * .model.basicmodel.concepts.AxArtifactKey) */ @Override @@ -71,18 +69,26 @@ public class InfinispanContextDistributor extends AbstractDistributor { // Create the infinispan manager if it does not already exist if (infinispanManager == null) { // Get the parameters from the parameter service - final InfinispanDistributorParameters parameters = - ParameterService.get(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + final InfinispanDistributorParameters parameters = ParameterService + .get(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - LOGGER.debug("initiating Infinispan with the parameters: " + parameters); + LOGGER.debug("initiating Infinispan with the parameters: {}", parameters); // Create the manager - infinispanManager = new InfinispanManager(parameters); + setInfinispanManager(new InfinispanManager(parameters)); } LOGGER.exit("init(" + key + ")"); } + /** + * Set the infinispan manager statically. + * @param newInfinispanManager the new infinspan manager instance + */ + private static void setInfinispanManager(InfinispanManager newInfinispanManager) { + infinispanManager = newInfinispanManager; + } + /* * (non-Javadoc) * @@ -94,10 +100,7 @@ public class InfinispanContextDistributor extends AbstractDistributor { LOGGER.info("InfinispanContextDistributor: create album: " + contextAlbumKey.getId()); // Get the Cache from Infinispan - final Cache infinispanCache = - infinispanManager.getCacheManager().getCache(contextAlbumKey.getId().replace(':', '_')); - - return infinispanCache; + return infinispanManager.getCacheManager().getCache(contextAlbumKey.getId().replace(':', '_')); } /* @@ -111,6 +114,6 @@ public class InfinispanContextDistributor extends AbstractDistributor { if (infinispanManager != null) { infinispanManager.shutdown(); } - infinispanManager = null; + setInfinispanManager(null); } } diff --git a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanDistributorParameters.java b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanDistributorParameters.java index 16fdd85ac..1993d21de 100644 --- a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanDistributorParameters.java +++ b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanDistributorParameters.java @@ -46,7 +46,7 @@ public class InfinispanDistributorParameters extends DistributorParameters { private String configFile = DEFAULT_INFINISPAN_DISTRIBUTION_CONFIG_FILE; private String jgroupsFile = DEFAULT_INFINISPAN_DISTRIBUTION_JGROUPS_FILE; private boolean preferIPv4Stack = DEFAULT_INFINISPAN_JAVA_NET_PREFER_IPV4_STACK; - private String jGroupsBindAddress = DEFAULT_INFINSPAN_JGROUPS_BIND_ADDRESS; + private String jgroupsBindAddress = DEFAULT_INFINSPAN_JGROUPS_BIND_ADDRESS; // @formatter:on /** @@ -116,16 +116,16 @@ public class InfinispanDistributorParameters extends DistributorParameters { * @return the j groups bind address */ public String getjGroupsBindAddress() { - return jGroupsBindAddress; + return jgroupsBindAddress; } /** * Setj groups bind address. * - * @param jGroupsBindAddress the j groups bind address + * @param jgroupsBindAddress the j groups bind address */ - public void setjGroupsBindAddress(final String jGroupsBindAddress) { - this.jGroupsBindAddress = jGroupsBindAddress; + public void setjGroupsBindAddress(final String jgroupsBindAddress) { + this.jgroupsBindAddress = jgroupsBindAddress; } /* @@ -136,6 +136,6 @@ public class InfinispanDistributorParameters extends DistributorParameters { @Override public String toString() { return "InfinispanDistributorParameters [configFile=" + configFile + ", jgroupsFile=" + jgroupsFile - + ", preferIPv4Stack=" + preferIPv4Stack + ", jGroupsBindAddress=" + jGroupsBindAddress + "]"; + + ", preferIPv4Stack=" + preferIPv4Stack + ", jGroupsBindAddress=" + jgroupsBindAddress + "]"; } } diff --git a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanManager.java b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanManager.java index 1a2076f10..843a6b971 100644 --- a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanManager.java +++ b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/main/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanManager.java @@ -45,7 +45,7 @@ public class InfinispanManager { * @throws ContextException On errors connecting to Infinispan */ public InfinispanManager(final InfinispanDistributorParameters infinispanDistributorParameters) - throws ContextException { + throws ContextException { LOGGER.entry("Creating Infinispan Manager: " + infinispanDistributorParameters); setSystemProperties(infinispanDistributorParameters); @@ -55,8 +55,8 @@ public class InfinispanManager { cacheManager = new DefaultCacheManager(infinispanDistributorParameters.getConfigFile()); LOGGER.debug("started infinispan cache manager using specified configuration"); } catch (final IOException ioException) { - final String errorMessage = - "failed to start infinispan cache manager, no infinispan configuration found on local file system or in classpath, " + final String errorMessage = "failed to start infinispan cache manager, " + + "no infinispan configuration found on local file system or in classpath, " + "try setting Infinspan \"configFile\" parameter"; LOGGER.error(errorMessage); throw new ContextException(errorMessage, ioException); @@ -101,7 +101,7 @@ public class InfinispanManager { */ private void setSystemProperties(final InfinispanDistributorParameters infinispanDistributorParameters) { System.setProperty("java.net.preferIPv4Stack", - Boolean.toString(infinispanDistributorParameters.preferIPv4Stack())); + Boolean.toString(infinispanDistributorParameters.preferIPv4Stack())); System.setProperty("jgroups.bind_addr", infinispanDistributorParameters.getjGroupsBindAddress()); } diff --git a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/test/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributorTest.java b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/test/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributorTest.java index 862dcef83..3da1cf509 100644 --- a/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/test/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributorTest.java +++ b/plugins/plugins-context/plugins-context-distribution/plugins-context-distribution-infinispan/src/test/java/org/onap/policy/apex/plugins/context/distribution/infinispan/InfinispanContextDistributorTest.java @@ -17,6 +17,7 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ + package org.onap.policy.apex.plugins.context.distribution.infinispan; import java.io.IOException; @@ -38,6 +39,9 @@ import org.onap.policy.common.parameters.ParameterService; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +/** + * The Class InfinispanContextDistributorTest. + */ public class InfinispanContextDistributorTest { private static final XLogger logger = XLoggerFactory.getXLogger(InfinispanContextDistributorTest.class); @@ -46,6 +50,9 @@ public class InfinispanContextDistributorTest { private SchemaParameters schemaParameters; private ContextParameters contextParameters; + /** + * Before test. + */ @Before public void beforeTest() { contextParameters = new ContextParameters(); @@ -70,6 +77,9 @@ public class InfinispanContextDistributorTest { ParameterService.register(schemaParameters); } + /** + * After test. + */ @After public void afterTest() { ParameterService.deregister(schemaParameters); @@ -80,6 +90,13 @@ public class InfinispanContextDistributorTest { ParameterService.deregister(contextParameters); } + /** + * Test context album update infinispan. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ @Test public void testContextAlbumUpdateInfinispan() throws ApexModelException, IOException, ApexException { logger.debug("Running testContextAlbumUpdateInfinispan test . . ."); @@ -89,6 +106,13 @@ public class InfinispanContextDistributorTest { logger.debug("Ran testContextAlbumUpdateInfinispan test"); } + /** + * Test context instantiation infinispan. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ @Test public void testContextInstantiationInfinispan() throws ApexModelException, IOException, ApexException { logger.debug("Running testContextInstantiationInfinispan test . . ."); @@ -98,6 +122,13 @@ public class InfinispanContextDistributorTest { logger.debug("Ran testContextInstantiationInfinispan test"); } + /** + * Test context update infinispan. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ @Test public void testContextUpdateInfinispan() throws ApexModelException, IOException, ApexException { logger.debug("Running testContextUpdateInfinispan test . . ."); @@ -107,6 +138,13 @@ public class InfinispanContextDistributorTest { logger.debug("Ran testContextUpdateInfinispan test"); } + /** + * Test sequential context instantiation infinispan. + * + * @throws ApexModelException the apex model exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexException the apex exception + */ @Test public void testSequentialContextInstantiationInfinispan() throws ApexModelException, IOException, ApexException { logger.debug("Running testSequentialContextInstantiationInfinispan test . . ."); diff --git a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockFacade.java b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockFacade.java index 928255031..4e6ab71a4 100644 --- a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockFacade.java +++ b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockFacade.java @@ -37,6 +37,9 @@ public class CuratorLockFacade implements Lock { // Logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(CuratorLockFacade.class); + // Recurring string constants + private static final String FAILED_TO_ACQUIRE_LOCK_TAG = "failed to acquire lock for \"{}\""; + // The Lock ID private final String lockId; @@ -64,7 +67,7 @@ public class CuratorLockFacade implements Lock { try { lockMutex.acquire(); } catch (final Exception e) { - LOGGER.warn("failed to acquire lock for \"" + lockId, e); + LOGGER.warn(FAILED_TO_ACQUIRE_LOCK_TAG, lockId, e); } } @@ -75,7 +78,7 @@ public class CuratorLockFacade implements Lock { */ @Override public void lockInterruptibly() throws InterruptedException { - LOGGER.warn("lockInterruptibly() not supported for \"" + lockId); + LOGGER.warn("lockInterruptibly() not supported for \"{}\"", lockId); } /* @@ -131,7 +134,7 @@ public class CuratorLockFacade implements Lock { */ @Override public Condition newCondition() { - LOGGER.warn("newCondition() not supported for \"" + lockId); + LOGGER.warn("newCondition() not supported for \"{} \"", lockId); return null; } } diff --git a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockManager.java b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockManager.java index d2976d799..bc8ce9055 100644 --- a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockManager.java +++ b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorLockManager.java @@ -81,9 +81,10 @@ public class CuratorLockManager extends AbstractLockManager { // Check if the curator address has been set curatorZookeeperAddress = lockParameters.getZookeeperAddress(); if (curatorZookeeperAddress == null || curatorZookeeperAddress.trim().length() == 0) { - LOGGER.warn("could not set up Curator locking, check if the curator Zookeeper address parameter is set correctly"); - throw new ContextException( - "could not set up Curator locking, check if the curator Zookeeper address parameter is set correctly"); + String message = "could not set up Curator locking, " + + "check if the curator Zookeeper address parameter is set correctly"; + LOGGER.warn(message); + throw new ContextException(message); } // Set up the curator framework we'll use diff --git a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorReentrantReadWriteLock.java b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorReentrantReadWriteLock.java index 22bf5e596..5a24fb701 100644 --- a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorReentrantReadWriteLock.java +++ b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-curator/src/main/java/org/onap/policy/apex/plugins/context/locking/curator/CuratorReentrantReadWriteLock.java @@ -33,7 +33,7 @@ import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock; */ public class CuratorReentrantReadWriteLock implements ReadWriteLock { // The Lock ID - private final String lockID; + private final String lockId; // The Curator lock private final InterProcessReadWriteLock curatorReadWriteLock; @@ -49,7 +49,7 @@ public class CuratorReentrantReadWriteLock implements ReadWriteLock { * @param lockId The unique ID of the lock. */ public CuratorReentrantReadWriteLock(final CuratorFramework curatorFramework, final String lockId) { - lockID = lockId; + this.lockId = lockId; // Create the Curator lock curatorReadWriteLock = new InterProcessReadWriteLock(curatorFramework, lockId); @@ -64,8 +64,8 @@ public class CuratorReentrantReadWriteLock implements ReadWriteLock { * * @return the lock ID */ - public String getLockID() { - return lockID; + public String getLockId() { + return lockId; } /* diff --git a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLock.java b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLock.java index 73678ad2a..9d4a5ca8f 100644 --- a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLock.java +++ b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLock.java @@ -20,12 +20,12 @@ package org.onap.policy.apex.plugins.context.locking.hazelcast; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; - import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ILock; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; + /** * This class maps a Hazelcast {@link ILock} to a Java {@link ReadWriteLock}. * @@ -33,7 +33,7 @@ import com.hazelcast.core.ILock; */ public class HazelcastLock implements ReadWriteLock { // The Lock ID - private final String lockID; + private final String lockId; // The hazelcast lock private final ILock readLock; @@ -46,7 +46,7 @@ public class HazelcastLock implements ReadWriteLock { * @param lockId The unique ID of the lock. */ public HazelcastLock(final HazelcastInstance hazelcastInstance, final String lockId) { - lockID = lockId; + this.lockId = lockId; // Create the Hazelcast read and write locks readLock = hazelcastInstance.getLock(lockId + "_READ"); @@ -58,8 +58,8 @@ public class HazelcastLock implements ReadWriteLock { * * @return the lock ID */ - public String getLockID() { - return lockID; + public String getLockId() { + return lockId; } /* diff --git a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLockManager.java b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLockManager.java index 34258bf24..4994cf7f5 100644 --- a/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLockManager.java +++ b/plugins/plugins-context/plugins-context-locking/plugins-context-locking-hazelcast/src/main/java/org/onap/policy/apex/plugins/context/locking/hazelcast/HazelcastLockManager.java @@ -20,6 +20,9 @@ package org.onap.policy.apex.plugins.context.locking.hazelcast; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; + import java.util.concurrent.locks.ReadWriteLock; import org.onap.policy.apex.context.ContextException; @@ -28,9 +31,6 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; -import com.hazelcast.core.Hazelcast; -import com.hazelcast.core.HazelcastInstance; - /** * The Class HazelcastLockManager manages Hazelcast locks for locks on items in Apex context albums. * diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroBytesObjectMapper.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroBytesObjectMapper.java index 20e701bc7..bee2f5957 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroBytesObjectMapper.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroBytesObjectMapper.java @@ -43,7 +43,7 @@ public class AvroBytesObjectMapper implements AvroObjectMapper { private Type avroType; // The Apex compatible class - private final Class schemaClass = Byte[].class; + private static final Class schemaClass = Byte[].class; /* * (non-Javadoc) @@ -142,8 +142,6 @@ public class AvroBytesObjectMapper implements AvroObjectMapper { } // Create a ByteBuffer object to serialize the bytes - final ByteBuffer byteBuffer = ByteBuffer.wrap((byte[]) object); - - return byteBuffer; + return ByteBuffer.wrap((byte[]) object); } } diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroDirectObjectMapper.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroDirectObjectMapper.java index 35e811dec..ca771d957 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroDirectObjectMapper.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroDirectObjectMapper.java @@ -132,7 +132,7 @@ public class AvroDirectObjectMapper implements AvroObjectMapper { // the decoded object is always returned as a null if (!schemaClass.isAssignableFrom(avroObject.getClass())) { final String returnString = - userKey.getId() + ": object \"" + avroObject + "\" of class \"" + avroObject.getClass() + userKey.getId() + ": object \"" + avroObject + "\" of class \"" + avroObject.getClass() + "\" cannot be decoded to an object of class \"" + schemaClass.getCanonicalName() + "\""; LOGGER.warn(returnString); throw new ContextRuntimeException(returnString); @@ -150,13 +150,11 @@ public class AvroDirectObjectMapper implements AvroObjectMapper { @Override public Object mapToAvro(final Object object) { // Null values are only allowed if the schema class is null - if (object == null) { - if (schemaClass != null) { - final String returnString = userKey.getId() + ": cannot encode a null object of class \"" - + schemaClass.getCanonicalName() + "\""; - LOGGER.warn(returnString); - throw new ContextRuntimeException(returnString); - } + if (object == null && schemaClass != null) { + final String returnString = userKey.getId() + ": cannot encode a null object of class \"" + + schemaClass.getCanonicalName() + "\""; + LOGGER.warn(returnString); + throw new ContextRuntimeException(returnString); } // For direct mappings, just work directly with the Java objects diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroObjectMapperFactory.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroObjectMapperFactory.java index a48ca8089..21e4d76a8 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroObjectMapperFactory.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroObjectMapperFactory.java @@ -75,12 +75,12 @@ public class AvroObjectMapperFactory { if (Schema.Type.UNION.equals(schema.getType())) { final List types = schema.getTypes(); - // TODO: properly support UNIONS + // currently only support unions with 2 types, one of which is NULL final Schema nullschema = Schema.create(Schema.Type.NULL); if (types.size() != 2 || !types.contains(nullschema)) { final String resultSting = userKey.getId() - + ": Apex currently only supports UNION schemas with 2 options, one must be NULL"; + + ": Apex currently only supports UNION schemas with 2 options, one must be NULL"; LOGGER.warn(resultSting); throw new ContextRuntimeException(resultSting); } @@ -92,7 +92,8 @@ public class AvroObjectMapperFactory { } if (Schema.Type.NULL.equals(schema.getType())) { final String resultSting = userKey.getId() - + ": Apex currently only supports UNION schema2 with 2 options, only one can be NULL, and the other cannot be another UNION"; + + ": Apex currently only supports UNION schema2 with 2 options, " + + "only one can be NULL, and the other cannot be another UNION"; LOGGER.warn(resultSting); throw new ContextRuntimeException(resultSting); } @@ -102,8 +103,8 @@ public class AvroObjectMapperFactory { // Check that there is a definition for the mapper for this type if (!AVRO_OBJECT_MAPPER_MAP.containsKey(avroType) || AVRO_OBJECT_MAPPER_MAP.get(avroType) == null) { - final String resultSting = - userKey.getId() + ": no Avro object mapper defined for Avro type \"" + avroType + "\""; + final String resultSting = userKey.getId() + ": no Avro object mapper defined for Avro type \"" + avroType + + "\""; LOGGER.warn(resultSting); throw new ContextRuntimeException(resultSting); } @@ -118,7 +119,7 @@ public class AvroObjectMapperFactory { } catch (final Exception e) { final String resultSting = userKey.getId() + ": could not create an Avro object mapper of type \"" - + AVRO_OBJECT_MAPPER_MAP.get(avroType) + "\" for Avro type \"" + avroType + "\" : " + e; + + AVRO_OBJECT_MAPPER_MAP.get(avroType) + "\" for Avro type \"" + avroType + "\" : " + e; LOGGER.warn(resultSting, e); throw new ContextRuntimeException(resultSting, e); } diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java index df430b683..9cdb5845b 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java @@ -20,6 +20,10 @@ package org.onap.policy.apex.plugins.context.schema.avro; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; + import java.io.ByteArrayOutputStream; import org.apache.avro.Schema; @@ -38,13 +42,8 @@ import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; - /** - * This class is the implementation of the {@link org.onap.policy.apex.context.SchemaHelper} - * interface for Avro schemas. + * This class is the implementation of the {@link org.onap.policy.apex.context.SchemaHelper} interface for Avro schemas. * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -52,6 +51,9 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(AvroSchemaHelper.class); + // Recurring string constants + private static final String OBJECT_TAG = ": object \""; + // The Avro schema for this context schema private Schema avroSchema; @@ -59,7 +61,7 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { private AvroObjectMapper avroObjectMapper; @Override - public void init(final AxKey userKey, final AxContextSchema schema) throws ContextRuntimeException { + public void init(final AxKey userKey, final AxContextSchema schema) { super.init(userKey, schema); // Configure the Avro schema @@ -67,7 +69,7 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { avroSchema = new Schema.Parser().parse(schema.getSchema()); } catch (final Exception e) { final String resultSting = userKey.getId() + ": avro context schema \"" + schema.getId() - + "\" schema is invalid: " + e.getMessage() + ", schema: " + schema.getSchema(); + + "\" schema is invalid: " + e.getMessage() + ", schema: " + schema.getSchema(); LOGGER.warn(resultSting); throw new ContextRuntimeException(resultSting); } @@ -91,7 +93,7 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { @Override public Object getSchemaObject() { - return avroSchema; + return getAvroSchema(); } @Override @@ -119,10 +121,9 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { final String elementJsonString = gson.toJson((JsonElement) incomingObject); return createNewInstance(elementJsonString); - } - else { + } else { final String returnString = getUserKey().getId() + ": the object \"" + incomingObject - + "\" is not an instance of JsonObject"; + + "\" is not an instance of JsonObject"; LOGGER.warn(returnString); throw new ContextRuntimeException(returnString); } @@ -146,8 +147,8 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { final JsonDecoder jsonDecoder = DecoderFactory.get().jsonDecoder(avroSchema, objectString); decodedObject = new GenericDatumReader(avroSchema).read(null, jsonDecoder); } catch (final Exception e) { - final String returnString = getUserKey().getId() + ": object \"" + objectString - + "\" Avro unmarshalling failed: " + e.getMessage(); + final String returnString = getUserKey().getId() + OBJECT_TAG + objectString + + "\" Avro unmarshalling failed: " + e.getMessage(); LOGGER.warn(returnString, e); throw new ContextRuntimeException(returnString, e); } @@ -157,8 +158,7 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { } /** - * Check that the incoming object is a string, the incoming object must be a string containing - * Json + * Check that the incoming object is a string, the incoming object must be a string containing Json. * * @param object incoming object * @return object as String @@ -185,10 +185,10 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { return (String) object; } } catch (final ClassCastException e) { - final String returnString = getUserKey().getId() + ": object \"" + object + "\" of type \"" - + (object != null ? object.getClass().getCanonicalName() : "null") + "\" must be assignable to \"" - + getSchemaClass().getCanonicalName() - + "\" or be a Json string representation of it for Avro unmarshalling"; + final String returnString = getUserKey().getId() + OBJECT_TAG + object + "\" of type \"" + + (object != null ? object.getClass().getCanonicalName() : "null") + + "\" must be assignable to \"" + getSchemaClass().getCanonicalName() + + "\" or be a Json string representation of it for Avro unmarshalling"; LOGGER.warn(returnString); throw new ContextRuntimeException(returnString); } @@ -217,8 +217,8 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { jsonEncoder.flush(); return new String(output.toByteArray()); } catch (final Exception e) { - final String returnString = - getUserKey().getId() + ": object \"" + object + "\" Avro marshalling failed: " + e.getMessage(); + final String returnString = getUserKey().getId() + OBJECT_TAG + object + "\" Avro marshalling failed: " + + e.getMessage(); LOGGER.warn(returnString); throw new ContextRuntimeException(returnString, e); } @@ -239,8 +239,7 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { } /** - * Check if we can pass this object straight through encoding or decoding, is it an object - * native to the schema. + * Check if we can pass this object straight through encoding or decoding, is it an object native to the schema. * * @param object the object to check * @return true if it's a straight pass through diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaKeyTranslationUtilities.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaKeyTranslationUtilities.java index dc3770a43..b4c8737dd 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaKeyTranslationUtilities.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaKeyTranslationUtilities.java @@ -20,13 +20,13 @@ package org.onap.policy.apex.plugins.context.schema.avro; -import java.util.Map.Entry; - import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import java.util.Map.Entry; + /** * This static final class contains utility methods for Avro schemas. * diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroStringObjectMapper.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroStringObjectMapper.java index 09d1d9f1f..a9acb1c12 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroStringObjectMapper.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroStringObjectMapper.java @@ -42,7 +42,7 @@ public class AvroStringObjectMapper implements AvroObjectMapper { private Type avroType; // The Apex compatible class - private final Class schemaClass = String.class; + private static final Class schemaClass = String.class; /* * (non-Javadoc) diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAAI.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAAI.java deleted file mode 100644 index 5198e82e0..000000000 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAAI.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.context.schema.avro; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.avro.generic.GenericData.Array; -import org.apache.avro.generic.GenericRecord; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.SchemaHelper; -import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.concepts.AxKey; -import org.onap.policy.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; -import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.common.parameters.ParameterService; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - * @version - */ -public class TestAvroSchemaAAI { - private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); - private AxContextSchemas schemas; - private String aaiInventoryResponseSchema; - - @Before - public void initTest() throws IOException { - schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); - ModelService.registerModel(AxContextSchemas.class, schemas); - - aaiInventoryResponseSchema = - TextFileUtils.getTextFileAsString("src/test/resources/avsc/AAIInventoryResponseItemType.avsc"); - } - - @Before - public void initContext() { - SchemaParameters schemaParameters = new SchemaParameters(); - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters()); - ParameterService.register(schemaParameters); - - } - - @After - public void clearContext() { - ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); - } - - @Test - public void testAAIResponsePolicy() throws IOException { - final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", aaiInventoryResponseSchema); - - schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); - final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); - - final Array newArrayEmpty = (Array) schemaHelper.createNewInstance(); - assertEquals(0, newArrayEmpty.size()); - - final String inString = TextFileUtils.getTextFileAsString("src/test/resources/data/AAIResponse4Policy.json"); - final Array newArrayFull = (Array) schemaHelper.createNewInstance(inString); - final String vnfName = ((GenericRecord) ((GenericRecord) newArrayFull.get(0)).get("generic_DasH_vnf")) - .get("vnf_DasH_name").toString(); - assertEquals("ZRDM2MMEX39", vnfName); - } -} diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAai.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAai.java new file mode 100644 index 000000000..bca896d2e --- /dev/null +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaAai.java @@ -0,0 +1,111 @@ +/*- + * ============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.schema.avro; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.avro.generic.GenericData.Array; +import org.apache.avro.generic.GenericRecord; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.SchemaHelper; +import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.common.parameters.ParameterService; + +/** + * The Class TestAvroSchemaAai. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @version + */ +public class TestAvroSchemaAai { + private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); + private AxContextSchemas schemas; + private String aaiInventoryResponseSchema; + + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Before + public void initTest() throws IOException { + schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); + ModelService.registerModel(AxContextSchemas.class, schemas); + + aaiInventoryResponseSchema = + TextFileUtils.getTextFileAsString("src/test/resources/avsc/AAIInventoryResponseItemType.avsc"); + } + + /** + * Inits the context. + */ + @Before + public void initContext() { + SchemaParameters schemaParameters = new SchemaParameters(); + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters()); + ParameterService.register(schemaParameters); + + } + + /** + * Clear context. + */ + @After + public void clearContext() { + ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); + } + + /** + * Test AAI response policy. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testAaiResponsePolicy() throws IOException { + final AxContextSchema avroSchema = + new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", aaiInventoryResponseSchema); + + schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); + final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); + + final Array newArrayEmpty = (Array) schemaHelper.createNewInstance(); + assertEquals(0, newArrayEmpty.size()); + + final String inString = TextFileUtils.getTextFileAsString("src/test/resources/data/AAIResponse4Policy.json"); + final Array newArrayFull = (Array) schemaHelper.createNewInstance(inString); + final String vnfName = ((GenericRecord) ((GenericRecord) newArrayFull.get(0)).get("generic_DasH_vnf")) + .get("vnf_DasH_name").toString(); + assertEquals("ZRDM2MMEX39", vnfName); + } +} diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaArray.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaArray.java index b72b2ca10..972e0bd32 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaArray.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaArray.java @@ -40,9 +40,12 @@ import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.common.parameters.ParameterService; +// TODO: Auto-generated Javadoc /** + * The Class TestAvroSchemaArray. + * * @author Liam Fallon (liam.fallon@ericsson.com) - * @version + * @version */ public class TestAvroSchemaArray { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); @@ -50,6 +53,11 @@ public class TestAvroSchemaArray { private String longArraySchema; private String addressArraySchema; + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void initTest() throws IOException { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); @@ -58,6 +66,9 @@ public class TestAvroSchemaArray { addressArraySchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/ArrayExampleAddress.avsc"); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); @@ -67,11 +78,19 @@ public class TestAvroSchemaArray { } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test array init. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testArrayInit() throws IOException { final AxContextSchema avroSchema = @@ -90,6 +109,11 @@ public class TestAvroSchemaArray { newArrayFull.get(0).toString()); } + /** + * Test long array unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testLongArrayUnmarshalMarshal() throws IOException { final AxContextSchema avroSchema = @@ -102,6 +126,11 @@ public class TestAvroSchemaArray { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/ArrayExampleLongFull.json"); } + /** + * Test address array unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testAddressArrayUnmarshalMarshal() throws IOException { final AxContextSchema avroSchema = @@ -114,6 +143,13 @@ public class TestAvroSchemaArray { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/ArrayExampleAddressFull.json"); } + /** + * Test unmarshal marshal. + * + * @param schemaHelper the schema helper + * @param fileName the file name + * @throws IOException Signals that an I/O exception has occurred. + */ private void testUnmarshalMarshal(final SchemaHelper schemaHelper, final String fileName) throws IOException { final String inString = TextFileUtils.getTextFileAsString(fileName); final Array schemaObject = (Array) schemaHelper.unmarshal(inString); diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaEnum.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaEnum.java index 47a5c969c..883f14bcb 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaEnum.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaEnum.java @@ -41,15 +41,23 @@ import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.common.parameters.ParameterService; +// TODO: Auto-generated Javadoc /** + * The Class TestAvroSchemaEnum. + * * @author Liam Fallon (liam.fallon@ericsson.com) - * @version + * @version */ public class TestAvroSchemaEnum { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); private AxContextSchemas schemas; private String enumSchema; + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void initTest() throws IOException { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); @@ -57,6 +65,9 @@ public class TestAvroSchemaEnum { enumSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/EnumSchema.avsc"); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); @@ -66,11 +77,19 @@ public class TestAvroSchemaEnum { } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test enum init. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testEnumInit() throws IOException { final AxContextSchema avroSchema = @@ -86,6 +105,11 @@ public class TestAvroSchemaEnum { assertEquals("HEARTS", newEnumFull.toString()); } + /** + * Test enum unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testEnumUnmarshalMarshal() throws IOException { final AxContextSchema avroSchema = @@ -127,6 +151,13 @@ public class TestAvroSchemaEnum { } } + /** + * Test unmarshal marshal. + * + * @param schemaHelper the schema helper + * @param fileName the file name + * @throws IOException Signals that an I/O exception has occurred. + */ private void testUnmarshalMarshal(final SchemaHelper schemaHelper, final String fileName) throws IOException { final String inString = TextFileUtils.getTextFileAsString(fileName); final EnumSymbol decodedObject = (EnumSymbol) schemaHelper.unmarshal(inString); diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaFixed.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaFixed.java index 6d709645f..26f4ba8af 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaFixed.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaFixed.java @@ -43,6 +43,8 @@ import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.common.parameters.ParameterService; /** + * The Class TestAvroSchemaFixed. + * * @author Liam Fallon (liam.fallon@ericsson.com) * @version */ @@ -51,6 +53,11 @@ public class TestAvroSchemaFixed { private AxContextSchemas schemas; private String fixedSchema; + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void initTest() throws IOException { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); @@ -58,24 +65,35 @@ public class TestAvroSchemaFixed { fixedSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/FixedSchema.avsc"); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters()); ParameterService.register(schemaParameters); - + } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test fixed init. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testFixedInit() throws IOException { - final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", fixedSchema); + final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", + fixedSchema); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); @@ -84,9 +102,9 @@ public class TestAvroSchemaFixed { schemaHelper.createNewInstance(); fail("Test should throw an exception here"); } catch (final Exception e) { - assertEquals( - "AvroTest:0.0.1: could not create an instance of class \"org.apache.avro.generic.GenericData.Fixed\" using the default constructor \"Fixed()\"", - e.getMessage()); + assertEquals("AvroTest:0.0.1: could not create an instance " + + "of class \"org.apache.avro.generic.GenericData.Fixed\" " + + "using the default constructor \"Fixed()\"", e.getMessage()); } final String inString = TextFileUtils.getTextFileAsString("src/test/resources/data/FixedExampleGood.json"); @@ -95,10 +113,15 @@ public class TestAvroSchemaFixed { assertTrue(newFixedFull.toString().endsWith("53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70]")); } + /** + * Test fixed unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testFixedUnmarshalMarshal() throws IOException { - final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroArray", "0.0.1"), "AVRO", fixedSchema); + final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroArray", "0.0.1"), "AVRO", + fixedSchema); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); @@ -110,33 +133,39 @@ public class TestAvroSchemaFixed { fail("This test should throw an exception here"); } catch (final Exception e) { assertEquals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: Expected fixed. Got VALUE_NULL", - e.getMessage()); + e.getMessage()); } try { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/FixedExampleNull.json"); fail("This test should throw an exception here"); } catch (final Exception e) { assertEquals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: Expected fixed. Got VALUE_NULL", - e.getMessage()); + e.getMessage()); } try { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/FixedExampleBad0.json"); fail("This test should throw an exception here"); } catch (final Exception e) { - assertEquals( - "AvroTest:0.0.1: object \"\"BADBAD\"\" Avro unmarshalling failed: Expected fixed length 64, but got6", - e.getMessage()); + assertEquals("AvroTest:0.0.1: object \"\"BADBAD\"\" " + + "Avro unmarshalling failed: Expected fixed length 64, but got6", e.getMessage()); } try { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/FixedExampleBad1.json"); fail("This test should throw an exception here"); } catch (final Exception e) { - assertEquals( - "AvroTest:0.0.1: object \"\"0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0\"\" Avro unmarshalling failed: Expected fixed length 64, but got65", - e.getMessage()); + assertEquals("AvroTest:0.0.1: object " + + "\"\"0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0\"\" " + + "Avro unmarshalling failed: Expected fixed length 64, but got65", e.getMessage()); } } + /** + * Test unmarshal marshal. + * + * @param schemaHelper the schema helper + * @param fileName the file name + * @throws IOException Signals that an I/O exception has occurred. + */ private void testUnmarshalMarshal(final SchemaHelper schemaHelper, final String fileName) throws IOException { final String inString = TextFileUtils.getTextFileAsString(fileName); final Fixed decodedObject = (Fixed) schemaHelper.unmarshal(inString); diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperBadSchemas.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperBadSchemas.java index 9cb027acf..cc79f9eb6 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperBadSchemas.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperBadSchemas.java @@ -37,19 +37,27 @@ import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; import org.onap.policy.common.parameters.ParameterService; /** + * The Class TestAvroSchemaHelperBadSchemas. + * * @author Liam Fallon (liam.fallon@ericsson.com) - * @version + * @version */ public class TestAvroSchemaHelperBadSchemas { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); private AxContextSchemas schemas; + /** + * Inits the test. + */ @Before public void initTest() { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); ModelService.registerModel(AxContextSchemas.class, schemas); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); @@ -59,11 +67,17 @@ public class TestAvroSchemaHelperBadSchemas { } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Bad schema test. + */ @Test public void badSchemaTest() { final AxContextSchema avroBadSchema0 = new AxContextSchema(new AxArtifactKey("AvroBad0", "0.0.1"), "AVRO", "}"); diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperMarshal.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperMarshal.java index 1f078879d..86d8426de 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperMarshal.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperMarshal.java @@ -39,6 +39,8 @@ import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; import org.onap.policy.common.parameters.ParameterService; /** + * The Class TestAvroSchemaHelperMarshal. + * * @author Liam Fallon (liam.fallon@ericsson.com) * @version */ @@ -46,48 +48,63 @@ public class TestAvroSchemaHelperMarshal { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); private AxContextSchemas schemas; + /** + * Inits the test. + */ @Before public void initTest() { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); ModelService.registerModel(AxContextSchemas.class, schemas); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters()); ParameterService.register(schemaParameters); - + } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test null marshal. + */ @Test public void testNullMarshal() { - final AxContextSchema avroNullSchema = - new AxContextSchema(new AxArtifactKey("AvroNull", "0.0.1"), "AVRO", "{\"type\": \"null\"}"); + final AxContextSchema avroNullSchema = new AxContextSchema(new AxArtifactKey("AvroNull", "0.0.1"), "AVRO", + "{\"type\": \"null\"}"); schemas.getSchemasMap().put(avroNullSchema.getKey(), avroNullSchema); - final SchemaHelper schemaHelper0 = - new SchemaHelperFactory().createSchemaHelper(testKey, avroNullSchema.getKey()); + final SchemaHelper schemaHelper0 = new SchemaHelperFactory().createSchemaHelper(testKey, + avroNullSchema.getKey()); assertEquals("null", schemaHelper0.marshal2String(null)); assertEquals("null", schemaHelper0.marshal2String(123)); assertEquals("null", schemaHelper0.marshal2String("Everything is marshalled to Null, no matter what it is")); } + /** + * Test boolean marshal. + */ @Test public void testBooleanMarshal() { - final AxContextSchema avroBooleanSchema = - new AxContextSchema(new AxArtifactKey("AvroBoolean", "0.0.1"), "AVRO", "{\"type\": \"boolean\"}"); + final AxContextSchema avroBooleanSchema = new AxContextSchema(new AxArtifactKey("AvroBoolean", "0.0.1"), "AVRO", + "{\"type\": \"boolean\"}"); schemas.getSchemasMap().put(avroBooleanSchema.getKey(), avroBooleanSchema); - final SchemaHelper schemaHelper1 = - new SchemaHelperFactory().createSchemaHelper(testKey, avroBooleanSchema.getKey()); + final SchemaHelper schemaHelper1 = new SchemaHelperFactory().createSchemaHelper(testKey, + avroBooleanSchema.getKey()); assertEquals("true", schemaHelper1.marshal2String(true)); assertEquals("false", schemaHelper1.marshal2String(false)); @@ -96,29 +113,30 @@ public class TestAvroSchemaHelperMarshal { fail("Test should throw an exception here"); } catch (final Exception e) { e.printStackTrace(); - assertEquals( - "AvroTest:0.0.1: object \"0\" Avro marshalling failed: java.lang.Integer cannot be cast to java.lang.Boolean", - e.getMessage()); + assertEquals("AvroTest:0.0.1: object \"0\" Avro marshalling failed: " + + "java.lang.Integer cannot be cast to java.lang.Boolean", e.getMessage()); } try { schemaHelper1.marshal2String("0"); fail("Test should throw an exception here"); } catch (final Exception e) { e.printStackTrace(); - assertEquals( - "AvroTest:0.0.1: object \"0\" Avro marshalling failed: java.lang.String cannot be cast to java.lang.Boolean", - e.getMessage()); + assertEquals("AvroTest:0.0.1: object \"0\" Avro marshalling failed: " + + "java.lang.String cannot be cast to java.lang.Boolean", e.getMessage()); } } + /** + * Test int marshal. + */ @Test public void testIntMarshal() { - final AxContextSchema avroIntSchema = - new AxContextSchema(new AxArtifactKey("AvroInt", "0.0.1"), "AVRO", "{\"type\": \"int\"}"); + final AxContextSchema avroIntSchema = new AxContextSchema(new AxArtifactKey("AvroInt", "0.0.1"), "AVRO", + "{\"type\": \"int\"}"); schemas.getSchemasMap().put(avroIntSchema.getKey(), avroIntSchema); - final SchemaHelper schemaHelper2 = - new SchemaHelperFactory().createSchemaHelper(testKey, avroIntSchema.getKey()); + final SchemaHelper schemaHelper2 = new SchemaHelperFactory().createSchemaHelper(testKey, + avroIntSchema.getKey()); assertEquals("0", schemaHelper2.marshal2String(0)); assertEquals("1", schemaHelper2.marshal2String(1)); @@ -131,26 +149,29 @@ public class TestAvroSchemaHelperMarshal { schemaHelper2.marshal2String("Hello"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: java.lang.String cannot be cast to java.lang.Number")); + assertTrue(e.getMessage().startsWith("AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: " + + "java.lang.String cannot be cast to java.lang.Number")); } try { schemaHelper2.marshal2String(null); fail("Test should throw an exception here"); } catch (final Exception e) { assertTrue(e.getMessage() - .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Integer\"")); + .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Integer\"")); } } + /** + * Test long marshal. + */ @Test public void testLongMarshal() { - final AxContextSchema avroLongSchema = - new AxContextSchema(new AxArtifactKey("AvroLong", "0.0.1"), "AVRO", "{\"type\": \"long\"}"); + final AxContextSchema avroLongSchema = new AxContextSchema(new AxArtifactKey("AvroLong", "0.0.1"), "AVRO", + "{\"type\": \"long\"}"); schemas.getSchemasMap().put(avroLongSchema.getKey(), avroLongSchema); - final SchemaHelper schemaHelper3 = - new SchemaHelperFactory().createSchemaHelper(testKey, avroLongSchema.getKey()); + final SchemaHelper schemaHelper3 = new SchemaHelperFactory().createSchemaHelper(testKey, + avroLongSchema.getKey()); assertEquals("0", schemaHelper3.marshal2String(0L)); assertEquals("1", schemaHelper3.marshal2String(1L)); @@ -161,26 +182,29 @@ public class TestAvroSchemaHelperMarshal { schemaHelper3.marshal2String("Hello"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: java.lang.String cannot be cast to java.lang.Long")); + assertTrue(e.getMessage().startsWith("AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: " + + "java.lang.String cannot be cast to java.lang.Long")); } try { schemaHelper3.marshal2String(null); fail("Test should throw an exception here"); } catch (final Exception e) { assertTrue(e.getMessage() - .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Long\"")); + .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Long\"")); } } + /** + * Test float marshal. + */ @Test public void testFloatMarshal() { - final AxContextSchema avroFloatSchema = - new AxContextSchema(new AxArtifactKey("AvroFloat", "0.0.1"), "AVRO", "{\"type\": \"float\"}"); + final AxContextSchema avroFloatSchema = new AxContextSchema(new AxArtifactKey("AvroFloat", "0.0.1"), "AVRO", + "{\"type\": \"float\"}"); schemas.getSchemasMap().put(avroFloatSchema.getKey(), avroFloatSchema); - final SchemaHelper schemaHelper4 = - new SchemaHelperFactory().createSchemaHelper(testKey, avroFloatSchema.getKey()); + final SchemaHelper schemaHelper4 = new SchemaHelperFactory().createSchemaHelper(testKey, + avroFloatSchema.getKey()); assertEquals("0.0", schemaHelper4.marshal2String(0F)); assertEquals("1.0", schemaHelper4.marshal2String(1F)); @@ -195,27 +219,29 @@ public class TestAvroSchemaHelperMarshal { schemaHelper4.marshal2String("Hello"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: java.lang.String cannot be cast to java.lang.Float")); + assertTrue(e.getMessage().startsWith("AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: " + + "java.lang.String cannot be cast to java.lang.Float")); } try { schemaHelper4.marshal2String(null); fail("Test should throw an exception here"); } catch (final Exception e) { assertTrue(e.getMessage() - .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Float\"")); + .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Float\"")); } } - + /** + * Test double marshal. + */ @Test public void testDoubleMarshal() { - final AxContextSchema avroDoubleSchema = - new AxContextSchema(new AxArtifactKey("AvroDouble", "0.0.1"), "AVRO", "{\"type\": \"double\"}"); + final AxContextSchema avroDoubleSchema = new AxContextSchema(new AxArtifactKey("AvroDouble", "0.0.1"), "AVRO", + "{\"type\": \"double\"}"); schemas.getSchemasMap().put(avroDoubleSchema.getKey(), avroDoubleSchema); - final SchemaHelper schemaHelper5 = - new SchemaHelperFactory().createSchemaHelper(testKey, avroDoubleSchema.getKey()); + final SchemaHelper schemaHelper5 = new SchemaHelperFactory().createSchemaHelper(testKey, + avroDoubleSchema.getKey()); assertEquals("0.0", schemaHelper5.marshal2String(0D)); assertEquals("1.0", schemaHelper5.marshal2String(1D)); @@ -230,26 +256,29 @@ public class TestAvroSchemaHelperMarshal { schemaHelper5.marshal2String("Hello"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: java.lang.String cannot be cast to java.lang.Double")); + assertTrue(e.getMessage().startsWith("AvroTest:0.0.1: object \"Hello\" Avro marshalling failed: " + + "java.lang.String cannot be cast to java.lang.Double")); } try { schemaHelper5.marshal2String(null); fail("Test should throw an exception here"); } catch (final Exception e) { assertTrue(e.getMessage() - .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Double\"")); + .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Double\"")); } } + /** + * Test string marshal. + */ @Test public void testStringMarshal() { - final AxContextSchema avroStringSchema = - new AxContextSchema(new AxArtifactKey("AvroString", "0.0.1"), "AVRO", "{\"type\": \"string\"}"); + final AxContextSchema avroStringSchema = new AxContextSchema(new AxArtifactKey("AvroString", "0.0.1"), "AVRO", + "{\"type\": \"string\"}"); schemas.getSchemasMap().put(avroStringSchema.getKey(), avroStringSchema); - final SchemaHelper schemaHelper7 = - new SchemaHelperFactory().createSchemaHelper(testKey, avroStringSchema.getKey()); + final SchemaHelper schemaHelper7 = new SchemaHelperFactory().createSchemaHelper(testKey, + avroStringSchema.getKey()); assertEquals("\"0\"", schemaHelper7.marshal2String("0")); assertEquals("\"1\"", schemaHelper7.marshal2String("1")); @@ -266,19 +295,23 @@ public class TestAvroSchemaHelperMarshal { fail("Test should throw an exception here"); } catch (final Exception e) { assertTrue(e.getMessage() - .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.String\"")); + .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.String\"")); } } + /** + * Test bytes marshal. + */ @Test public void testBytesMarshal() { - final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroString", "0.0.1"), "AVRO", "{\"type\": \"bytes\"}"); + final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroString", "0.0.1"), "AVRO", + "{\"type\": \"bytes\"}"); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); - final byte[] helloBytes = {104, 101, 108, 108, 111}; + final byte[] helloBytes = + { 104, 101, 108, 108, 111 }; final String helloOut = schemaHelper.marshal2String(helloBytes); assertEquals("\"hello\"", helloOut); @@ -287,7 +320,7 @@ public class TestAvroSchemaHelperMarshal { fail("Test should throw an exception here"); } catch (final Exception e) { assertTrue(e.getMessage() - .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Byte[]\"")); + .startsWith("AvroTest:0.0.1: cannot encode a null object of class \"java.lang.Byte[]\"")); } } } diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperUnmarshal.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperUnmarshal.java index db7edd673..6dede515e 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperUnmarshal.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaHelperUnmarshal.java @@ -40,6 +40,8 @@ import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; import org.onap.policy.common.parameters.ParameterService; /** + * The Class TestAvroSchemaHelperUnmarshal. + * * @author Liam Fallon (liam.fallon@ericsson.com) * @version */ @@ -47,12 +49,18 @@ public class TestAvroSchemaHelperUnmarshal { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); private AxContextSchemas schemas; + /** + * Inits the test. + */ @Before public void initTest() { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); ModelService.registerModel(AxContextSchemas.class, schemas); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); @@ -62,11 +70,17 @@ public class TestAvroSchemaHelperUnmarshal { } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test null unmarshal. + */ @Test public void testNullUnmarshal() { final AxContextSchema avroNullSchema = new AxContextSchema(new AxArtifactKey("AvroNull", "0.0.1"), "AVRO", @@ -90,11 +104,14 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper0.unmarshal("123"); fail("test should throw an exception here"); } catch (final Exception e) { - assertEquals("AvroTest:0.0.1: object \"123\" Avro unmarshalling failed: Expected null. Got VALUE_NUMBER_INT", - e.getMessage()); + assertEquals("AvroTest:0.0.1: object \"123\" Avro unmarshalling failed: " + + "Expected null. Got VALUE_NUMBER_INT", e.getMessage()); } } + /** + * Test boolean unmarshal. + */ @Test public void testBooleanUnmarshal() { final AxContextSchema avroBooleanSchema = new AxContextSchema(new AxArtifactKey("AvroBoolean", "0.0.1"), "AVRO", @@ -108,8 +125,8 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper1.createNewInstance(); fail("test should throw an exception here"); } catch (final Exception e) { - assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Boolean\" using the default constructor \"Boolean()\"", - e.getMessage()); + assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Boolean\" " + + "using the default constructor \"Boolean()\"", e.getMessage()); } assertEquals(true, schemaHelper1.createNewInstance("true")); @@ -125,6 +142,9 @@ public class TestAvroSchemaHelperUnmarshal { } } + /** + * Test int unmarshal. + */ @Test public void testIntUnmarshal() { final AxContextSchema avroIntSchema = new AxContextSchema(new AxArtifactKey("AvroInt", "0.0.1"), "AVRO", @@ -138,8 +158,8 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper2.createNewInstance(); fail("test should throw an exception here"); } catch (final Exception e) { - assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Integer\" using the default constructor \"Integer()\"", - e.getMessage()); + assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Integer\" " + + "using the default constructor \"Integer()\"", e.getMessage()); } assertEquals(123, schemaHelper2.createNewInstance("123")); @@ -154,25 +174,28 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper2.unmarshal("2147483648"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"2147483648\" Avro unmarshalling failed: Numeric value (2147483648) out of range of int")); + assertTrue(e.getMessage().startsWith("AvroTest:0.0.1: object \"2147483648\" Avro unmarshalling failed: " + + "Numeric value (2147483648) out of range of int")); } try { schemaHelper2.unmarshal("-2147483649"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"-2147483649\" Avro unmarshalling failed: Numeric value (-2147483649) out of range of int")); + assertTrue(e.getMessage().startsWith("AvroTest:0.0.1: object \"-2147483649\" Avro unmarshalling failed: " + + "Numeric value (-2147483649) out of range of int")); } try { schemaHelper2.unmarshal(null); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: String to read from cannot be null!")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: " + + "String to read from cannot be null!")); } } + /** + * Test long unmarshal. + */ @Test public void testLongUnmarshal() { final AxContextSchema avroLongSchema = new AxContextSchema(new AxArtifactKey("AvroLong", "0.0.1"), "AVRO", @@ -186,8 +209,8 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper3.createNewInstance(); fail("test should throw an exception here"); } catch (final Exception e) { - assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Long\" using the default constructor \"Long()\"", - e.getMessage()); + assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Long\" " + + "using the default constructor \"Long()\"", e.getMessage()); } assertEquals(123456789L, schemaHelper3.createNewInstance("123456789")); @@ -202,32 +225,37 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper3.unmarshal("9223372036854775808"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"9223372036854775808\" Avro unmarshalling failed: Numeric value (9223372036854775808) out of range of long")); + assertTrue(e.getMessage() + .startsWith("AvroTest:0.0.1: object \"9223372036854775808\" Avro unmarshalling failed: " + + "Numeric value (9223372036854775808) out of range of long")); } try { schemaHelper3.unmarshal("-9223372036854775809"); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().startsWith( - "AvroTest:0.0.1: object \"-9223372036854775809\" Avro unmarshalling failed: Numeric value (-9223372036854775809) out of range of long")); + assertTrue(e.getMessage() + .startsWith("AvroTest:0.0.1: object \"-9223372036854775809\" Avro unmarshalling failed: " + + "Numeric value (-9223372036854775809) out of range of long")); } try { schemaHelper3.unmarshal("\"Hello\""); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"\"Hello\"\" Avro unmarshalling failed: Expected long. Got VALUE_STRING")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"\"Hello\"\" Avro unmarshalling failed: " + + "Expected long. Got VALUE_STRING")); } try { schemaHelper3.unmarshal(null); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: String to read from cannot be null!")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: " + + "String to read from cannot be null!")); } } + /** + * Test float unmarshal. + */ @Test public void testFloatUnmarshal() { final AxContextSchema avroFloatSchema = new AxContextSchema(new AxArtifactKey("AvroFloat", "0.0.1"), "AVRO", @@ -241,8 +269,8 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper4.createNewInstance(); fail("test should throw an exception here"); } catch (final Exception e) { - assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Float\" using the default constructor \"Float()\"", - e.getMessage()); + assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Float\" " + + "using the default constructor \"Float()\"", e.getMessage()); } assertEquals(1.2345F, schemaHelper4.createNewInstance("1.2345")); @@ -259,18 +287,21 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper4.unmarshal("\"Hello\""); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"\"Hello\"\" Avro unmarshalling failed: Expected float. Got VALUE_STRING")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"\"Hello\"\" Avro unmarshalling failed: " + + "Expected float. Got VALUE_STRING")); } try { schemaHelper4.unmarshal(null); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: String to read from cannot be null!")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: " + + "String to read from cannot be null!")); } } + /** + * Test double unmarshal. + */ @Test public void testDoubleUnmarshal() { final AxContextSchema avroDoubleSchema = new AxContextSchema(new AxArtifactKey("AvroDouble", "0.0.1"), "AVRO", @@ -284,8 +315,8 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper5.createNewInstance(); fail("test should throw an exception here"); } catch (final Exception e) { - assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Double\" using the default constructor \"Double()\"", - e.getMessage()); + assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Double\" " + + "using the default constructor \"Double()\"", e.getMessage()); } assertEquals(1.2345E06, schemaHelper5.createNewInstance("1.2345E06")); @@ -302,18 +333,21 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper5.unmarshal("\"Hello\""); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"\"Hello\"\" Avro unmarshalling failed: Expected double. Got VALUE_STRING")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"\"Hello\"\" Avro unmarshalling failed: " + + "Expected double. Got VALUE_STRING")); } try { schemaHelper5.unmarshal(null); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: String to read from cannot be null!")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: " + + "String to read from cannot be null!")); } } + /** + * Test string unmarshal. + */ @Test public void testStringUnmarshal() { final AxContextSchema avroStringSchema = new AxContextSchema(new AxArtifactKey("AvroString", "0.0.1"), "AVRO", @@ -341,11 +375,14 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper7.unmarshal(null); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: String to read from cannot be null!")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: " + + "String to read from cannot be null!")); } } + /** + * Test bytes unmarshal. + */ @Test public void testBytesUnmarshal() { final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroString", "0.0.1"), "AVRO", @@ -358,8 +395,8 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper.createNewInstance(); fail("test should throw an exception here"); } catch (final Exception e) { - assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Byte[]\" using the default constructor \"Byte[]()\"", - e.getMessage()); + assertEquals("AvroTest:0.0.1: could not create an instance of class \"java.lang.Byte[]\" " + + "using the default constructor \"Byte[]()\"", e.getMessage()); } final byte[] newBytes = (byte[]) schemaHelper.createNewInstance("\"hello\""); assertEquals(5, newBytes.length); @@ -373,8 +410,8 @@ public class TestAvroSchemaHelperUnmarshal { schemaHelper.unmarshal(null); fail("Test should throw an exception here"); } catch (final Exception e) { - assertTrue(e.getMessage().equals( - "AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: String to read from cannot be null!")); + assertTrue(e.getMessage().equals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: " + + "String to read from cannot be null!")); } } } diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaMap.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaMap.java index 7bf6b0029..9bc87cf61 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaMap.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaMap.java @@ -43,8 +43,10 @@ import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.common.parameters.ParameterService; /** + * The Class TestAvroSchemaMap. + * * @author Liam Fallon (liam.fallon@ericsson.com) - * @version + * @version */ public class TestAvroSchemaMap { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); @@ -53,6 +55,11 @@ public class TestAvroSchemaMap { private String addressMapSchema; private String addressMapSchemaInvalidFields; + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void initTest() throws IOException { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); @@ -63,6 +70,9 @@ public class TestAvroSchemaMap { TextFileUtils.getTextFileAsString("src/test/resources/avsc/MapExampleAddressInvalidFields.avsc"); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); @@ -72,11 +82,19 @@ public class TestAvroSchemaMap { } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test map init. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testMapInit() throws IOException { final AxContextSchema avroSchema = @@ -95,6 +113,11 @@ public class TestAvroSchemaMap { newMapFull.get(new Utf8("address2")).toString()); } + /** + * Test long map unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testLongMapUnmarshalMarshal() throws IOException { final AxContextSchema avroSchema = @@ -107,6 +130,11 @@ public class TestAvroSchemaMap { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/MapExampleLongFull.json"); } + /** + * Test address map unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testAddressMapUnmarshalMarshal() throws IOException { final AxContextSchema avroSchema = @@ -119,6 +147,11 @@ public class TestAvroSchemaMap { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/MapExampleAddressFull.json"); } + /** + * Test address map unmarshal marshal invalid fields. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testAddressMapUnmarshalMarshalInvalidFields() throws IOException { final AxContextSchema avroSchema = @@ -130,6 +163,13 @@ public class TestAvroSchemaMap { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/MapExampleAddressInvalidFields.json"); } + /** + * Test unmarshal marshal. + * + * @param schemaHelper the schema helper + * @param fileName the file name + * @throws IOException Signals that an I/O exception has occurred. + */ private void testUnmarshalMarshal(final SchemaHelper schemaHelper, final String fileName) throws IOException { final String originalInString = TextFileUtils.getTextFileAsString(fileName); final HashMap firstDecodedMap = (HashMap) schemaHelper.unmarshal(originalInString); diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaRecord.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaRecord.java index 000dcc9fd..6b1d09eb6 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaRecord.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaRecord.java @@ -40,29 +40,40 @@ import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.common.parameters.ParameterService; +// TODO: Auto-generated Javadoc /** + * The Class TestAvroSchemaRecord. + * * @author Liam Fallon (liam.fallon@ericsson.com) - * @version + * @version */ public class TestAvroSchemaRecord { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); private AxContextSchemas schemas; private String recordSchema; - private String recordSchemaVPN; - private String recordSchemaVPNReuse; + private String recordSchemaVpn; + private String recordSchemaVpnReuse; private String recordSchemaInvalidFields; + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void initTest() throws IOException { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); ModelService.registerModel(AxContextSchemas.class, schemas); recordSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExample.avsc"); - recordSchemaVPN = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleVPN.avsc"); - recordSchemaVPNReuse = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleVPNReuse.avsc"); + recordSchemaVpn = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleVPN.avsc"); + recordSchemaVpnReuse = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleVPNReuse.avsc"); recordSchemaInvalidFields = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleInvalidFields.avsc"); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); @@ -72,11 +83,19 @@ public class TestAvroSchemaRecord { } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test record init. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testRecordInit() throws IOException { final AxContextSchema avroSchema = @@ -93,6 +112,11 @@ public class TestAvroSchemaRecord { assertEquals("gobbledygook", newRecordFull.get("passwordHash").toString()); } + /** + * Test record unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testRecordUnmarshalMarshal() throws IOException { final AxContextSchema avroSchema = @@ -105,6 +129,11 @@ public class TestAvroSchemaRecord { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/RecordExampleFull.json"); } + /** + * Test record unmarshal marshal invalid. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testRecordUnmarshalMarshalInvalid() throws IOException { final AxContextSchema avroSchema = @@ -116,10 +145,15 @@ public class TestAvroSchemaRecord { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/RecordExampleInvalidFields.json"); } + /** + * Test VPN record unmarshal marshal. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test - public void testVPNRecordUnmarshalMarshal() throws IOException { + public void testVpnRecordUnmarshalMarshal() throws IOException { final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchemaVPN); + new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchemaVpn); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); @@ -127,16 +161,28 @@ public class TestAvroSchemaRecord { testUnmarshalMarshal(schemaHelper, "src/test/resources/data/RecordExampleVPNFull.json"); } + /** + * Test VPN record reuse. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test - public void testVPNRecordReuse() throws IOException { + public void testVpnRecordReuse() throws IOException { final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchemaVPNReuse); + new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchemaVpnReuse); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); } + /** + * Test unmarshal marshal. + * + * @param schemaHelper the schema helper + * @param fileName the file name + * @throws IOException Signals that an I/O exception has occurred. + */ private void testUnmarshalMarshal(final SchemaHelper schemaHelper, final String fileName) throws IOException { final String inString = TextFileUtils.getTextFileAsString(fileName); final GenericRecord decodedObject = (GenericRecord) schemaHelper.unmarshal(inString); diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaUnion.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaUnion.java index 33cb20328..c957d8d4c 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaUnion.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestAvroSchemaUnion.java @@ -42,14 +42,21 @@ import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.common.parameters.ParameterService; /** + * The Class TestAvroSchemaUnion. + * * @author Liam Fallon (liam.fallon@ericsson.com) - * @version + * @version */ public class TestAvroSchemaUnion { private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1"); private AxContextSchemas schemas; private String uinionSchema; + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void initTest() throws IOException { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); @@ -57,25 +64,36 @@ public class TestAvroSchemaUnion { uinionSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/UnionExample.avsc"); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters()); ParameterService.register(schemaParameters); - + } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test union all fields. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Ignore @Test public void testUnionAllFields() throws IOException { final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema); + new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); @@ -88,17 +106,22 @@ public class TestAvroSchemaUnion { assertEquals("red", user.get("favourite_colour").toString()); } + /** + * Test union optional field. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Ignore @Test public void testUnionOptionalField() throws IOException { final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema); + new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); final String inString = - TextFileUtils.getTextFileAsString("src/test/resources/data/UnionExampleOptionalField.json"); + TextFileUtils.getTextFileAsString("src/test/resources/data/UnionExampleOptionalField.json"); final GenericRecord user = (GenericRecord) schemaHelper.createNewInstance(inString); assertEquals("Ben", user.get("name").toString()); @@ -106,11 +129,16 @@ public class TestAvroSchemaUnion { assertEquals("red", user.get("favourite_colour").toString()); } + /** + * Test union null field. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Ignore @Test public void testUnionNullField() throws IOException { final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema); + new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestHealthCheckSchema.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestHealthCheckSchema.java index 42764a1ca..646b8aa04 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestHealthCheckSchema.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/test/java/org/onap/policy/apex/plugins/context/schema/avro/TestHealthCheckSchema.java @@ -44,6 +44,8 @@ import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.common.parameters.ParameterService; /** + * The Class TestHealthCheckSchema. + * * @author Liam Fallon (liam.fallon@ericsson.com) */ public class TestHealthCheckSchema { @@ -51,6 +53,11 @@ public class TestHealthCheckSchema { private AxContextSchemas schemas; private String healthCheckSchema; + /** + * Inits the test. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Before public void initTest() throws IOException { schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1")); @@ -59,24 +66,35 @@ public class TestHealthCheckSchema { healthCheckSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/HealthCheckBodyType.avsc"); } + /** + * Inits the context. + */ @Before public void initContext() { SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters()); ParameterService.register(schemaParameters); - + } + /** + * Clear context. + */ @After public void clearContext() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); } + /** + * Test health check. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testHealthCheck() throws IOException { - final AxContextSchema avroSchema = - new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", healthCheckSchema); + final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", + healthCheckSchema); schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema); final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey()); @@ -89,15 +107,15 @@ public class TestHealthCheckSchema { final GenericRecord inputRecord = new GenericData.Record(healthCheckRecordSchema.getField("input").schema()); final Schema inputRecordRecordSchema = inputRecord.getSchema(); - final GenericRecord actionIndentifiersRecord = - new GenericData.Record(inputRecordRecordSchema.getField("action_DasH_identifiers").schema()); + final GenericRecord actionIndentifiersRecord = new GenericData.Record( + inputRecordRecordSchema.getField("action_DasH_identifiers").schema()); - final GenericRecord commonHeaderRecord = - new GenericData.Record(inputRecordRecordSchema.getField("common_DasH_header").schema()); + final GenericRecord commonHeaderRecord = new GenericData.Record( + inputRecordRecordSchema.getField("common_DasH_header").schema()); final Schema commonHeaderRecordSchema = commonHeaderRecord.getSchema(); - final GenericRecord commonHeaderFlagsRecord = - new GenericData.Record(commonHeaderRecordSchema.getField("flags").schema()); + final GenericRecord commonHeaderFlagsRecord = new GenericData.Record( + commonHeaderRecordSchema.getField("flags").schema()); healthCheckRecord.put("input", inputRecord); inputRecord.put("action_DasH_identifiers", actionIndentifiersRecord); @@ -105,8 +123,8 @@ public class TestHealthCheckSchema { commonHeaderRecord.put("flags", commonHeaderFlagsRecord); inputRecord.put("action", "HealthCheck"); - inputRecord.put("payload", - "{\"host-ip-address\":\"131.160.203.125\",\"input.url\":\"131.160.203.125/afr\",\"request-action-type\":\"GET\",\"request-action\":\"AFR\"}"); + inputRecord.put("payload", "{\"host-ip-address\":\"131.160.203.125\",\"input.url\":\"131.160.203.125/afr\"," + + "\"request-action-type\":\"GET\",\"request-action\":\"AFR\"}"); actionIndentifiersRecord.put("vnf_DasH_id", "49414df5-3482-4fd8-9952-c463dff2770b"); @@ -125,6 +143,13 @@ public class TestHealthCheckSchema { assertEquals(eventString.toString().replaceAll("\\s+", ""), outString.replaceAll("\\s+", "")); } + /** + * Test unmarshal marshal. + * + * @param schemaHelper the schema helper + * @param fileName the file name + * @throws IOException Signals that an I/O exception has occurred. + */ private void testUnmarshalMarshal(final SchemaHelper schemaHelper, final String fileName) throws IOException { final String inString = TextFileUtils.getTextFileAsString(fileName); final GenericRecord decodedObject = (GenericRecord) schemaHelper.unmarshal(inString); diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSConsumer.java deleted file mode 100644 index 93174b941..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSConsumer.java +++ /dev/null @@ -1,280 +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.event.carrier.jms; - -import java.util.EnumMap; -import java.util.Map; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.jms.Topic; -import javax.naming.InitialContext; - -import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.service.engine.event.ApexEventConsumer; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventReceiver; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.onap.policy.apex.service.engine.event.PeeredReference; -import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; -import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class implements an Apex event consumer that receives events using JMS. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexJMSConsumer implements MessageListener, ApexEventConsumer, Runnable { - // Get a reference to the logger - private static final Logger LOGGER = LoggerFactory.getLogger(ApexJMSConsumer.class); - - // The Apex and JMS parameters read from the parameter service - private JMSCarrierTechnologyParameters jmsConsumerProperties; - - // The event receiver that will receive events from this consumer - private ApexEventReceiver eventReceiver; - - // The consumer thread and stopping flag - private Thread consumerThread; - private boolean stopOrderedFlag = false; - - // The connection to the JMS server - private Connection connection; - - // The topic on which we receive events from JMS - private Topic jmsIncomingTopic; - - // The name for this consumer - private String name = null; - - // The peer references for this event handler - private Map peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class); - - @Override - public void init(final String consumerName, final EventHandlerParameters consumerParameters, - final ApexEventReceiver incomingEventReceiver) throws ApexEventException { - this.eventReceiver = incomingEventReceiver; - - this.name = consumerName; - - // Check and get the JMS Properties - if (!(consumerParameters.getCarrierTechnologyParameters() instanceof JMSCarrierTechnologyParameters)) { - final String errorMessage = "specified consumer properties of type \"" - + consumerParameters.getCarrierTechnologyParameters().getClass().getCanonicalName() - + "\" are not applicable to a JMS consumer"; - LOGGER.warn(errorMessage); - throw new ApexEventException(errorMessage); - } - jmsConsumerProperties = (JMSCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); - - // Look up the JMS connection factory - InitialContext jmsContext = null; - ConnectionFactory connectionFactory = null; - try { - jmsContext = new InitialContext(jmsConsumerProperties.getJmsConsumerProperties()); - connectionFactory = (ConnectionFactory) jmsContext.lookup(jmsConsumerProperties.getConnectionFactory()); - - // Check if we actually got a connection factory - if (connectionFactory == null) { - throw new NullPointerException( - "JMS context lookup of \"" + jmsConsumerProperties.getConnectionFactory() + "\" returned null"); - } - } catch (final Exception e) { - final String errorMessage = "lookup of JMS connection factory \"" - + jmsConsumerProperties.getConnectionFactory() + "\" failed for JMS consumer properties \"" - + jmsConsumerProperties.getJmsConsumerProperties() + "\""; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - - // Lookup the topic on which we will receive events - try { - jmsIncomingTopic = (Topic) jmsContext.lookup(jmsConsumerProperties.getConsumerTopic()); - - // Check if we actually got a topic - if (jmsIncomingTopic == null) { - throw new NullPointerException( - "JMS context lookup of \"" + jmsConsumerProperties.getConsumerTopic() + "\" returned null"); - } - } catch (final Exception e) { - final String errorMessage = "lookup of JMS topic \"" + jmsConsumerProperties.getConsumerTopic() - + "\" failed for JMS consumer properties \"" + jmsConsumerProperties.getJmsConsumerProperties() - + "\""; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - - // Create and start a connection to the JMS server - try { - connection = connectionFactory.createConnection(jmsConsumerProperties.getSecurityPrincipal(), - jmsConsumerProperties.getSecurityCredentials()); - connection.start(); - } catch (final Exception e) { - final String errorMessage = "connection to the JMS server failed for JMS properties \"" - + jmsConsumerProperties.getJmsConsumerProperties() + "\""; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start() - */ - @Override - public void start() { - // Configure and start the event reception thread - final String threadName = this.getClass().getName() + ":" + this.name; - consumerThread = new ApplicationThreadFactory(threadName).newThread(this); - consumerThread.setDaemon(true); - consumerThread.start(); - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName() - */ - @Override - public String getName() { - return name; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.policy.apex.service. - * parameters. eventhandler.EventHandlerPeeredMode) - */ - @Override - public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) { - return peerReferenceMap.get(peeredMode); - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.policy.apex.service. - * parameters. eventhandler.EventHandlerPeeredMode, org.onap.policy.apex.service.engine.event.PeeredReference) - */ - @Override - public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) { - peerReferenceMap.put(peeredMode, peeredReference); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - // JMS session and message consumer for receiving messages - try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { - // Create a message consumer for reception of messages and set this class as a message listener - createMessageConsumer(jmsSession); - } catch (final Exception e) { - final String errorMessage = "failed to create a JMS session towards the JMS server for receiving messages"; - LOGGER.warn(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - // Everything is now set up - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("event receiver " + this.getClass().getName() + ":" + this.name + " subscribed to JMS topic: " - + jmsConsumerProperties.getConsumerTopic()); - } - } - - /** - * The helper function to create a message consumer from a given JMS session - * - * @param jmsSession a JMS session - */ - private void createMessageConsumer(final Session jmsSession) { - try (final MessageConsumer messageConsumer = jmsSession.createConsumer(jmsIncomingTopic)) { - messageConsumer.setMessageListener(this); - - // The endless loop that receives events over JMS - while (consumerThread.isAlive() && !stopOrderedFlag) { - ThreadUtilities.sleep(jmsConsumerProperties.getConsumerWaitTime()); - } - } catch (final Exception e) { - final String errorMessage = "failed to create a JMS message consumer for receiving messages"; - LOGGER.warn(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - } - - /* - * (non-Javadoc) - * - * @see javax.jms.MessageListener#onMessage(javax.jms.Message) - */ - @Override - public void onMessage(final Message jmsMessage) { - try { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("event received for {} for forwarding to Apex engine : {} {}", - this.getClass().getName() + ":" + this.name, jmsMessage.getJMSMessageID(), - jmsMessage.getJMSType()); - } - - eventReceiver.receiveEvent(jmsMessage); - } catch (final Exception e) { - final String errorMessage = "failed to receive message from JMS"; - LOGGER.warn(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.producer.ApexEventProducer#stop() - */ - @Override - public void stop() { - stopOrderedFlag = true; - - while (consumerThread.isAlive()) { - ThreadUtilities.sleep(jmsConsumerProperties.getConsumerWaitTime()); - } - - // Close the connection to the JMS server - try { - if (connection != null) { - connection.close(); - } - } catch (final Exception e) { - final String errorMessage = "close of connection to the JMS server failed"; - LOGGER.warn(errorMessage, e); - } - } - -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSProducer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSProducer.java deleted file mode 100644 index 86e9555f9..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSProducer.java +++ /dev/null @@ -1,287 +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.event.carrier.jms; - -import java.io.Serializable; -import java.util.EnumMap; -import java.util.Map; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.Topic; -import javax.naming.InitialContext; - -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventProducer; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.onap.policy.apex.service.engine.event.PeeredReference; -import org.onap.policy.apex.service.engine.event.SynchronousEventCache; -import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; -import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Concrete implementation of an Apex event producer that sends events using JMS. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexJMSProducer implements ApexEventProducer { - - // Get a reference to the logger - private static final Logger LOGGER = LoggerFactory.getLogger(ApexJMSProducer.class); - - // The JMS parameters read from the parameter service - private JMSCarrierTechnologyParameters jmsProducerProperties; - - // The connection to the JMS server - private Connection connection; - - // The JMS session on which we will send events - private Session jmsSession; - - // The producer on which we will send events - private MessageProducer messageProducer; - - // The name for this producer - private String name = null; - - // The peer references for this event handler - private Map peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class); - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#init(java.lang.String, - * org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters) - */ - @Override - public void init(final String producerName, final EventHandlerParameters producerParameters) - throws ApexEventException { - this.name = producerName; - - // Check and get the JMS Properties - if (!(producerParameters.getCarrierTechnologyParameters() instanceof JMSCarrierTechnologyParameters)) { - final String errorMessage = "specified producer properties are not applicable to a JMS producer (" + this.name + ")"; - LOGGER.warn(errorMessage); - throw new ApexEventException(errorMessage); - } - jmsProducerProperties = (JMSCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); - - // Look up the JMS connection factory - InitialContext jmsContext = null; - ConnectionFactory connectionFactory = null; - try { - jmsContext = new InitialContext(jmsProducerProperties.getJmsProducerProperties()); - connectionFactory = (ConnectionFactory) jmsContext.lookup(jmsProducerProperties.getConnectionFactory()); - - // Check if we actually got a connection factory - if (connectionFactory == null) { - throw new NullPointerException("JMS context lookup of \"" + jmsProducerProperties.getConnectionFactory() - + "\" returned null for producer (" + this.name + ")"); - } - } catch (final Exception e) { - final String errorMessage = "lookup of JMS connection factory \"" - + jmsProducerProperties.getConnectionFactory() + "\" failed for JMS producer properties \"" - + jmsProducerProperties.getJmsConsumerProperties() + "\" for producer (" + this.name + ")"; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - - // Lookup the topic on which we will send events - Topic jmsOutgoingTopic; - try { - jmsOutgoingTopic = (Topic) jmsContext.lookup(jmsProducerProperties.getProducerTopic()); - - // Check if we actually got a topic - if (jmsOutgoingTopic == null) { - throw new NullPointerException("JMS context lookup of \"" + jmsProducerProperties.getProducerTopic() - + "\" returned null for producer (" + this.name + ")"); - } - } catch (final Exception e) { - final String errorMessage = "lookup of JMS topic \"" + jmsProducerProperties.getProducerTopic() - + "\" failed for JMS producer properties \"" + jmsProducerProperties.getJmsProducerProperties() - + "\" for producer (" + this.name + ")"; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - - // Create and start a connection to the JMS server - try { - connection = connectionFactory.createConnection(jmsProducerProperties.getSecurityPrincipal(), - jmsProducerProperties.getSecurityCredentials()); - connection.start(); - } catch (final Exception e) { - final String errorMessage = "connection to JMS server failed for JMS properties \"" - + jmsProducerProperties.getJmsConsumerProperties() + "\" for producer (" + this.name + ")"; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - - // Create a JMS session for sending events - try { - jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } catch (final Exception e) { - final String errorMessage = "creation of session to JMS server failed for JMS properties \"" - + jmsProducerProperties.getJmsConsumerProperties() + "\" for producer (" + this.name + ")"; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - - // Create a JMS message producer for sending events - try { - messageProducer = jmsSession.createProducer(jmsOutgoingTopic); - } catch (final Exception e) { - final String errorMessage = - "creation of producer for sending events to JMS server failed for JMS properties \"" - + jmsProducerProperties.getJmsConsumerProperties() + "\""; - LOGGER.warn(errorMessage, e); - throw new ApexEventException(errorMessage, e); - } - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#getName() - */ - @Override - public String getName() { - return name; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#getPeeredReference(org.onap.policy.apex.service. - * parameters. eventhandler.EventHandlerPeeredMode) - */ - @Override - public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) { - return peerReferenceMap.get(peeredMode); - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#setPeeredReference(org.onap.policy.apex.service. - * parameters. eventhandler.EventHandlerPeeredMode, org.onap.policy.apex.service.engine.event.PeeredReference) - */ - @Override - public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) { - peerReferenceMap.put(peeredMode, peeredReference); - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#sendEvent(long, java.lang.String, - * java.lang.Object) - */ - @Override - public void sendEvent(final long executionId, final String eventname, final Object eventObject) { - // Check if this is a synchronized event, if so we have received a reply - final SynchronousEventCache synchronousEventCache = - (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS); - if (synchronousEventCache != null) { - synchronousEventCache.removeCachedEventToApexIfExists(executionId); - } - - // Check if the object to be sent is serializable - if (!Serializable.class.isAssignableFrom(eventObject.getClass())) { - final String errorMessage = "could not send event \"" + eventname + "\" on JMS message producer " - + this.name + ", object of type \"" + eventObject.getClass().getCanonicalName() - + "\" is not serializable"; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - - // The JMS message to send is constructed using the JMS session - Message jmsMessage = null; - - // Check the type of JMS message to send - if (jmsProducerProperties.isObjectMessageSending()) { - // We should send a JMS Object Message - try { - jmsMessage = jmsSession.createObjectMessage((Serializable) eventObject); - } catch (final Exception e) { - final String errorMessage = "could not send event \"" + eventname + "\" on JMS message producer " - + this.name + ", could not create JMS Object Message for object \"" + eventObject; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - } else { - // We should send a JMS Text Message - try { - jmsMessage = jmsSession.createTextMessage(eventObject.toString()); - } catch (final Exception e) { - final String errorMessage = "could not send event \"" + eventname + "\" on JMS message producer " - + this.name + ", could not create JMS Text Message for object \"" + eventObject; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - } - - try { - messageProducer.send(jmsMessage); - } catch (final Exception e) { - final String errorMessage = "could not send event \"" + eventname + "\" on JMS message producer " - + this.name + ", send failed for object \"" + eventObject; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.producer.ApexEventProducer#stop() - */ - @Override - public void stop() { - // Close the message producer - try { - messageProducer.close(); - } catch (final Exception e) { - final String errorMessage = "failed to close JMS message producer " + this.name + " for sending messages"; - LOGGER.warn(errorMessage, e); - } - - // Close the session - try { - jmsSession.close(); - } catch (final Exception e) { - final String errorMessage = "failed to close the JMS session for " + this.name + " for sending messages"; - LOGGER.warn(errorMessage, e); - } - - // Close the connection to the JMS server - try { - connection.close(); - } catch (final Exception e) { - final String errorMessage = "close of connection to the JMS server for " + this.name + " failed"; - LOGGER.warn(errorMessage, e); - } - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsConsumer.java new file mode 100644 index 000000000..de324512b --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsConsumer.java @@ -0,0 +1,280 @@ +/*- + * ============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.event.carrier.jms; + +import java.util.EnumMap; +import java.util.Map; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageListener; +import javax.jms.Session; +import javax.jms.Topic; +import javax.naming.InitialContext; + +import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.service.engine.event.ApexEventConsumer; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventReceiver; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.service.engine.event.PeeredReference; +import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; +import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class implements an Apex event consumer that receives events using JMS. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexJmsConsumer implements MessageListener, ApexEventConsumer, Runnable { + // Get a reference to the logger + private static final Logger LOGGER = LoggerFactory.getLogger(ApexJmsConsumer.class); + + // The Apex and JMS parameters read from the parameter service + private JmsCarrierTechnologyParameters jmsConsumerProperties; + + // The event receiver that will receive events from this consumer + private ApexEventReceiver eventReceiver; + + // The consumer thread and stopping flag + private Thread consumerThread; + private boolean stopOrderedFlag = false; + + // The connection to the JMS server + private Connection connection; + + // The topic on which we receive events from JMS + private Topic jmsIncomingTopic; + + // The name for this consumer + private String name = null; + + // The peer references for this event handler + private Map peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class); + + @Override + public void init(final String consumerName, final EventHandlerParameters consumerParameters, + final ApexEventReceiver incomingEventReceiver) throws ApexEventException { + this.eventReceiver = incomingEventReceiver; + + this.name = consumerName; + + // Check and get the JMS Properties + if (!(consumerParameters.getCarrierTechnologyParameters() instanceof JmsCarrierTechnologyParameters)) { + final String errorMessage = "specified consumer properties of type \"" + + consumerParameters.getCarrierTechnologyParameters().getClass().getCanonicalName() + + "\" are not applicable to a JMS consumer"; + LOGGER.warn(errorMessage); + throw new ApexEventException(errorMessage); + } + jmsConsumerProperties = (JmsCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); + + // Look up the JMS connection factory + InitialContext jmsContext = null; + ConnectionFactory connectionFactory = null; + try { + jmsContext = new InitialContext(jmsConsumerProperties.getJmsConsumerProperties()); + connectionFactory = (ConnectionFactory) jmsContext.lookup(jmsConsumerProperties.getConnectionFactory()); + + // Check if we actually got a connection factory + if (connectionFactory == null) { + throw new NullPointerException( + "JMS context lookup of \"" + jmsConsumerProperties.getConnectionFactory() + "\" returned null"); + } + } catch (final Exception e) { + final String errorMessage = "lookup of JMS connection factory \"" + + jmsConsumerProperties.getConnectionFactory() + "\" failed for JMS consumer properties \"" + + jmsConsumerProperties.getJmsConsumerProperties() + "\""; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + + // Lookup the topic on which we will receive events + try { + jmsIncomingTopic = (Topic) jmsContext.lookup(jmsConsumerProperties.getConsumerTopic()); + + // Check if we actually got a topic + if (jmsIncomingTopic == null) { + throw new NullPointerException( + "JMS context lookup of \"" + jmsConsumerProperties.getConsumerTopic() + "\" returned null"); + } + } catch (final Exception e) { + final String errorMessage = "lookup of JMS topic \"" + jmsConsumerProperties.getConsumerTopic() + + "\" failed for JMS consumer properties \"" + jmsConsumerProperties.getJmsConsumerProperties() + + "\""; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + + // Create and start a connection to the JMS server + try { + connection = connectionFactory.createConnection(jmsConsumerProperties.getSecurityPrincipal(), + jmsConsumerProperties.getSecurityCredentials()); + connection.start(); + } catch (final Exception e) { + final String errorMessage = "connection to the JMS server failed for JMS properties \"" + + jmsConsumerProperties.getJmsConsumerProperties() + "\""; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start() + */ + @Override + public void start() { + // Configure and start the event reception thread + final String threadName = this.getClass().getName() + ":" + this.name; + consumerThread = new ApplicationThreadFactory(threadName).newThread(this); + consumerThread.setDaemon(true); + consumerThread.start(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName() + */ + @Override + public String getName() { + return name; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.policy.apex.service. + * parameters. eventhandler.EventHandlerPeeredMode) + */ + @Override + public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) { + return peerReferenceMap.get(peeredMode); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.policy.apex.service. + * parameters. eventhandler.EventHandlerPeeredMode, org.onap.policy.apex.service.engine.event.PeeredReference) + */ + @Override + public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) { + peerReferenceMap.put(peeredMode, peeredReference); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + // JMS session and message consumer for receiving messages + try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { + // Create a message consumer for reception of messages and set this class as a message listener + createMessageConsumer(jmsSession); + } catch (final Exception e) { + final String errorMessage = "failed to create a JMS session towards the JMS server for receiving messages"; + LOGGER.warn(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + // Everything is now set up + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("event receiver " + this.getClass().getName() + ":" + this.name + " subscribed to JMS topic: " + + jmsConsumerProperties.getConsumerTopic()); + } + } + + /** + * The helper function to create a message consumer from a given JMS session. + * + * @param jmsSession a JMS session + */ + private void createMessageConsumer(final Session jmsSession) { + try (final MessageConsumer messageConsumer = jmsSession.createConsumer(jmsIncomingTopic)) { + messageConsumer.setMessageListener(this); + + // The endless loop that receives events over JMS + while (consumerThread.isAlive() && !stopOrderedFlag) { + ThreadUtilities.sleep(jmsConsumerProperties.getConsumerWaitTime()); + } + } catch (final Exception e) { + final String errorMessage = "failed to create a JMS message consumer for receiving messages"; + LOGGER.warn(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + } + + /* + * (non-Javadoc) + * + * @see javax.jms.MessageListener#onMessage(javax.jms.Message) + */ + @Override + public void onMessage(final Message jmsMessage) { + try { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("event received for {} for forwarding to Apex engine : {} {}", + this.getClass().getName() + ":" + this.name, jmsMessage.getJMSMessageID(), + jmsMessage.getJMSType()); + } + + eventReceiver.receiveEvent(jmsMessage); + } catch (final Exception e) { + final String errorMessage = "failed to receive message from JMS"; + LOGGER.warn(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.producer.ApexEventProducer#stop() + */ + @Override + public void stop() { + stopOrderedFlag = true; + + while (consumerThread.isAlive()) { + ThreadUtilities.sleep(jmsConsumerProperties.getConsumerWaitTime()); + } + + // Close the connection to the JMS server + try { + if (connection != null) { + connection.close(); + } + } catch (final Exception e) { + final String errorMessage = "close of connection to the JMS server failed"; + LOGGER.warn(errorMessage, e); + } + } + +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsProducer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsProducer.java new file mode 100644 index 000000000..7277a7dc3 --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsProducer.java @@ -0,0 +1,292 @@ +/*- + * ============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.event.carrier.jms; + +import java.io.Serializable; +import java.util.EnumMap; +import java.util.Map; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.Topic; +import javax.naming.InitialContext; + +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventProducer; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.service.engine.event.PeeredReference; +import org.onap.policy.apex.service.engine.event.SynchronousEventCache; +import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; +import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Concrete implementation of an Apex event producer that sends events using JMS. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexJmsProducer implements ApexEventProducer { + // Get a reference to the logger + private static final Logger LOGGER = LoggerFactory.getLogger(ApexJmsProducer.class); + + // Recurring string constants + private static final String COULD_NOT_SEND_PREFIX = "could not send event \""; + private static final String FOR_PRODUCER_TAG = "\" for producer ("; + private static final String JMS_MESSAGE_PRODUCER_TAG = "\" on JMS message producer "; + + // The JMS parameters read from the parameter service + private JmsCarrierTechnologyParameters jmsProducerProperties; + + // The connection to the JMS server + private Connection connection; + + // The JMS session on which we will send events + private Session jmsSession; + + // The producer on which we will send events + private MessageProducer messageProducer; + + // The name for this producer + private String name = null; + + // The peer references for this event handler + private Map peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class); + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#init(java.lang.String, + * org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters) + */ + @Override + public void init(final String producerName, final EventHandlerParameters producerParameters) + throws ApexEventException { + this.name = producerName; + + // Check and get the JMS Properties + if (!(producerParameters.getCarrierTechnologyParameters() instanceof JmsCarrierTechnologyParameters)) { + final String errorMessage = "specified producer properties are not applicable to a JMS producer (" + + this.name + ")"; + LOGGER.warn(errorMessage); + throw new ApexEventException(errorMessage); + } + jmsProducerProperties = (JmsCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + + // Look up the JMS connection factory + InitialContext jmsContext = null; + ConnectionFactory connectionFactory = null; + try { + jmsContext = new InitialContext(jmsProducerProperties.getJmsProducerProperties()); + connectionFactory = (ConnectionFactory) jmsContext.lookup(jmsProducerProperties.getConnectionFactory()); + + // Check if we actually got a connection factory + if (connectionFactory == null) { + throw new NullPointerException("JMS context lookup of \"" + jmsProducerProperties.getConnectionFactory() + + "\" returned null for producer (" + this.name + ")"); + } + } catch (final Exception e) { + final String errorMessage = "lookup of JMS connection factory \"" + + jmsProducerProperties.getConnectionFactory() + "\" failed for JMS producer properties \"" + + jmsProducerProperties.getJmsConsumerProperties() + FOR_PRODUCER_TAG + this.name + ")"; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + + // Lookup the topic on which we will send events + Topic jmsOutgoingTopic; + try { + jmsOutgoingTopic = (Topic) jmsContext.lookup(jmsProducerProperties.getProducerTopic()); + + // Check if we actually got a topic + if (jmsOutgoingTopic == null) { + throw new NullPointerException("JMS context lookup of \"" + jmsProducerProperties.getProducerTopic() + + "\" returned null for producer (" + this.name + ")"); + } + } catch (final Exception e) { + final String errorMessage = "lookup of JMS topic \"" + jmsProducerProperties.getProducerTopic() + + "\" failed for JMS producer properties \"" + + jmsProducerProperties.getJmsProducerProperties() + FOR_PRODUCER_TAG + this.name + ")"; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + + // Create and start a connection to the JMS server + try { + connection = connectionFactory.createConnection(jmsProducerProperties.getSecurityPrincipal(), + jmsProducerProperties.getSecurityCredentials()); + connection.start(); + } catch (final Exception e) { + final String errorMessage = "connection to JMS server failed for JMS properties \"" + + jmsProducerProperties.getJmsConsumerProperties() + FOR_PRODUCER_TAG + this.name + ")"; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + + // Create a JMS session for sending events + try { + jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } catch (final Exception e) { + final String errorMessage = "creation of session to JMS server failed for JMS properties \"" + + jmsProducerProperties.getJmsConsumerProperties() + FOR_PRODUCER_TAG + this.name + ")"; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + + // Create a JMS message producer for sending events + try { + messageProducer = jmsSession.createProducer(jmsOutgoingTopic); + } catch (final Exception e) { + final String errorMessage = "creation of producer for sending events " + + "to JMS server failed for JMS properties \"" + + jmsProducerProperties.getJmsConsumerProperties() + "\""; + LOGGER.warn(errorMessage, e); + throw new ApexEventException(errorMessage, e); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#getName() + */ + @Override + public String getName() { + return name; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#getPeeredReference(org.onap.policy.apex.service. + * parameters. eventhandler.EventHandlerPeeredMode) + */ + @Override + public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) { + return peerReferenceMap.get(peeredMode); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#setPeeredReference(org.onap.policy.apex.service. + * parameters. eventhandler.EventHandlerPeeredMode, org.onap.policy.apex.service.engine.event.PeeredReference) + */ + @Override + public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) { + peerReferenceMap.put(peeredMode, peeredReference); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#sendEvent(long, java.lang.String, + * java.lang.Object) + */ + @Override + public void sendEvent(final long executionId, final String eventname, final Object eventObject) { + // Check if this is a synchronized event, if so we have received a reply + final SynchronousEventCache synchronousEventCache = (SynchronousEventCache) peerReferenceMap + .get(EventHandlerPeeredMode.SYNCHRONOUS); + if (synchronousEventCache != null) { + synchronousEventCache.removeCachedEventToApexIfExists(executionId); + } + + // Check if the object to be sent is serializable + if (!Serializable.class.isAssignableFrom(eventObject.getClass())) { + final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + this.name + + ", object of type \"" + eventObject.getClass().getCanonicalName() + + "\" is not serializable"; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + + // The JMS message to send is constructed using the JMS session + Message jmsMessage = null; + + // Check the type of JMS message to send + if (jmsProducerProperties.isObjectMessageSending()) { + // We should send a JMS Object Message + try { + jmsMessage = jmsSession.createObjectMessage((Serializable) eventObject); + } catch (final Exception e) { + final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + + this.name + ", could not create JMS Object Message for object \"" + eventObject; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + } else { + // We should send a JMS Text Message + try { + jmsMessage = jmsSession.createTextMessage(eventObject.toString()); + } catch (final Exception e) { + final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + + this.name + ", could not create JMS Text Message for object \"" + eventObject; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + } + + try { + messageProducer.send(jmsMessage); + } catch (final Exception e) { + final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + this.name + + ", send failed for object \"" + eventObject; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.producer.ApexEventProducer#stop() + */ + @Override + public void stop() { + // Close the message producer + try { + messageProducer.close(); + } catch (final Exception e) { + final String errorMessage = "failed to close JMS message producer " + this.name + " for sending messages"; + LOGGER.warn(errorMessage, e); + } + + // Close the session + try { + jmsSession.close(); + } catch (final Exception e) { + final String errorMessage = "failed to close the JMS session for " + this.name + " for sending messages"; + LOGGER.warn(errorMessage, e); + } + + // Close the connection to the JMS server + try { + connection.close(); + } catch (final Exception e) { + final String errorMessage = "close of connection to the JMS server for " + this.name + " failed"; + LOGGER.warn(errorMessage, e); + } + } +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JMSCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JMSCarrierTechnologyParameters.java deleted file mode 100644 index 80977b5d8..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JMSCarrierTechnologyParameters.java +++ /dev/null @@ -1,375 +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.event.carrier.jms; - -import java.util.Properties; - -import javax.naming.Context; - -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ValidationStatus; - -/** - * Apex parameters for JMS as an event carrier technology. - *

- * The parameters for this plugin are: - *

    - *
  1. initialContextFactory: JMS uses a naming {@link Context} object to look up the locations of JMS servers and JMS - * topics. An Initial Context Factory is used to when creating a {@link Context} object that can be used for JMS - * lookups. The value of this parameter is passed to the {@link Context} with the label - * {@link Context#INITIAL_CONTEXT_FACTORY}. Its value must be the full canonical path to a class that implements the - * {@code javax.naming.spi.InitialContextFactory} interface. The parameter defaults to the string value - * {@code org.jboss.naming.remote.client.InitialContextFactory}. - *
  2. providerURL: The location of the server to use for naming context lookups. The value of this parameter is passed - * to the {@link Context} with the label {@link Context#PROVIDER_URL}. Its value must be a URL that identifies the JMS - * naming server. The parameter defaults to the string value {@code remote://localhost:4447}. - *
  3. securityPrincipal: The user name to use for JMS access. The value of this parameter is passed to the - * {@link Context} with the label {@link Context#SECURITY_PRINCIPAL}. Its value must be the user name of a user defined - * on the JMS server. The parameter defaults to the string value {@code userid}. - *
  4. securityCredentials:The password to use for JMS access. The value of this parameter is passed to the - * {@link Context} with the label {@link Context#SECURITY_CREDENTIALS}. Its value must be the password of a suer defined - * on the JMS server. The parameter defaults to the string value {@code password}. - *
  5. connectionFactory: JMS uses a {@link javax.jms.ConnectionFactory} instance to create connections towards a JMS - * server. The connection factory to use is held in the JMS {@link Context} object. This parameter specifies the label - * to use to look up the {@link javax.jms.ConnectionFactory} instance from the JMS {@link Context}. - *
  6. producerTopic: JMS uses a {@link javax.jms.Topic} instance to for sending and receiving messages. The topic to - * use for sending events to JMS from an Apex producer is held in the JMS {@link Context} object. This parameter - * specifies the label to use to look up the {@link javax.jms.Topic} instance in the JMS {@link Context} for the JMS - * server. The topic must, of course, also be defined on the JMS server. The parameter defaults to the string value - * {@code apex-out}. - *
  7. consumerTopic: The topic to use for receiving events from JMS in an Apex consumer is held in the JMS - * {@link Context} object. This parameter specifies the label to use to look up the {@link javax.jms.Topic} instance in - * the JMS {@link Context} for the JMS server. The topic must, of course, also be defined on the JMS server. The - * parameter defaults to the string value {@code apex-in}. - *
  8. consumerWaitTime: The amount of milliseconds a JMS consumer should wait between checks of its thread execution - * status. The parameter defaults to the long value {@code 100}. - *
  9. objectMessageSending: A flag that indicates whether Apex producers should send JMS messages as - * {@link javax.jms.ObjectMessage} instances for java objects (value {@code true}) or as {@link javax.jms.TextMessage} - * instances for strings (value {@code false}) . The parameter defaults to the boolean value {@code true}. - *
- * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JMSCarrierTechnologyParameters extends CarrierTechnologyParameters { - /** The label of this carrier technology. */ - public static final String JMS_CARRIER_TECHNOLOGY_LABEL = "JMS"; - - /** The producer plugin class for the JMS carrier technology. */ - public static final String JMS_EVENT_PRODUCER_PLUGIN_CLASS = ApexJMSProducer.class.getCanonicalName(); - - /** The consumer plugin class for the JMS carrier technology. */ - public static final String JMS_EVENT_CONSUMER_PLUGIN_CLASS = ApexJMSConsumer.class.getCanonicalName(); - - // @formatter:off - - // Default parameter values - private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory"; - private static final String DEFAULT_INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory"; - private static final String DEFAULT_PROVIDER_URL = "remote://localhost:4447"; - private static final String DEFAULT_SECURITY_PRINCIPAL = "userid"; - private static final String DEFAULT_SECURITY_CREDENTIALS = "password"; - private static final String DEFAULT_CONSUMER_TOPIC = "apex-in"; - private static final String DEFAULT_PRODUCER_TOPIC = "apex-out"; - private static final int DEFAULT_CONSUMER_WAIT_TIME = 100; - private static final boolean DEFAULT_TO_OBJECT_MESSAGE_SENDING = true; - - // Parameter property map tokens - private static final String PROPERTY_INITIAL_CONTEXT_FACTORY = Context.INITIAL_CONTEXT_FACTORY; - private static final String PROPERTY_PROVIDER_URL = Context.PROVIDER_URL; - private static final String PROPERTY_SECURITY_PRINCIPAL = Context.SECURITY_PRINCIPAL; - private static final String PROPERTY_SECURITY_CREDENTIALS = Context.SECURITY_CREDENTIALS; - - // JMS carrier parameters - private String connectionFactory = DEFAULT_CONNECTION_FACTORY; - private String initialContextFactory = DEFAULT_INITIAL_CONTEXT_FACTORY; - private String providerUrl = DEFAULT_PROVIDER_URL; - private String securityPrincipal = DEFAULT_SECURITY_PRINCIPAL; - private String securityCredentials = DEFAULT_SECURITY_CREDENTIALS; - private String producerTopic = DEFAULT_PRODUCER_TOPIC; - private String consumerTopic = DEFAULT_CONSUMER_TOPIC; - private int consumerWaitTime = DEFAULT_CONSUMER_WAIT_TIME; - private boolean objectMessageSending = DEFAULT_TO_OBJECT_MESSAGE_SENDING; - // @formatter:on - - /** - * Constructor to create a jms carrier technology parameters instance and register the instance with the parameter - * service. - */ - public JMSCarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the JMS carrier technology - this.setLabel(JMS_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(JMS_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(JMS_EVENT_CONSUMER_PLUGIN_CLASS); - } - - /** - * Gets the JMS producer properties. - * - * @return the JMS producer properties - */ - public Properties getJmsProducerProperties() { - return getJmsProperties(); - } - - /** - * Gets the jms consumer properties. - * - * @return the jms consumer properties - */ - public Properties getJmsConsumerProperties() { - return getJmsProperties(); - } - - /** - * Gets the JMS consumer properties. - * - * @return the jms consumer properties - */ - private Properties getJmsProperties() { - final Properties jmsProperties = new Properties(); - - jmsProperties.put(PROPERTY_INITIAL_CONTEXT_FACTORY, initialContextFactory); - jmsProperties.put(PROPERTY_PROVIDER_URL, providerUrl); - jmsProperties.put(PROPERTY_SECURITY_PRINCIPAL, securityPrincipal); - jmsProperties.put(PROPERTY_SECURITY_CREDENTIALS, securityCredentials); - - return jmsProperties; - } - - /** - * Gets the connection factory. - * - * @return the connection factory - */ - public String getConnectionFactory() { - return connectionFactory; - } - - /** - * Gets the initial context factory. - * - * @return the initial context factory - */ - public String getInitialContextFactory() { - return initialContextFactory; - } - - /** - * Gets the provider URL. - * - * @return the provider URL - */ - public String getProviderUrl() { - return providerUrl; - } - - /** - * Gets the security principal. - * - * @return the security principal - */ - public String getSecurityPrincipal() { - return securityPrincipal; - } - - /** - * Gets the security credentials. - * - * @return the security credentials - */ - public String getSecurityCredentials() { - return securityCredentials; - } - - /** - * Gets the producer topic. - * - * @return the producer topic - */ - public String getProducerTopic() { - return producerTopic; - } - - /** - * Gets the consumer topic. - * - * @return the consumer topic - */ - public String getConsumerTopic() { - return consumerTopic; - } - - /** - * Gets the consumer wait time. - * - * @return the consumer wait time - */ - public long getConsumerWaitTime() { - return consumerWaitTime; - } - - /** - * Sets the connection factory. - * - * @param connectionFactory the connection factory - */ - public void setConnectionFactory(final String connectionFactory) { - this.connectionFactory = connectionFactory; - } - - /** - * Sets the initial context factory. - * - * @param initialContextFactory the initial context factory - */ - public void setInitialContextFactory(final String initialContextFactory) { - this.initialContextFactory = initialContextFactory; - } - - /** - * Sets the provider URL. - * - * @param providerUrl the provider URL - */ - public void setProviderUrl(final String providerUrl) { - this.providerUrl = providerUrl; - } - - /** - * Sets the security principal. - * - * @param securityPrincipal the security principal - */ - public void setSecurityPrincipal(final String securityPrincipal) { - this.securityPrincipal = securityPrincipal; - } - - /** - * Sets the security credentials. - * - * @param securityCredentials the security credentials - */ - public void setSecurityCredentials(final String securityCredentials) { - this.securityCredentials = securityCredentials; - } - - /** - * Sets the producer topic. - * - * @param producerTopic the producer topic - */ - public void setProducerTopic(final String producerTopic) { - this.producerTopic = producerTopic; - } - - /** - * Sets the consumer topic. - * - * @param consumerTopic the consumer topic - */ - public void setConsumerTopic(final String consumerTopic) { - this.consumerTopic = consumerTopic; - } - - /** - * Sets the consumer wait time. - * - * @param consumerWaitTime the consumer wait time - */ - public void setConsumerWaitTime(final int consumerWaitTime) { - this.consumerWaitTime = consumerWaitTime; - } - - /** - * Checks if is object message sending. - * - * @return true, if checks if is object message sending - */ - public boolean isObjectMessageSending() { - return objectMessageSending; - } - - /** - * Sets the object message sending. - * - * @param objectMessageSending the object message sending - */ - public void setObjectMessageSending(final boolean objectMessageSending) { - this.objectMessageSending = objectMessageSending; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = super.validate(); - - if (initialContextFactory == null || initialContextFactory.trim().length() == 0) { - result.setResult("initialContextFactory", ValidationStatus.INVALID, - "initialContextFactory must be specified as a string that is a class that implements the " - + "interface org.jboss.naming.remote.client.InitialContextFactory"); - } - - if (providerUrl == null || providerUrl.trim().length() == 0) { - result.setResult("providerUrl", ValidationStatus.INVALID, - "providerUrl must be specified as a URL string that specifies the location of " - + "configuration information for the service provider to use " - + "such as remote://localhost:4447"); - } - - if (securityPrincipal == null || securityPrincipal.trim().length() == 0) { - result.setResult("securityPrincipal", ValidationStatus.INVALID, - "securityPrincipal must be specified the identity of the principal for authenticating " - + "the caller to the service"); - } - - if (securityCredentials == null || securityCredentials.trim().length() == 0) { - result.setResult("securityCredentials", ValidationStatus.INVALID, - " securityCredentials must be specified as the credentials of the " - + "principal for authenticating the caller to the service"); - } - - if (producerTopic == null || producerTopic.trim().length() == 0) { - result.setResult("producerTopic", ValidationStatus.INVALID, - " producerTopic must be a string that identifies the JMS topic " - + "on which Apex will send events"); - } - - if (consumerTopic == null || consumerTopic.trim().length() == 0) { - result.setResult("consumerTopic", ValidationStatus.INVALID, - " consumerTopic must be a string that identifies the JMS topic " - + "on which Apex will recieve events"); - } - - if (consumerWaitTime < 0) { - result.setResult("consumerWaitTime", ValidationStatus.INVALID, - "[" + consumerWaitTime + "] invalid, must be specified as consumerWaitTime >= 0"); - } - - return result; - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java new file mode 100644 index 000000000..8b120ca3a --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java @@ -0,0 +1,375 @@ +/*- + * ============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.event.carrier.jms; + +import java.util.Properties; + +import javax.naming.Context; + +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; + +/** + * Apex parameters for JMS as an event carrier technology. + * + *

The parameters for this plugin are: + *

    + *
  1. initialContextFactory: JMS uses a naming {@link Context} object to look up the locations of JMS servers and JMS + * topics. An Initial Context Factory is used to when creating a {@link Context} object that can be used for JMS + * lookups. The value of this parameter is passed to the {@link Context} with the label + * {@link Context#INITIAL_CONTEXT_FACTORY}. Its value must be the full canonical path to a class that implements the + * {@code javax.naming.spi.InitialContextFactory} interface. The parameter defaults to the string value + * {@code org.jboss.naming.remote.client.InitialContextFactory}. + *
  2. providerURL: The location of the server to use for naming context lookups. The value of this parameter is passed + * to the {@link Context} with the label {@link Context#PROVIDER_URL}. Its value must be a URL that identifies the JMS + * naming server. The parameter defaults to the string value {@code remote://localhost:4447}. + *
  3. securityPrincipal: The user name to use for JMS access. The value of this parameter is passed to the + * {@link Context} with the label {@link Context#SECURITY_PRINCIPAL}. Its value must be the user name of a user defined + * on the JMS server. The parameter defaults to the string value {@code userid}. + *
  4. securityCredentials:The password to use for JMS access. The value of this parameter is passed to the + * {@link Context} with the label {@link Context#SECURITY_CREDENTIALS}. Its value must be the password of a suer defined + * on the JMS server. The parameter defaults to the string value {@code password}. + *
  5. connectionFactory: JMS uses a {@link javax.jms.ConnectionFactory} instance to create connections towards a JMS + * server. The connection factory to use is held in the JMS {@link Context} object. This parameter specifies the label + * to use to look up the {@link javax.jms.ConnectionFactory} instance from the JMS {@link Context}. + *
  6. producerTopic: JMS uses a {@link javax.jms.Topic} instance to for sending and receiving messages. The topic to + * use for sending events to JMS from an Apex producer is held in the JMS {@link Context} object. This parameter + * specifies the label to use to look up the {@link javax.jms.Topic} instance in the JMS {@link Context} for the JMS + * server. The topic must, of course, also be defined on the JMS server. The parameter defaults to the string value + * {@code apex-out}. + *
  7. consumerTopic: The topic to use for receiving events from JMS in an Apex consumer is held in the JMS + * {@link Context} object. This parameter specifies the label to use to look up the {@link javax.jms.Topic} instance in + * the JMS {@link Context} for the JMS server. The topic must, of course, also be defined on the JMS server. The + * parameter defaults to the string value {@code apex-in}. + *
  8. consumerWaitTime: The amount of milliseconds a JMS consumer should wait between checks of its thread execution + * status. The parameter defaults to the long value {@code 100}. + *
  9. objectMessageSending: A flag that indicates whether Apex producers should send JMS messages as + * {@link javax.jms.ObjectMessage} instances for java objects (value {@code true}) or as {@link javax.jms.TextMessage} + * instances for strings (value {@code false}) . The parameter defaults to the boolean value {@code true}. + *
+ * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JmsCarrierTechnologyParameters extends CarrierTechnologyParameters { + /** The label of this carrier technology. */ + public static final String JMS_CARRIER_TECHNOLOGY_LABEL = "JMS"; + + /** The producer plugin class for the JMS carrier technology. */ + public static final String JMS_EVENT_PRODUCER_PLUGIN_CLASS = ApexJmsProducer.class.getCanonicalName(); + + /** The consumer plugin class for the JMS carrier technology. */ + public static final String JMS_EVENT_CONSUMER_PLUGIN_CLASS = ApexJmsConsumer.class.getCanonicalName(); + + // @formatter:off + + // Default parameter values + private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory"; + private static final String DEFAULT_INITIAL_CTXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory"; + private static final String DEFAULT_PROVIDER_URL = "remote://localhost:4447"; + private static final String DEFAULT_SECURITY_PRINCIPAL = "userid"; + private static final String DEFAULT_SECURITY_CREDENTIALS = "password"; + private static final String DEFAULT_CONSUMER_TOPIC = "apex-in"; + private static final String DEFAULT_PRODUCER_TOPIC = "apex-out"; + private static final int DEFAULT_CONSUMER_WAIT_TIME = 100; + private static final boolean DEFAULT_TO_OBJECT_MSG_SENDING = true; + + // Parameter property map tokens + private static final String PROPERTY_INITIAL_CONTEXT_FACTORY = Context.INITIAL_CONTEXT_FACTORY; + private static final String PROPERTY_PROVIDER_URL = Context.PROVIDER_URL; + private static final String PROPERTY_SECURITY_PRINCIPAL = Context.SECURITY_PRINCIPAL; + private static final String PROPERTY_SECURITY_CREDENTIALS = Context.SECURITY_CREDENTIALS; + + // JMS carrier parameters + private String connectionFactory = DEFAULT_CONNECTION_FACTORY; + private String initialContextFactory = DEFAULT_INITIAL_CTXT_FACTORY; + private String providerUrl = DEFAULT_PROVIDER_URL; + private String securityPrincipal = DEFAULT_SECURITY_PRINCIPAL; + private String securityCredentials = DEFAULT_SECURITY_CREDENTIALS; + private String producerTopic = DEFAULT_PRODUCER_TOPIC; + private String consumerTopic = DEFAULT_CONSUMER_TOPIC; + private int consumerWaitTime = DEFAULT_CONSUMER_WAIT_TIME; + private boolean objectMessageSending = DEFAULT_TO_OBJECT_MSG_SENDING; + // @formatter:on + + /** + * Constructor to create a jms carrier technology parameters instance and register the instance with the parameter + * service. + */ + public JmsCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the JMS carrier technology + this.setLabel(JMS_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(JMS_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(JMS_EVENT_CONSUMER_PLUGIN_CLASS); + } + + /** + * Gets the JMS producer properties. + * + * @return the JMS producer properties + */ + public Properties getJmsProducerProperties() { + return getJmsProperties(); + } + + /** + * Gets the jms consumer properties. + * + * @return the jms consumer properties + */ + public Properties getJmsConsumerProperties() { + return getJmsProperties(); + } + + /** + * Gets the JMS consumer properties. + * + * @return the jms consumer properties + */ + private Properties getJmsProperties() { + final Properties jmsProperties = new Properties(); + + jmsProperties.put(PROPERTY_INITIAL_CONTEXT_FACTORY, initialContextFactory); + jmsProperties.put(PROPERTY_PROVIDER_URL, providerUrl); + jmsProperties.put(PROPERTY_SECURITY_PRINCIPAL, securityPrincipal); + jmsProperties.put(PROPERTY_SECURITY_CREDENTIALS, securityCredentials); + + return jmsProperties; + } + + /** + * Gets the connection factory. + * + * @return the connection factory + */ + public String getConnectionFactory() { + return connectionFactory; + } + + /** + * Gets the initial context factory. + * + * @return the initial context factory + */ + public String getInitialContextFactory() { + return initialContextFactory; + } + + /** + * Gets the provider URL. + * + * @return the provider URL + */ + public String getProviderUrl() { + return providerUrl; + } + + /** + * Gets the security principal. + * + * @return the security principal + */ + public String getSecurityPrincipal() { + return securityPrincipal; + } + + /** + * Gets the security credentials. + * + * @return the security credentials + */ + public String getSecurityCredentials() { + return securityCredentials; + } + + /** + * Gets the producer topic. + * + * @return the producer topic + */ + public String getProducerTopic() { + return producerTopic; + } + + /** + * Gets the consumer topic. + * + * @return the consumer topic + */ + public String getConsumerTopic() { + return consumerTopic; + } + + /** + * Gets the consumer wait time. + * + * @return the consumer wait time + */ + public long getConsumerWaitTime() { + return consumerWaitTime; + } + + /** + * Sets the connection factory. + * + * @param connectionFactory the connection factory + */ + public void setConnectionFactory(final String connectionFactory) { + this.connectionFactory = connectionFactory; + } + + /** + * Sets the initial context factory. + * + * @param initialContextFactory the initial context factory + */ + public void setInitialContextFactory(final String initialContextFactory) { + this.initialContextFactory = initialContextFactory; + } + + /** + * Sets the provider URL. + * + * @param providerUrl the provider URL + */ + public void setProviderUrl(final String providerUrl) { + this.providerUrl = providerUrl; + } + + /** + * Sets the security principal. + * + * @param securityPrincipal the security principal + */ + public void setSecurityPrincipal(final String securityPrincipal) { + this.securityPrincipal = securityPrincipal; + } + + /** + * Sets the security credentials. + * + * @param securityCredentials the security credentials + */ + public void setSecurityCredentials(final String securityCredentials) { + this.securityCredentials = securityCredentials; + } + + /** + * Sets the producer topic. + * + * @param producerTopic the producer topic + */ + public void setProducerTopic(final String producerTopic) { + this.producerTopic = producerTopic; + } + + /** + * Sets the consumer topic. + * + * @param consumerTopic the consumer topic + */ + public void setConsumerTopic(final String consumerTopic) { + this.consumerTopic = consumerTopic; + } + + /** + * Sets the consumer wait time. + * + * @param consumerWaitTime the consumer wait time + */ + public void setConsumerWaitTime(final int consumerWaitTime) { + this.consumerWaitTime = consumerWaitTime; + } + + /** + * Checks if is object message sending. + * + * @return true, if checks if is object message sending + */ + public boolean isObjectMessageSending() { + return objectMessageSending; + } + + /** + * Sets the object message sending. + * + * @param objectMessageSending the object message sending + */ + public void setObjectMessageSending(final boolean objectMessageSending) { + this.objectMessageSending = objectMessageSending; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); + + if (initialContextFactory == null || initialContextFactory.trim().length() == 0) { + result.setResult("initialContextFactory", ValidationStatus.INVALID, + "initialContextFactory must be specified as a string that is a class that implements the " + + "interface org.jboss.naming.remote.client.InitialContextFactory"); + } + + if (providerUrl == null || providerUrl.trim().length() == 0) { + result.setResult("providerUrl", ValidationStatus.INVALID, + "providerUrl must be specified as a URL string that specifies the location of " + + "configuration information for the service provider to use " + + "such as remote://localhost:4447"); + } + + if (securityPrincipal == null || securityPrincipal.trim().length() == 0) { + result.setResult("securityPrincipal", ValidationStatus.INVALID, + "securityPrincipal must be specified the identity of the principal for authenticating " + + "the caller to the service"); + } + + if (securityCredentials == null || securityCredentials.trim().length() == 0) { + result.setResult("securityCredentials", ValidationStatus.INVALID, + " securityCredentials must be specified as the credentials of the " + + "principal for authenticating the caller to the service"); + } + + if (producerTopic == null || producerTopic.trim().length() == 0) { + result.setResult("producerTopic", ValidationStatus.INVALID, + " producerTopic must be a string that identifies the JMS topic " + + "on which Apex will send events"); + } + + if (consumerTopic == null || consumerTopic.trim().length() == 0) { + result.setResult("consumerTopic", ValidationStatus.INVALID, + " consumerTopic must be a string that identifies the JMS topic " + + "on which Apex will recieve events"); + } + + if (consumerWaitTime < 0) { + result.setResult("consumerWaitTime", ValidationStatus.INVALID, + "[" + consumerWaitTime + "] invalid, must be specified as consumerWaitTime >= 0"); + } + + return result; + } +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java index 3351a58e9..dfb12617c 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java @@ -47,7 +47,7 @@ public class ApexKafkaConsumer implements ApexEventConsumer, Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(ApexKafkaConsumer.class); // The Kafka parameters read from the parameter service - private KAFKACarrierTechnologyParameters kafkaConsumerProperties; + private KafkaCarrierTechnologyParameters kafkaConsumerProperties; // The event receiver that will receive events from this consumer private ApexEventReceiver eventReceiver; @@ -79,7 +79,7 @@ public class ApexKafkaConsumer implements ApexEventConsumer, Runnable { this.name = consumerName; // Check and get the Kafka Properties - if (!(consumerParameters.getCarrierTechnologyParameters() instanceof KAFKACarrierTechnologyParameters)) { + if (!(consumerParameters.getCarrierTechnologyParameters() instanceof KafkaCarrierTechnologyParameters)) { LOGGER.warn("specified consumer properties of type \"" + consumerParameters.getCarrierTechnologyParameters().getClass().getCanonicalName() + "\" are not applicable to a Kafka consumer"); @@ -88,10 +88,10 @@ public class ApexKafkaConsumer implements ApexEventConsumer, Runnable { + "\" are not applicable to a Kafka consumer"); } kafkaConsumerProperties = - (KAFKACarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); + (KafkaCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); // Kick off the Kafka consumer - kafkaConsumer = new KafkaConsumer(kafkaConsumerProperties.getKafkaConsumerProperties()); + kafkaConsumer = new KafkaConsumer<>(kafkaConsumerProperties.getKafkaConsumerProperties()); kafkaConsumer.subscribe(kafkaConsumerProperties.getConsumerTopicList()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("event receiver for " + this.getClass().getName() + ":" + this.name + " subscribed to topics: " @@ -153,7 +153,7 @@ public class ApexKafkaConsumer implements ApexEventConsumer, Runnable { @Override public void run() { // Kick off the Kafka consumer - kafkaConsumer = new KafkaConsumer(kafkaConsumerProperties.getKafkaConsumerProperties()); + kafkaConsumer = new KafkaConsumer<>(kafkaConsumerProperties.getKafkaConsumerProperties()); kafkaConsumer.subscribe(kafkaConsumerProperties.getConsumerTopicList()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("event receiver for " + this.getClass().getName() + ":" + this.name + " subscribed to topics: " diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaProducer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaProducer.java index fb851bc70..c83c0ae1e 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaProducer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaProducer.java @@ -46,7 +46,7 @@ public class ApexKafkaProducer implements ApexEventProducer { private static final Logger LOGGER = LoggerFactory.getLogger(ApexKafkaProducer.class); // The Kafka parameters read from the parameter service - private KAFKACarrierTechnologyParameters kafkaProducerProperties; + private KafkaCarrierTechnologyParameters kafkaProducerProperties; // The Kafka Producer used to send events using Kafka private Producer kafkaProducer; @@ -63,13 +63,14 @@ public class ApexKafkaProducer implements ApexEventProducer { this.name = producerName; // Check and get the Kafka Properties - if (!(producerParameters.getCarrierTechnologyParameters() instanceof KAFKACarrierTechnologyParameters)) { - LOGGER.warn("specified producer properties are not applicable to a Kafka producer (" + this.name + ")"); + if (!(producerParameters.getCarrierTechnologyParameters() instanceof KafkaCarrierTechnologyParameters)) { + String message = "specified producer properties are not applicable to a Kafka producer (" + this.name + ")"; + LOGGER.warn(message); throw new ApexEventException( - "specified producer properties are not applicable to a Kafka producer (" + this.name + ")"); + message); } kafkaProducerProperties = - (KAFKACarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + (KafkaCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); } /* @@ -122,7 +123,7 @@ public class ApexKafkaProducer implements ApexEventProducer { // Kafka producer must be started in the same thread as it is stopped, so we must start it here if (kafkaProducer == null) { // Kick off the Kafka producer - kafkaProducer = new KafkaProducer(kafkaProducerProperties.getKafkaProducerProperties()); + kafkaProducer = new KafkaProducer<>(kafkaProducerProperties.getKafkaProducerProperties()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("event producer " + this.name + " is ready to send to topics: " + kafkaProducerProperties.getProducerTopic()); diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KAFKACarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KAFKACarrierTechnologyParameters.java deleted file mode 100644 index 5ce96662e..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KAFKACarrierTechnologyParameters.java +++ /dev/null @@ -1,419 +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.event.carrier.kafka; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Properties; - -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ValidationStatus; - -/** - * Apex parameters for Kafka as an event carrier technology. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class KAFKACarrierTechnologyParameters extends CarrierTechnologyParameters { - // @formatter:off - /** The label of this carrier technology. */ - public static final String KAFKA_CARRIER_TECHNOLOGY_LABEL = "KAFKA"; - - /** The producer plugin class for the Kafka carrier technology. */ - public static final String KAFKA_EVENT_PRODUCER_PLUGIN_CLASS = ApexKafkaProducer.class.getCanonicalName(); - - /** The consumer plugin class for the Kafka carrier technology. */ - public static final String KAFKA_EVENT_CONSUMER_PLUGIN_CLASS = ApexKafkaConsumer.class.getCanonicalName(); - - // Repeated strings in messages - private static final String SPECIFY_AS_STRING_MESSAGE = "not specified, must be specified as a string"; - - // Default parameter values - private static final String DEFAULT_ACKS = "all"; - private static final String DEFAULT_BOOTSTRAP_SERVERS = "localhost:9092"; - private static final int DEFAULT_RETRIES = 0; - private static final int DEFAULT_BATCH_SIZE = 16384; - private static final int DEFAULT_LINGER_TIME = 1; - private static final long DEFAULT_BUFFER_MEMORY = 33554432; - private static final String DEFAULT_GROUP_ID = "default-group-id"; - private static final boolean DEFAULT_ENABLE_AUTO_COMMIT = true; - private static final int DEFAULT_AUTO_COMMIT_TIME = 1000; - private static final int DEFAULT_SESSION_TIMEOUT = 30000; - private static final String DEFAULT_PRODUCER_TOPIC = "apex-out"; - private static final int DEFAULT_CONSUMER_POLL_TIME = 100; - private static final String[] DEFAULT_CONSUMER_TOPIC_LIST = {"apex-in"}; - private static final String DEFAULT_KEY_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer"; - private static final String DEFAULT_VALUE_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer"; - private static final String DEFAULT_KEY_DESERIALIZER = "org.apache.kafka.common.serialization.StringDeserializer"; - private static final String DEFAULT_VALUE_DESERIALIZER = "org.apache.kafka.common.serialization.StringDeserializer"; - - // Parameter property map tokens - private static final String PROPERTY_BOOTSTRAP_SERVERS = "bootstrap.servers"; - private static final String PROPERTY_ACKS = "acks"; - private static final String PROPERTY_RETRIES = "retries"; - private static final String PROPERTY_BATCH_SIZE = "batch.size"; - private static final String PROPERTY_LINGER_TIME = "linger.ms"; - private static final String PROPERTY_BUFFER_MEMORY = "buffer.memory"; - private static final String PROPERTY_GROUP_ID = "group.id"; - private static final String PROPERTY_ENABLE_AUTO_COMMIT = "enable.auto.commit"; - private static final String PROPERTY_AUTO_COMMIT_TIME = "auto.commit.interval.ms"; - private static final String PROPERTY_SESSION_TIMEOUT = "session.timeout.ms"; - private static final String PROPERTY_KEY_SERIALIZER = "key.serializer"; - private static final String PROPERTY_VALUE_SERIALIZER = "value.serializer"; - private static final String PROPERTY_KEY_DESERIALIZER = "key.deserializer"; - private static final String PROPERTY_VALUE_DESERIALIZER = "value.deserializer"; - - // kafka carrier parameters - private String bootstrapServers = DEFAULT_BOOTSTRAP_SERVERS; - private String acks = DEFAULT_ACKS; - private int retries = DEFAULT_RETRIES; - private int batchSize = DEFAULT_BATCH_SIZE; - private int lingerTime = DEFAULT_LINGER_TIME; - private long bufferMemory = DEFAULT_BUFFER_MEMORY; - private String groupId = DEFAULT_GROUP_ID; - private boolean enableAutoCommit = DEFAULT_ENABLE_AUTO_COMMIT; - private int autoCommitTime = DEFAULT_AUTO_COMMIT_TIME; - private int sessionTimeout = DEFAULT_SESSION_TIMEOUT; - private String producerTopic = DEFAULT_PRODUCER_TOPIC; - private int consumerPollTime = DEFAULT_CONSUMER_POLL_TIME; - private String[] consumerTopicList = DEFAULT_CONSUMER_TOPIC_LIST; - private String keySerializer = DEFAULT_KEY_SERIALIZER; - private String valueSerializer = DEFAULT_VALUE_SERIALIZER; - private String keyDeserializer = DEFAULT_KEY_DESERIALIZER; - private String valueDeserializer = DEFAULT_VALUE_DESERIALIZER; - // @formatter:on - - /** - * Constructor to create a kafka carrier technology parameters instance and register the instance with the parameter - * service. - */ - public KAFKACarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the kafka carrier technology - this.setLabel(KAFKA_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(KAFKA_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(KAFKA_EVENT_CONSUMER_PLUGIN_CLASS); - } - - /** - * Gets the kafka producer properties. - * - * @return the kafka producer properties - */ - public Properties getKafkaProducerProperties() { - final Properties kafkaProperties = new Properties(); - - kafkaProperties.put(PROPERTY_BOOTSTRAP_SERVERS, bootstrapServers); - kafkaProperties.put(PROPERTY_ACKS, acks); - kafkaProperties.put(PROPERTY_RETRIES, retries); - kafkaProperties.put(PROPERTY_BATCH_SIZE, batchSize); - kafkaProperties.put(PROPERTY_LINGER_TIME, lingerTime); - kafkaProperties.put(PROPERTY_BUFFER_MEMORY, bufferMemory); - kafkaProperties.put(PROPERTY_KEY_SERIALIZER, keySerializer); - kafkaProperties.put(PROPERTY_VALUE_SERIALIZER, valueSerializer); - - return kafkaProperties; - } - - /** - * Gets the kafka consumer properties. - * - * @return the kafka consumer properties - */ - public Properties getKafkaConsumerProperties() { - final Properties kafkaProperties = new Properties(); - - kafkaProperties.put(PROPERTY_BOOTSTRAP_SERVERS, bootstrapServers); - kafkaProperties.put(PROPERTY_GROUP_ID, groupId); - kafkaProperties.put(PROPERTY_ENABLE_AUTO_COMMIT, enableAutoCommit); - kafkaProperties.put(PROPERTY_AUTO_COMMIT_TIME, autoCommitTime); - kafkaProperties.put(PROPERTY_SESSION_TIMEOUT, sessionTimeout); - kafkaProperties.put(PROPERTY_KEY_DESERIALIZER, keyDeserializer); - kafkaProperties.put(PROPERTY_VALUE_DESERIALIZER, valueDeserializer); - - return kafkaProperties; - } - - /** - * Gets the bootstrap servers. - * - * @return the bootstrap servers - */ - public String getBootstrapServers() { - return bootstrapServers; - } - - /** - * Gets the acks. - * - * @return the acks - */ - public String getAcks() { - return acks; - } - - /** - * Gets the retries. - * - * @return the retries - */ - public int getRetries() { - return retries; - } - - /** - * Gets the batch size. - * - * @return the batch size - */ - public int getBatchSize() { - return batchSize; - } - - /** - * Gets the linger time. - * - * @return the linger time - */ - public int getLingerTime() { - return lingerTime; - } - - /** - * Gets the buffer memory. - * - * @return the buffer memory - */ - public long getBufferMemory() { - return bufferMemory; - } - - /** - * Gets the group id. - * - * @return the group id - */ - public String getGroupId() { - return groupId; - } - - /** - * Checks if is enable auto commit. - * - * @return true, if checks if is enable auto commit - */ - public boolean isEnableAutoCommit() { - return enableAutoCommit; - } - - /** - * Gets the auto commit time. - * - * @return the auto commit time - */ - public int getAutoCommitTime() { - return autoCommitTime; - } - - /** - * Gets the session timeout. - * - * @return the session timeout - */ - public int getSessionTimeout() { - return sessionTimeout; - } - - /** - * Gets the producer topic. - * - * @return the producer topic - */ - public String getProducerTopic() { - return producerTopic; - } - - /** - * Gets the consumer poll time. - * - * @return the consumer poll time - */ - public long getConsumerPollTime() { - return consumerPollTime; - } - - /** - * Gets the consumer topic list. - * - * @return the consumer topic list - */ - public Collection getConsumerTopicList() { - return Arrays.asList(consumerTopicList); - } - - /** - * Gets the key serializer. - * - * @return the key serializer - */ - public String getKeySerializer() { - return keySerializer; - } - - /** - * Gets the value serializer. - * - * @return the value serializer - */ - public String getValueSerializer() { - return valueSerializer; - } - - /** - * Gets the key deserializer. - * - * @return the key deserializer - */ - public String getKeyDeserializer() { - return keyDeserializer; - } - - /** - * Gets the value deserializer. - * - * @return the value deserializer - */ - public String getValueDeserializer() { - return valueDeserializer; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = super.validate(); - - if (isNullOrBlank(bootstrapServers)) { - result.setResult("bootstrapServers", ValidationStatus.INVALID, - "not specified, must be specified as a string of form host:port"); - } - - if (isNullOrBlank(acks)) { - result.setResult("acks", ValidationStatus.INVALID, - "not specified, must be specified as a string with values [0|1|all]"); - } - - if (retries < 0) { - result.setResult(PROPERTY_RETRIES, ValidationStatus.INVALID, - "[" + retries + "] invalid, must be specified as retries >= 0"); - } - - if (batchSize < 0) { - result.setResult("batchSize", ValidationStatus.INVALID, - "[" + batchSize + "] invalid, must be specified as batchSize >= 0"); - } - - if (lingerTime < 0) { - result.setResult("lingerTime", ValidationStatus.INVALID, - "[" + lingerTime + "] invalid, must be specified as lingerTime >= 0"); - } - - if (bufferMemory < 0) { - result.setResult("bufferMemory", ValidationStatus.INVALID, - "[" + bufferMemory + "] invalid, must be specified as bufferMemory >= 0"); - } - - if (isNullOrBlank(groupId)) { - result.setResult("groupId", ValidationStatus.INVALID, SPECIFY_AS_STRING_MESSAGE); - } - - if (autoCommitTime < 0) { - result.setResult("autoCommitTime", ValidationStatus.INVALID, - "[" + autoCommitTime + "] invalid, must be specified as autoCommitTime >= 0"); - } - - if (sessionTimeout < 0) { - result.setResult("sessionTimeout", ValidationStatus.INVALID, - "[" + sessionTimeout + "] invalid, must be specified as sessionTimeout >= 0"); - } - - if (isNullOrBlank(producerTopic)) { - result.setResult("producerTopic", ValidationStatus.INVALID, - SPECIFY_AS_STRING_MESSAGE); - } - - if (consumerPollTime < 0) { - result.setResult("consumerPollTime", ValidationStatus.INVALID, - "[" + consumerPollTime + "] invalid, must be specified as consumerPollTime >= 0"); - } - - validateConsumerTopicList(result); - - if (isNullOrBlank(keySerializer)) { - result.setResult("keySerializer", ValidationStatus.INVALID, - SPECIFY_AS_STRING_MESSAGE); - } - - if (isNullOrBlank(valueSerializer)) { - result.setResult("valueSerializer", ValidationStatus.INVALID, - SPECIFY_AS_STRING_MESSAGE); - } - - if (isNullOrBlank(keyDeserializer)) { - result.setResult("keyDeserializer", ValidationStatus.INVALID, - SPECIFY_AS_STRING_MESSAGE); - } - - if (isNullOrBlank(valueDeserializer)) { - result.setResult("valueDeserializer", ValidationStatus.INVALID, - SPECIFY_AS_STRING_MESSAGE); - } - - return result; - } - - private void validateConsumerTopicList(final GroupValidationResult result) { - if (consumerTopicList == null || consumerTopicList.length == 0) { - result.setResult("consumerTopicList", ValidationStatus.INVALID, - "not specified, must be specified as a list of strings"); - } - - StringBuilder consumerTopicStringBuilder = new StringBuilder(); - for (final String consumerTopic : consumerTopicList) { - if (consumerTopic == null || consumerTopic.trim().length() == 0) { - consumerTopicStringBuilder.append(consumerTopic + "/"); - } - } - if (consumerTopicStringBuilder.length() > 0) { - result.setResult("consumerTopicList", ValidationStatus.INVALID, - "invalid consumer topic list entries found: /" + consumerTopicStringBuilder.toString()); - } - } - - private boolean isNullOrBlank(final String stringValue) { - return stringValue == null || stringValue.trim().length() == 0; - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java new file mode 100644 index 000000000..9d7cc77f3 --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java @@ -0,0 +1,419 @@ +/*- + * ============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.event.carrier.kafka; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Properties; + +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; + +/** + * Apex parameters for Kafka as an event carrier technology. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameters { + // @formatter:off + /** The label of this carrier technology. */ + public static final String KAFKA_CARRIER_TECHNOLOGY_LABEL = "KAFKA"; + + /** The producer plugin class for the Kafka carrier technology. */ + public static final String KAFKA_EVENT_PRODUCER_PLUGIN_CLASS = ApexKafkaProducer.class.getCanonicalName(); + + /** The consumer plugin class for the Kafka carrier technology. */ + public static final String KAFKA_EVENT_CONSUMER_PLUGIN_CLASS = ApexKafkaConsumer.class.getCanonicalName(); + + // Repeated strings in messages + private static final String SPECIFY_AS_STRING_MESSAGE = "not specified, must be specified as a string"; + + // Default parameter values + private static final String DEFAULT_ACKS = "all"; + private static final String DEFAULT_BOOT_SERVERS = "localhost:9092"; + private static final int DEFAULT_RETRIES = 0; + private static final int DEFAULT_BATCH_SIZE = 16384; + private static final int DEFAULT_LINGER_TIME = 1; + private static final long DEFAULT_BUFFER_MEMORY = 33554432; + private static final String DEFAULT_GROUP_ID = "default-group-id"; + private static final boolean DEFAULT_ENABLE_AUTOCMIT = true; + private static final int DEFAULT_AUTO_COMMIT_TIME = 1000; + private static final int DEFAULT_SESSION_TIMEOUT = 30000; + private static final String DEFAULT_PROD_TOPIC = "apex-out"; + private static final int DEFAULT_CONS_POLL_TIME = 100; + private static final String[] DEFAULT_CONS_TOPICLIST = {"apex-in"}; + private static final String DEFAULT_KEY_SERZER = "org.apache.kafka.common.serialization.StringSerializer"; + private static final String DEFAULT_VAL_SERZER = "org.apache.kafka.common.serialization.StringSerializer"; + private static final String DEFAULT_KEY_DESZER = "org.apache.kafka.common.serialization.StringDeserializer"; + private static final String DEFAULT_VALUE_DESZER = "org.apache.kafka.common.serialization.StringDeserializer"; + + // Parameter property map tokens + private static final String PROPERTY_BOOTSTRAP_SERVERS = "bootstrap.servers"; + private static final String PROPERTY_ACKS = "acks"; + private static final String PROPERTY_RETRIES = "retries"; + private static final String PROPERTY_BATCH_SIZE = "batch.size"; + private static final String PROPERTY_LINGER_TIME = "linger.ms"; + private static final String PROPERTY_BUFFER_MEMORY = "buffer.memory"; + private static final String PROPERTY_GROUP_ID = "group.id"; + private static final String PROPERTY_ENABLE_AUTO_COMMIT = "enable.auto.commit"; + private static final String PROPERTY_AUTO_COMMIT_TIME = "auto.commit.interval.ms"; + private static final String PROPERTY_SESSION_TIMEOUT = "session.timeout.ms"; + private static final String PROPERTY_KEY_SERIALIZER = "key.serializer"; + private static final String PROPERTY_VALUE_SERIALIZER = "value.serializer"; + private static final String PROPERTY_KEY_DESERIALIZER = "key.deserializer"; + private static final String PROPERTY_VALUE_DESERIALIZER = "value.deserializer"; + + // kafka carrier parameters + private String bootstrapServers = DEFAULT_BOOT_SERVERS; + private String acks = DEFAULT_ACKS; + private int retries = DEFAULT_RETRIES; + private int batchSize = DEFAULT_BATCH_SIZE; + private int lingerTime = DEFAULT_LINGER_TIME; + private long bufferMemory = DEFAULT_BUFFER_MEMORY; + private String groupId = DEFAULT_GROUP_ID; + private boolean enableAutoCommit = DEFAULT_ENABLE_AUTOCMIT; + private int autoCommitTime = DEFAULT_AUTO_COMMIT_TIME; + private int sessionTimeout = DEFAULT_SESSION_TIMEOUT; + private String producerTopic = DEFAULT_PROD_TOPIC; + private int consumerPollTime = DEFAULT_CONS_POLL_TIME; + private String[] consumerTopicList = DEFAULT_CONS_TOPICLIST; + private String keySerializer = DEFAULT_KEY_SERZER; + private String valueSerializer = DEFAULT_VAL_SERZER; + private String keyDeserializer = DEFAULT_KEY_DESZER; + private String valueDeserializer = DEFAULT_VALUE_DESZER; + // @formatter:on + + /** + * Constructor to create a kafka carrier technology parameters instance and register the instance with the parameter + * service. + */ + public KafkaCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the kafka carrier technology + this.setLabel(KAFKA_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(KAFKA_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(KAFKA_EVENT_CONSUMER_PLUGIN_CLASS); + } + + /** + * Gets the kafka producer properties. + * + * @return the kafka producer properties + */ + public Properties getKafkaProducerProperties() { + final Properties kafkaProperties = new Properties(); + + kafkaProperties.put(PROPERTY_BOOTSTRAP_SERVERS, bootstrapServers); + kafkaProperties.put(PROPERTY_ACKS, acks); + kafkaProperties.put(PROPERTY_RETRIES, retries); + kafkaProperties.put(PROPERTY_BATCH_SIZE, batchSize); + kafkaProperties.put(PROPERTY_LINGER_TIME, lingerTime); + kafkaProperties.put(PROPERTY_BUFFER_MEMORY, bufferMemory); + kafkaProperties.put(PROPERTY_KEY_SERIALIZER, keySerializer); + kafkaProperties.put(PROPERTY_VALUE_SERIALIZER, valueSerializer); + + return kafkaProperties; + } + + /** + * Gets the kafka consumer properties. + * + * @return the kafka consumer properties + */ + public Properties getKafkaConsumerProperties() { + final Properties kafkaProperties = new Properties(); + + kafkaProperties.put(PROPERTY_BOOTSTRAP_SERVERS, bootstrapServers); + kafkaProperties.put(PROPERTY_GROUP_ID, groupId); + kafkaProperties.put(PROPERTY_ENABLE_AUTO_COMMIT, enableAutoCommit); + kafkaProperties.put(PROPERTY_AUTO_COMMIT_TIME, autoCommitTime); + kafkaProperties.put(PROPERTY_SESSION_TIMEOUT, sessionTimeout); + kafkaProperties.put(PROPERTY_KEY_DESERIALIZER, keyDeserializer); + kafkaProperties.put(PROPERTY_VALUE_DESERIALIZER, valueDeserializer); + + return kafkaProperties; + } + + /** + * Gets the bootstrap servers. + * + * @return the bootstrap servers + */ + public String getBootstrapServers() { + return bootstrapServers; + } + + /** + * Gets the acks. + * + * @return the acks + */ + public String getAcks() { + return acks; + } + + /** + * Gets the retries. + * + * @return the retries + */ + public int getRetries() { + return retries; + } + + /** + * Gets the batch size. + * + * @return the batch size + */ + public int getBatchSize() { + return batchSize; + } + + /** + * Gets the linger time. + * + * @return the linger time + */ + public int getLingerTime() { + return lingerTime; + } + + /** + * Gets the buffer memory. + * + * @return the buffer memory + */ + public long getBufferMemory() { + return bufferMemory; + } + + /** + * Gets the group id. + * + * @return the group id + */ + public String getGroupId() { + return groupId; + } + + /** + * Checks if is enable auto commit. + * + * @return true, if checks if is enable auto commit + */ + public boolean isEnableAutoCommit() { + return enableAutoCommit; + } + + /** + * Gets the auto commit time. + * + * @return the auto commit time + */ + public int getAutoCommitTime() { + return autoCommitTime; + } + + /** + * Gets the session timeout. + * + * @return the session timeout + */ + public int getSessionTimeout() { + return sessionTimeout; + } + + /** + * Gets the producer topic. + * + * @return the producer topic + */ + public String getProducerTopic() { + return producerTopic; + } + + /** + * Gets the consumer poll time. + * + * @return the consumer poll time + */ + public long getConsumerPollTime() { + return consumerPollTime; + } + + /** + * Gets the consumer topic list. + * + * @return the consumer topic list + */ + public Collection getConsumerTopicList() { + return Arrays.asList(consumerTopicList); + } + + /** + * Gets the key serializer. + * + * @return the key serializer + */ + public String getKeySerializer() { + return keySerializer; + } + + /** + * Gets the value serializer. + * + * @return the value serializer + */ + public String getValueSerializer() { + return valueSerializer; + } + + /** + * Gets the key deserializer. + * + * @return the key deserializer + */ + public String getKeyDeserializer() { + return keyDeserializer; + } + + /** + * Gets the value deserializer. + * + * @return the value deserializer + */ + public String getValueDeserializer() { + return valueDeserializer; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); + + if (isNullOrBlank(bootstrapServers)) { + result.setResult("bootstrapServers", ValidationStatus.INVALID, + "not specified, must be specified as a string of form host:port"); + } + + if (isNullOrBlank(acks)) { + result.setResult("acks", ValidationStatus.INVALID, + "not specified, must be specified as a string with values [0|1|all]"); + } + + if (retries < 0) { + result.setResult(PROPERTY_RETRIES, ValidationStatus.INVALID, + "[" + retries + "] invalid, must be specified as retries >= 0"); + } + + if (batchSize < 0) { + result.setResult("batchSize", ValidationStatus.INVALID, + "[" + batchSize + "] invalid, must be specified as batchSize >= 0"); + } + + if (lingerTime < 0) { + result.setResult("lingerTime", ValidationStatus.INVALID, + "[" + lingerTime + "] invalid, must be specified as lingerTime >= 0"); + } + + if (bufferMemory < 0) { + result.setResult("bufferMemory", ValidationStatus.INVALID, + "[" + bufferMemory + "] invalid, must be specified as bufferMemory >= 0"); + } + + if (isNullOrBlank(groupId)) { + result.setResult("groupId", ValidationStatus.INVALID, SPECIFY_AS_STRING_MESSAGE); + } + + if (autoCommitTime < 0) { + result.setResult("autoCommitTime", ValidationStatus.INVALID, + "[" + autoCommitTime + "] invalid, must be specified as autoCommitTime >= 0"); + } + + if (sessionTimeout < 0) { + result.setResult("sessionTimeout", ValidationStatus.INVALID, + "[" + sessionTimeout + "] invalid, must be specified as sessionTimeout >= 0"); + } + + if (isNullOrBlank(producerTopic)) { + result.setResult("producerTopic", ValidationStatus.INVALID, + SPECIFY_AS_STRING_MESSAGE); + } + + if (consumerPollTime < 0) { + result.setResult("consumerPollTime", ValidationStatus.INVALID, + "[" + consumerPollTime + "] invalid, must be specified as consumerPollTime >= 0"); + } + + validateConsumerTopicList(result); + + if (isNullOrBlank(keySerializer)) { + result.setResult("keySerializer", ValidationStatus.INVALID, + SPECIFY_AS_STRING_MESSAGE); + } + + if (isNullOrBlank(valueSerializer)) { + result.setResult("valueSerializer", ValidationStatus.INVALID, + SPECIFY_AS_STRING_MESSAGE); + } + + if (isNullOrBlank(keyDeserializer)) { + result.setResult("keyDeserializer", ValidationStatus.INVALID, + SPECIFY_AS_STRING_MESSAGE); + } + + if (isNullOrBlank(valueDeserializer)) { + result.setResult("valueDeserializer", ValidationStatus.INVALID, + SPECIFY_AS_STRING_MESSAGE); + } + + return result; + } + + private void validateConsumerTopicList(final GroupValidationResult result) { + if (consumerTopicList == null || consumerTopicList.length == 0) { + result.setResult("consumerTopicList", ValidationStatus.INVALID, + "not specified, must be specified as a list of strings"); + } + + StringBuilder consumerTopicStringBuilder = new StringBuilder(); + for (final String consumerTopic : consumerTopicList) { + if (consumerTopic == null || consumerTopic.trim().length() == 0) { + consumerTopicStringBuilder.append(consumerTopic + "/"); + } + } + if (consumerTopicStringBuilder.length() > 0) { + result.setResult("consumerTopicList", ValidationStatus.INVALID, + "invalid consumer topic list entries found: /" + consumerTopicStringBuilder.toString()); + } + } + + private boolean isNullOrBlank(final String stringValue) { + return stringValue == null || stringValue.trim().length() == 0; + } +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumer.java index af5d4d861..13edea8a6 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumer.java @@ -52,7 +52,7 @@ public class ApexRestClientConsumer implements ApexEventConsumer, Runnable { private static final long REST_CLIENT_WAIT_SLEEP_TIME = 50; // The REST parameters read from the parameter service - private RESTClientCarrierTechnologyParameters restConsumerProperties; + private RestClientCarrierTechnologyParameters restConsumerProperties; // The event receiver that will receive events from this consumer private ApexEventReceiver eventReceiver; @@ -77,22 +77,22 @@ public class ApexRestClientConsumer implements ApexEventConsumer, Runnable { this.name = consumerName; // Check and get the REST Properties - if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RESTClientCarrierTechnologyParameters)) { + if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) { final String errorMessage = "specified consumer properties are not applicable to REST client consumer (" + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - restConsumerProperties = (RESTClientCarrierTechnologyParameters) consumerParameters + restConsumerProperties = (RestClientCarrierTechnologyParameters) consumerParameters .getCarrierTechnologyParameters(); // Check if the HTTP method has been set if (restConsumerProperties.getHttpMethod() == null) { - restConsumerProperties.setHttpMethod(RESTClientCarrierTechnologyParameters.CONSUMER_HTTP_METHOD); + restConsumerProperties.setHttpMethod(RestClientCarrierTechnologyParameters.CONSUMER_HTTP_METHOD); } if (!restConsumerProperties.getHttpMethod() - .equalsIgnoreCase(RESTClientCarrierTechnologyParameters.CONSUMER_HTTP_METHOD)) { + .equalsIgnoreCase(RestClientCarrierTechnologyParameters.CONSUMER_HTTP_METHOD)) { final String errorMessage = "specified HTTP method of \"" + restConsumerProperties.getHttpMethod() + "\" is invalid, only HTTP method \"GET\" " + "is supported for event reception on REST client consumer (" + this.name + ")"; @@ -214,17 +214,17 @@ public class ApexRestClientConsumer implements ApexEventConsumer, Runnable { } // Get the event we received - final String eventJSONString = response.readEntity(String.class); + final String eventJsonString = response.readEntity(String.class); // Check there is content - if (eventJSONString == null || eventJSONString.trim().length() == 0) { + if (eventJsonString == null || eventJsonString.trim().length() == 0) { final String errorMessage = "received an empty event from URL \"" + restConsumerProperties.getUrl() + "\""; throw new ApexEventRuntimeException(errorMessage); } // Send the event into Apex - eventReceiver.receiveEvent(eventJSONString); + eventReceiver.receiveEvent(eventJsonString); } catch (final Exception e) { LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e); } diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducer.java index 2765fe9e7..82c3cf331 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducer.java @@ -51,7 +51,7 @@ public class ApexRestClientProducer implements ApexEventProducer { private Client client; // The REST carrier properties - private RESTClientCarrierTechnologyParameters restProducerProperties; + private RestClientCarrierTechnologyParameters restProducerProperties; // The name for this producer private String name = null; @@ -67,29 +67,29 @@ public class ApexRestClientProducer implements ApexEventProducer { */ @Override public void init(final String producerName, final EventHandlerParameters producerParameters) - throws ApexEventException { + throws ApexEventException { this.name = producerName; // Check and get the REST Properties - if (!(producerParameters.getCarrierTechnologyParameters() instanceof RESTClientCarrierTechnologyParameters)) { - final String errorMessage = - "specified consumer properties are not applicable to REST client producer (" + this.name + ")"; + if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) { + final String errorMessage = "specified consumer properties are not applicable to REST client producer (" + + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - restProducerProperties = - (RESTClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + restProducerProperties = (RestClientCarrierTechnologyParameters) producerParameters + .getCarrierTechnologyParameters(); // Check if the HTTP method has been set if (restProducerProperties.getHttpMethod() == null) { - restProducerProperties.setHttpMethod(RESTClientCarrierTechnologyParameters.DEFAULT_PRODUCER_HTTP_METHOD); + restProducerProperties.setHttpMethod(RestClientCarrierTechnologyParameters.DEFAULT_PRODUCER_HTTP_METHOD); } if (!restProducerProperties.getHttpMethod().equalsIgnoreCase("POST") - && !restProducerProperties.getHttpMethod().equalsIgnoreCase("PUT")) { + && !restProducerProperties.getHttpMethod().equalsIgnoreCase("PUT")) { final String errorMessage = "specified HTTP method of \"" + restProducerProperties.getHttpMethod() - + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supproted for event sending on REST client producer (" - + this.name + ")"; + + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supproted " + + "for event sending on REST client producer (" + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } @@ -139,8 +139,8 @@ public class ApexRestClientProducer implements ApexEventProducer { @Override public void sendEvent(final long executionId, final String eventName, final Object event) { // Check if this is a synchronized event, if so we have received a reply - final SynchronousEventCache synchronousEventCache = - (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS); + final SynchronousEventCache synchronousEventCache = (SynchronousEventCache) peerReferenceMap + .get(EventHandlerPeeredMode.SYNCHRONOUS); if (synchronousEventCache != null) { synchronousEventCache.removeCachedEventToApexIfExists(executionId); } @@ -151,15 +151,16 @@ public class ApexRestClientProducer implements ApexEventProducer { // Check that the request worked if (response.getStatus() != Response.Status.OK.getStatusCode()) { final String errorMessage = "send of event to URL \"" + restProducerProperties.getUrl() + "\" using HTTP \"" - + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus() - + " and message \"" + response.readEntity(String.class) + "\", event:\n" + event; + + restProducerProperties.getHttpMethod() + "\" failed with status code " + + response.getStatus() + " and message \"" + response.readEntity(String.class) + + "\", event:\n" + event; LOGGER.warn(errorMessage); throw new ApexEventRuntimeException(errorMessage); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("event sent from engine using {} to URL {} with HTTP {} : {} and response {} ", this.name, - restProducerProperties.getUrl(), restProducerProperties.getHttpMethod(), event, response); + restProducerProperties.getUrl(), restProducerProperties.getHttpMethod(), event, response); } } diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RESTClientCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RESTClientCarrierTechnologyParameters.java deleted file mode 100644 index d260cbeca..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RESTClientCarrierTechnologyParameters.java +++ /dev/null @@ -1,135 +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.event.carrier.restclient; - -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ValidationStatus; - -/** - * Apex parameters for REST as an event carrier technology with Apex as a REST client. - * - *

The parameters for this plugin are: - *

    - *
  1. url: The URL that the Apex Rest client will connect to over REST for event reception or event sending. This - * parameter is mandatory. - *
  2. httpMethod: The HTTP method to use when sending events over REST, legal values are POST (default) and PUT. When - * receiving events, the REST client plugin always uses the HTTP GET method. - *
- * - * @author Joss Armstrong (joss.armstrong@ericsson.com) - */ -public class RESTClientCarrierTechnologyParameters extends CarrierTechnologyParameters { - - /** The label of this carrier technology. */ - public static final String RESTCLIENT_CARRIER_TECHNOLOGY_LABEL = "RESTCLIENT"; - - /** The producer plugin class for the REST carrier technology. */ - public static final String RESTCLIENT_EVENT_PRODUCER_PLUGIN_CLASS = ApexRestClientProducer.class.getCanonicalName(); - - /** The consumer plugin class for the REST carrier technology. */ - public static final String RESTCLIENT_EVENT_CONSUMER_PLUGIN_CLASS = ApexRestClientConsumer.class.getCanonicalName(); - - /** The default HTTP method for output of events. */ - public static final String DEFAULT_PRODUCER_HTTP_METHOD = "POST"; - - /** The HTTP method for input of events. */ - public static final String CONSUMER_HTTP_METHOD = "GET"; - - private String url = null; - private String httpMethod = null; - - /** - * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter - * service. - */ - public RESTClientCarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the web socket carrier technology - this.setLabel(RESTCLIENT_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(RESTCLIENT_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(RESTCLIENT_EVENT_CONSUMER_PLUGIN_CLASS); - - } - - /** - * Gets the URL for the REST request. - * - * @return the URL - */ - public String getUrl() { - return url; - } - - /** - * Sets the URL for the REST request. - * - * @param incomingURL the URL - */ - public void setURL(final String incomingURL) { - this.url = incomingURL; - } - - /** - * Gets the HTTP method to use for the REST request. - * - * @return the HTTP method - */ - public String getHttpMethod() { - return httpMethod; - } - - /** - * Sets the HTTP method to use for the REST request. - * - * @param httpMethod the HTTP method - */ - public void setHttpMethod(final String httpMethod) { - this.httpMethod = httpMethod; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "RESTClientCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + "]"; - } - - /* - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = super.validate(); - - // Check if the URL has been set for event output - if (getUrl() == null) { - result.setResult("url", ValidationStatus.INVALID, "no URL has been set for event sending on REST client"); - } - - return result; - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RestClientCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RestClientCarrierTechnologyParameters.java new file mode 100644 index 000000000..86c8bb4cf --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/main/java/org/onap/policy/apex/plugins/event/carrier/restclient/RestClientCarrierTechnologyParameters.java @@ -0,0 +1,135 @@ +/*- + * ============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.event.carrier.restclient; + +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; + +/** + * Apex parameters for REST as an event carrier technology with Apex as a REST client. + * + *

The parameters for this plugin are: + *

    + *
  1. url: The URL that the Apex Rest client will connect to over REST for event reception or event sending. This + * parameter is mandatory. + *
  2. httpMethod: The HTTP method to use when sending events over REST, legal values are POST (default) and PUT. When + * receiving events, the REST client plugin always uses the HTTP GET method. + *
+ * + * @author Joss Armstrong (joss.armstrong@ericsson.com) + */ +public class RestClientCarrierTechnologyParameters extends CarrierTechnologyParameters { + + /** The label of this carrier technology. */ + public static final String RESTCLIENT_CARRIER_TECHNOLOGY_LABEL = "RESTCLIENT"; + + /** The producer plugin class for the REST carrier technology. */ + public static final String RESTCLIENT_EVENT_PRODUCER_PLUGIN_CLASS = ApexRestClientProducer.class.getCanonicalName(); + + /** The consumer plugin class for the REST carrier technology. */ + public static final String RESTCLIENT_EVENT_CONSUMER_PLUGIN_CLASS = ApexRestClientConsumer.class.getCanonicalName(); + + /** The default HTTP method for output of events. */ + public static final String DEFAULT_PRODUCER_HTTP_METHOD = "POST"; + + /** The HTTP method for input of events. */ + public static final String CONSUMER_HTTP_METHOD = "GET"; + + private String url = null; + private String httpMethod = null; + + /** + * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter + * service. + */ + public RestClientCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the web socket carrier technology + this.setLabel(RESTCLIENT_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(RESTCLIENT_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(RESTCLIENT_EVENT_CONSUMER_PLUGIN_CLASS); + + } + + /** + * Gets the URL for the REST request. + * + * @return the URL + */ + public String getUrl() { + return url; + } + + /** + * Sets the URL for the REST request. + * + * @param incomingUrl the URL + */ + public void setUrl(final String incomingUrl) { + this.url = incomingUrl; + } + + /** + * Gets the HTTP method to use for the REST request. + * + * @return the HTTP method + */ + public String getHttpMethod() { + return httpMethod; + } + + /** + * Sets the HTTP method to use for the REST request. + * + * @param httpMethod the HTTP method + */ + public void setHttpMethod(final String httpMethod) { + this.httpMethod = httpMethod; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "RESTClientCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + "]"; + } + + /* + * + * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); + + // Check if the URL has been set for event output + if (getUrl() == null) { + result.setResult("url", ValidationStatus.INVALID, "no URL has been set for event sending on REST client"); + } + + return result; + } +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequest.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequest.java index 12b9a695c..4b16d30d4 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequest.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequest.java @@ -31,32 +31,67 @@ public class ApexRestRequest { private Object event; private long timestamp; + /** + * Instantiates a new apex rest request. + * + * @param executionId the execution id + * @param eventName the event name + * @param event the event + */ public ApexRestRequest(final long executionId, final String eventName, final Object event) { this.executionId = executionId; this.eventName = eventName; this.event = event; } + /** + * Gets the execution id. + * + * @return the execution id + */ public long getExecutionId() { return executionId; } + /** + * Gets the event name. + * + * @return the event name + */ public String getEventName() { return eventName; } + /** + * Gets the event. + * + * @return the event + */ public Object getEvent() { return event; } + /** + * Gets the timestamp. + * + * @return the timestamp + */ public long getTimestamp() { return timestamp; } + /** + * Sets the timestamp. + * + * @param timestamp the new timestamp + */ public void setTimestamp(final long timestamp) { this.timestamp = timestamp; } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ @Override public String toString() { return "ApexRestRequest [executionId=" + executionId + ", eventName=" + eventName + ", event=" + event diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorConsumer.java index 9998349db..dea839ebb 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorConsumer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorConsumer.java @@ -49,8 +49,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * This class implements an Apex event consumer that issues a REST request and returns the REST - * response to APEX as an event. + * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an + * event. * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -63,10 +63,10 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50; // The REST parameters read from the parameter service - private RESTRequestorCarrierTechnologyParameters restConsumerProperties; + private RestRequestorCarrierTechnologyParameters restConsumerProperties; // The timeout for REST requests - private long restRequestTimeout = RESTRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT; + private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT; // The event receiver that will receive events from this consumer private ApexEventReceiver eventReceiver; @@ -99,25 +99,25 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { @Override public void init(final String consumerName, final EventHandlerParameters consumerParameters, - final ApexEventReceiver incomingEventReceiver) throws ApexEventException { + final ApexEventReceiver incomingEventReceiver) throws ApexEventException { this.eventReceiver = incomingEventReceiver; this.name = consumerName; // Check and get the REST Properties if (!(consumerParameters - .getCarrierTechnologyParameters() instanceof RESTRequestorCarrierTechnologyParameters)) { - final String errorMessage = - "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")"; + .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) { + final String errorMessage = "specified consumer properties are not applicable to REST Requestor consumer (" + + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - restConsumerProperties = - (RESTRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); + restConsumerProperties = (RestRequestorCarrierTechnologyParameters) consumerParameters + .getCarrierTechnologyParameters(); // Check if we are in peered mode if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) { final String errorMessage = "REST Requestor consumer (" + this.name - + ") must run in peered requestor mode with a REST Requestor producer"; + + ") must run in peered requestor mode with a REST Requestor producer"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } @@ -125,7 +125,7 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { // Check if the HTTP method has been set if (restConsumerProperties.getHttpMethod() == null) { restConsumerProperties - .setHttpMethod(RESTRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD); + .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD); } // Check if the HTTP URL has been set @@ -164,8 +164,8 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { try { incomingRestRequestQueue.add(restRequest); } catch (final Exception e) { - final String errorMessage = - "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")"; + final String errorMessage = "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventRuntimeException(errorMessage); } @@ -196,7 +196,7 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { } /** - * Get the number of events received to date + * Get the number of events received to date. * * @return the number of events received */ @@ -238,8 +238,8 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { while (consumerThread.isAlive() && !stopOrderedFlag) { try { // Take the next event from the queue - final ApexRestRequest restRequest = - incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS); + final ApexRestRequest restRequest = incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, + TimeUnit.MILLISECONDS); if (restRequest == null) { // Poll timed out, check for request timeouts timeoutExpiredRequests(); @@ -268,7 +268,7 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { } /** - * This method times out REST requests that have expired + * This method times out REST requests that have expired. */ private void timeoutExpiredRequests() { // Hold a list of timed out requests @@ -284,8 +284,8 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { // Interrupt timed out requests and remove them from the ongoing map for (final ApexRestRequest timedoutRequest : timedoutRequestList) { - final String errorMessage = - "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest; + final String errorMessage = "REST Requestor consumer (" + this.name + "), REST request timed out: " + + timedoutRequest; LOGGER.warn(errorMessage); ongoingRestRequestMap.remove(timedoutRequest); @@ -321,7 +321,7 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { private Thread restRequestThread; /** - * Constructor, initialise the request runner with the request + * Constructor, initialise the request runner with the request. * * @param request the request this runner will issue */ @@ -341,28 +341,29 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { try { // Execute the REST request - final Response response = sendEventAsRESTRequest(); + final Response response = sendEventAsRestRequest(); // Check that the event request worked if (response.getStatus() != Response.Status.OK.getStatusCode()) { final String errorMessage = "reception of response to \"" + request + "\" from URL \"" - + restConsumerProperties.getUrl() + "\" failed with status code " + response.getStatus() - + " and message \"" + response.readEntity(String.class) + "\""; + + restConsumerProperties.getUrl() + "\" failed with status code " + + response.getStatus() + " and message \"" + response.readEntity(String.class) + + "\""; throw new ApexEventRuntimeException(errorMessage); } // Get the event we received - final String eventJSONString = response.readEntity(String.class); + final String eventJsonString = response.readEntity(String.class); // Check there is content - if (eventJSONString == null || eventJSONString.trim().length() == 0) { + if (eventJsonString == null || eventJsonString.trim().length() == 0) { final String errorMessage = "received an enpty response to \"" + request + "\" from URL \"" - + restConsumerProperties.getUrl() + "\""; + + restConsumerProperties.getUrl() + "\""; throw new ApexEventRuntimeException(errorMessage); } // Send the event into Apex - eventReceiver.receiveEvent(request.getExecutionId(), eventJSONString); + eventReceiver.receiveEvent(request.getExecutionId(), eventJsonString); synchronized (eventsReceivedLock) { eventsReceived++; @@ -376,7 +377,7 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { } /** - * Stop the REST request + * Stop the REST request. */ private void stop() { restRequestThread.interrupt(); @@ -387,21 +388,24 @@ public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable { * * @return the response to the REST request */ - public Response sendEventAsRESTRequest() { + public Response sendEventAsRestRequest() { switch (restConsumerProperties.getHttpMethod()) { case GET: return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON).get(); case PUT: return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON) - .put(Entity.json(request.getEvent())); + .put(Entity.json(request.getEvent())); case POST: return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON) - .post(Entity.json(request.getEvent())); + .post(Entity.json(request.getEvent())); case DELETE: return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON).delete(); + + default: + break; } return null; diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorProducer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorProducer.java index 721dfb683..69ad05b27 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorProducer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/ApexRestRequestorProducer.java @@ -44,7 +44,7 @@ public class ApexRestRequestorProducer implements ApexEventProducer { private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorProducer.class); // The REST carrier properties - private RESTRequestorCarrierTechnologyParameters restProducerProperties; + private RestRequestorCarrierTechnologyParameters restProducerProperties; // The name for this producer private String name = null; @@ -68,14 +68,14 @@ public class ApexRestRequestorProducer implements ApexEventProducer { // Check and get the REST Properties if (!(producerParameters - .getCarrierTechnologyParameters() instanceof RESTRequestorCarrierTechnologyParameters)) { + .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) { final String errorMessage = "specified consumer properties are not applicable to REST requestor producer (" + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } restProducerProperties = - (RESTRequestorCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + (RestRequestorCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); // Check if we are in peered mode if (!producerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) { diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RESTRequestorCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RESTRequestorCarrierTechnologyParameters.java deleted file mode 100644 index 65eb731ed..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RESTRequestorCarrierTechnologyParameters.java +++ /dev/null @@ -1,125 +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.event.carrier.restrequestor; - -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; - -/** - * Apex parameters for REST as an event carrier technology with Apex issuing a REST request and receiving a REST - * response. - * - *

The parameters for this plugin are: - *

    - *
  1. url: The URL that the Apex Rest Requestor will connect to over REST for REST request sending. This parameter is - * mandatory. - *
  2. httpMethod: The HTTP method to use when making requests over REST, legal values are GET (default), POST, PUT, and - * DELETE. - *
  3. restRequestTimeout: The time in milliseconds to wait for a REST request to complete. - *
- * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class RESTRequestorCarrierTechnologyParameters extends CarrierTechnologyParameters { - /** The supported HTTP methods. */ - public enum HTTP_METHOD { - GET, PUT, POST, DELETE - } - - /** The label of this carrier technology. */ - public static final String RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL = "RESTREQUESTOR"; - - /** The producer plugin class for the REST carrier technology. */ - public static final String RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS = - ApexRestRequestorProducer.class.getCanonicalName(); - - /** The consumer plugin class for the REST carrier technology. */ - public static final String RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS = - ApexRestRequestorConsumer.class.getCanonicalName(); - - /** The default HTTP method for request events. */ - public static final HTTP_METHOD DEFAULT_REQUESTOR_HTTP_METHOD = HTTP_METHOD.GET; - - /** The default timeout for REST requests. */ - public static final long DEFAULT_REST_REQUEST_TIMEOUT = 500; - - private String url = null; - private HTTP_METHOD httpMethod = null; - - /** - * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter - * service. - */ - public RESTRequestorCarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the web socket carrier technology - this.setLabel(RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS); - } - - /** - * Gets the URL for the REST request. - * - * @return the URL - */ - public String getUrl() { - return url; - } - - /** - * Sets the URL for the REST request. - * - * @param incomingURL the URL - */ - public void setURL(final String incomingURL) { - this.url = incomingURL; - } - - /** - * Gets the HTTP method to use for the REST request. - * - * @return the HTTP method - */ - public HTTP_METHOD getHttpMethod() { - return httpMethod; - } - - /** - * Sets the HTTP method to use for the REST request. - * - * @param httpMethod the HTTP method - */ - public void setHttpMethod(final HTTP_METHOD httpMethod) { - this.httpMethod = httpMethod; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - - @Override - public String toString() { - return "RESTRequestorCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + "]"; - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParameters.java new file mode 100644 index 000000000..acd5e52e8 --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/main/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParameters.java @@ -0,0 +1,125 @@ +/*- + * ============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.event.carrier.restrequestor; + +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; + +/** + * Apex parameters for REST as an event carrier technology with Apex issuing a REST request and receiving a REST + * response. + * + *

The parameters for this plugin are: + *

    + *
  1. url: The URL that the Apex Rest Requestor will connect to over REST for REST request sending. This parameter is + * mandatory. + *
  2. httpMethod: The HTTP method to use when making requests over REST, legal values are GET (default), POST, PUT, and + * DELETE. + *
  3. restRequestTimeout: The time in milliseconds to wait for a REST request to complete. + *
+ * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class RestRequestorCarrierTechnologyParameters extends CarrierTechnologyParameters { + /** The supported HTTP methods. */ + public enum HttpMethod { + GET, PUT, POST, DELETE + } + + /** The label of this carrier technology. */ + public static final String RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL = "RESTREQUESTOR"; + + /** The producer plugin class for the REST carrier technology. */ + public static final String RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS = + ApexRestRequestorProducer.class.getCanonicalName(); + + /** The consumer plugin class for the REST carrier technology. */ + public static final String RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS = + ApexRestRequestorConsumer.class.getCanonicalName(); + + /** The default HTTP method for request events. */ + public static final HttpMethod DEFAULT_REQUESTOR_HTTP_METHOD = HttpMethod.GET; + + /** The default timeout for REST requests. */ + public static final long DEFAULT_REST_REQUEST_TIMEOUT = 500; + + private String url = null; + private HttpMethod httpMethod = null; + + /** + * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter + * service. + */ + public RestRequestorCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the web socket carrier technology + this.setLabel(RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS); + } + + /** + * Gets the URL for the REST request. + * + * @return the URL + */ + public String getUrl() { + return url; + } + + /** + * Sets the URL for the REST request. + * + * @param incomingUrl the URL + */ + public void setUrl(final String incomingUrl) { + this.url = incomingUrl; + } + + /** + * Gets the HTTP method to use for the REST request. + * + * @return the HTTP method + */ + public HttpMethod getHttpMethod() { + return httpMethod; + } + + /** + * Sets the HTTP method to use for the REST request. + * + * @param httpMethod the HTTP method + */ + public void setHttpMethod(final HttpMethod httpMethod) { + this.httpMethod = httpMethod; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + + @Override + public String toString() { + return "RESTRequestorCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + "]"; + } +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRESTRequestor.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRESTRequestor.java deleted file mode 100644 index 3db0f1467..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRESTRequestor.java +++ /dev/null @@ -1,291 +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.restrequestor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.gson.Gson; - -import java.io.ByteArrayOutputStream; -import java.io.File; -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.Before; -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; - -public class TestRESTRequestor { - private static final String BASE_URI = "http://localhost:32801/TestRESTRequestor"; - private static HttpServer server; - - private ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private 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(TestRestRequestorEndpoint.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); - - while (!server.isStarted()) { - ThreadUtilities.sleep(50); - } - } - - @AfterClass - public static void tearDown() throws Exception { - server.shutdownNow(); - - new File("src/test/resources/events/EventsOut.json").delete(); - new File("src/test/resources/events/EventsOutMulti0.json").delete(); - new File("src/test/resources/events/EventsOutMulti1.json").delete(); - } - - @Before - public void resetCounters() { - TestRestRequestorEndpoint.resetCounters(); - } - - @Test - public void testRESTRequestorGet() throws MessagingException, ApexException, IOException { - final Client client = ClientBuilder.newClient(); - - final String[] args = { "src/test/resources/prodcons/File2RESTRequest2FileGet.json" }; - final ApexMain apexMain = new ApexMain(args); - - // Wait for the required amount of events to be received or for 10 seconds - Double getsSoFar = 0.0; - for (int i = 0; i < 40; i++) { - ThreadUtilities.sleep(100); - - final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); - getsSoFar = Double.valueOf(jsonMap.get("GET").toString()); - - if (getsSoFar >= 50.0) { - break; - } - } - - apexMain.shutdown(); - client.close(); - - assertEquals(Double.valueOf(50.0), getsSoFar); - } - - @Test - public void testRESTRequestorPut() throws MessagingException, ApexException, IOException { - final Client client = ClientBuilder.newClient(); - - final String[] args = { "src/test/resources/prodcons/File2RESTRequest2FilePut.json" }; - final ApexMain apexMain = new ApexMain(args); - - // Wait for the required amount of events to be received or for 10 seconds - Double putsSoFar = 0.0; - for (int i = 0; i < 40; i++) { - ThreadUtilities.sleep(100); - - final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); - putsSoFar = Double.valueOf(jsonMap.get("PUT").toString()); - - if (putsSoFar >= 50.0) { - break; - } - } - - apexMain.shutdown(); - client.close(); - - assertEquals(Double.valueOf(50.0), putsSoFar); - } - - @Test - public void testRESTRequestorPost() throws MessagingException, ApexException, IOException { - final Client client = ClientBuilder.newClient(); - - final String[] args = { "src/test/resources/prodcons/File2RESTRequest2FilePost.json" }; - final ApexMain apexMain = new ApexMain(args); - - // Wait for the required amount of events to be received or for 10 seconds - Double postsSoFar = 0.0; - for (int i = 0; i < 40; i++) { - ThreadUtilities.sleep(100); - - final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); - postsSoFar = Double.valueOf(jsonMap.get("POST").toString()); - - if (postsSoFar >= 50.0) { - break; - } - } - - apexMain.shutdown(); - client.close(); - - assertEquals(Double.valueOf(50.0), postsSoFar); - } - - @Test - public void testRESTRequestorDelete() throws MessagingException, ApexException, IOException { - final Client client = ClientBuilder.newClient(); - - final String[] args = { "src/test/resources/prodcons/File2RESTRequest2FileDelete.json" }; - final ApexMain apexMain = new ApexMain(args); - - // Wait for the required amount of events to be received or for 10 seconds - Double deletesSoFar = 0.0; - for (int i = 0; i < 40; i++) { - ThreadUtilities.sleep(100); - - final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); - deletesSoFar = Double.valueOf(jsonMap.get("DELETE").toString()); - - if (deletesSoFar >= 50.0) { - break; - } - } - - apexMain.shutdown(); - client.close(); - - assertEquals(Double.valueOf(50.0), deletesSoFar); - } - - @Test - public void testRESTRequestorMultiInputs() throws MessagingException, ApexException, IOException { - final Client client = ClientBuilder.newClient(); - - final String[] args = { "src/test/resources/prodcons/File2RESTRequest2FileGetMulti.json" }; - final ApexMain apexMain = new ApexMain(args); - - // Wait for the required amount of events to be received or for 10 seconds - Double getsSoFar = 0.0; - for (int i = 0; i < 40; i++) { - ThreadUtilities.sleep(100); - - final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); - getsSoFar = Double.valueOf(jsonMap.get("GET").toString()); - - if (getsSoFar >= 8.0) { - break; - } - } - - apexMain.shutdown(); - client.close(); - - assertEquals(Double.valueOf(8.0), getsSoFar); - - ThreadUtilities.sleep(1000); - } - - @Test - public void testRESTRequestorProducerAlone() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = { "src/test/resources/prodcons/File2RESTRequest2FileGetProducerAlone.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 Requestor producer (RestRequestorProducer) must run in peered requestor mode with a REST Requestor consumer")); - } - - @Test - public void testRESTRequestorConsumerAlone() throws MessagingException, ApexException, IOException { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - - final String[] args = { "src/test/resources/prodcons/File2RESTRequest2FileGetConsumerAlone.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 \"RestRequestorProducer for peered mode REQUESTOR does not exist or is not defined with the same peered mode")); - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestor.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestor.java new file mode 100644 index 000000000..051647339 --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestor.java @@ -0,0 +1,363 @@ +/*- + * ============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.restrequestor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.io.ByteArrayOutputStream; +import java.io.File; +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.Before; +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 TestRestRequestor. + */ +public class TestRestRequestor { + private static final String BASE_URI = "http://localhost:32801/TestRESTRequestor"; + private static HttpServer server; + + private ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private 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(TestRestRequestorEndpoint.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.shutdownNow(); + + new File("src/test/resources/events/EventsOut.json").delete(); + new File("src/test/resources/events/EventsOutMulti0.json").delete(); + new File("src/test/resources/events/EventsOutMulti1.json").delete(); + } + + /** + * Reset counters. + */ + @Before + public void resetCounters() { + TestRestRequestorEndpoint.resetCounters(); + } + + /** + * Test rest requestor get. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestRequestorGet() throws MessagingException, ApexException, IOException { + final Client client = ClientBuilder.newClient(); + + final String[] args = + { "src/test/resources/prodcons/File2RESTRequest2FileGet.json" }; + final ApexMain apexMain = new ApexMain(args); + + // Wait for the required amount of events to be received or for 10 seconds + Double getsSoFar = 0.0; + for (int i = 0; i < 40; i++) { + ThreadUtilities.sleep(100); + + final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); + getsSoFar = Double.valueOf(jsonMap.get("GET").toString()); + + if (getsSoFar >= 50.0) { + break; + } + } + + apexMain.shutdown(); + client.close(); + + assertEquals(Double.valueOf(50.0), getsSoFar); + } + + /** + * Test REST requestor put. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestRequestorPut() throws MessagingException, ApexException, IOException { + final Client client = ClientBuilder.newClient(); + + final String[] args = + { "src/test/resources/prodcons/File2RESTRequest2FilePut.json" }; + final ApexMain apexMain = new ApexMain(args); + + // Wait for the required amount of events to be received or for 10 seconds + Double putsSoFar = 0.0; + for (int i = 0; i < 40; i++) { + ThreadUtilities.sleep(100); + + final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); + putsSoFar = Double.valueOf(jsonMap.get("PUT").toString()); + + if (putsSoFar >= 50.0) { + break; + } + } + + apexMain.shutdown(); + client.close(); + + assertEquals(Double.valueOf(50.0), putsSoFar); + } + + /** + * Test REST requestor post. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestRequestorPost() throws MessagingException, ApexException, IOException { + final Client client = ClientBuilder.newClient(); + + final String[] args = + { "src/test/resources/prodcons/File2RESTRequest2FilePost.json" }; + final ApexMain apexMain = new ApexMain(args); + + // Wait for the required amount of events to be received or for 10 seconds + Double postsSoFar = 0.0; + for (int i = 0; i < 40; i++) { + ThreadUtilities.sleep(100); + + final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); + postsSoFar = Double.valueOf(jsonMap.get("POST").toString()); + + if (postsSoFar >= 50.0) { + break; + } + } + + apexMain.shutdown(); + client.close(); + + assertEquals(Double.valueOf(50.0), postsSoFar); + } + + /** + * Test REST requestor delete. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestRequestorDelete() throws MessagingException, ApexException, IOException { + final Client client = ClientBuilder.newClient(); + + final String[] args = + { "src/test/resources/prodcons/File2RESTRequest2FileDelete.json" }; + final ApexMain apexMain = new ApexMain(args); + + // Wait for the required amount of events to be received or for 10 seconds + Double deletesSoFar = 0.0; + for (int i = 0; i < 40; i++) { + ThreadUtilities.sleep(100); + + final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); + deletesSoFar = Double.valueOf(jsonMap.get("DELETE").toString()); + + if (deletesSoFar >= 50.0) { + break; + } + } + + apexMain.shutdown(); + client.close(); + + assertEquals(Double.valueOf(50.0), deletesSoFar); + } + + /** + * Test REST requestor 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 testRestRequestorMultiInputs() throws MessagingException, ApexException, IOException { + final Client client = ClientBuilder.newClient(); + + final String[] args = + { "src/test/resources/prodcons/File2RESTRequest2FileGetMulti.json" }; + final ApexMain apexMain = new ApexMain(args); + + // Wait for the required amount of events to be received or for 10 seconds + Double getsSoFar = 0.0; + for (int i = 0; i < 40; i++) { + ThreadUtilities.sleep(100); + + final Response response = client.target("http://localhost:32801/TestRESTRequestor/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); + getsSoFar = Double.valueOf(jsonMap.get("GET").toString()); + + if (getsSoFar >= 8.0) { + break; + } + } + + apexMain.shutdown(); + client.close(); + + assertEquals(Double.valueOf(8.0), getsSoFar); + + ThreadUtilities.sleep(1000); + } + + /** + * Test REST requestor producer alone. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestRequestorProducerAlone() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTRequest2FileGetProducerAlone.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 Requestor producer (RestRequestorProducer) " + + "must run in peered requestor mode with a REST Requestor consumer")); + } + + /** + * Test REST requestor consumer alone. + * + * @throws MessagingException the messaging exception + * @throws ApexException the apex exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testRestRequestorConsumerAlone() throws MessagingException, ApexException, IOException { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + + final String[] args = + { "src/test/resources/prodcons/File2RESTRequest2FileGetConsumerAlone.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 \"RestRequestorProducer for peered mode REQUESTOR " + + "does not exist or is not defined with the same peered mode")); + } +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestorEndpoint.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestorEndpoint.java index 4977b3efb..0de34eb9b 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestorEndpoint.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/apps/uservice/test/adapt/restrequestor/TestRestRequestorEndpoint.java @@ -34,6 +34,9 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.Response; +/** + * The Class TestRestRequestorEndpoint. + */ @Path("/apex") public class TestRestRequestorEndpoint { @@ -50,6 +53,9 @@ public class TestRestRequestorEndpoint { + "\"TestMatchCase\": 2,\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; + /** + * Reset counters. + */ public static void resetCounters() { postMessagesReceived = 0; putMessagesReceived = 0; @@ -58,6 +64,11 @@ public class TestRestRequestorEndpoint { deleteMessagesReceived = 0; } + /** + * Service get stats. + * + * @return the response + */ @Path("/event/Stats") @GET public Response serviceGetStats() { @@ -71,6 +82,11 @@ public class TestRestRequestorEndpoint { .build(); } + /** + * Service get event. + * + * @return the response + */ @Path("/event/GetEvent") @GET public Response serviceGetEvent() { @@ -81,18 +97,34 @@ public class TestRestRequestorEndpoint { return Response.status(200).entity(EVENT_STRING).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) { @@ -111,12 +143,24 @@ public class TestRestRequestorEndpoint { return Response.status(200).entity(EVENT_STRING).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) { @@ -135,6 +179,12 @@ public class TestRestRequestorEndpoint { return Response.status(200).entity(EVENT_STRING).build(); } + /** + * Service delete request. + * + * @param jsonString the json string + * @return the response + */ @Path("/event/DeleteEvent") @DELETE public Response serviceDeleteRequest(final String jsonString) { @@ -145,6 +195,12 @@ public class TestRestRequestorEndpoint { return Response.status(200).entity(EVENT_STRING).build(); } + /** + * Service delete request bad response. + * + * @param jsonString the json string + * @return the response + */ @Path("/event/DeleteEventBadResponse") @DELETE public Response serviceDeleteRequestBadResponse(final String jsonString) { diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileDelete.json b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileDelete.json index 6e12c0b1f..46da3970a 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileDelete.json +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileDelete.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -29,7 +29,7 @@ "RestRequestorConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRESTRequestor/apex/event/DeleteEvent", "httpMethod": "DELETE", @@ -49,7 +49,7 @@ "RestRequestorProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGet.json b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGet.json index d0879eb73..3c1d314fe 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGet.json +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGet.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -29,7 +29,7 @@ "RestRequestorConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRESTRequestor/apex/event/GetEvent", "httpMethod": "GET", @@ -49,7 +49,7 @@ "RestRequestorProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetConsumerAlone.json b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetConsumerAlone.json index b957b61de..9ebe89df5 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetConsumerAlone.json +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetConsumerAlone.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -29,7 +29,7 @@ "RestRequestorConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRESTRequestor/apex/event/GetEvent", "httpMethod": "GET", @@ -49,7 +49,7 @@ "RestRequestorProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetMulti.json b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetMulti.json index ba1c997f5..424d2b454 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetMulti.json +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetMulti.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -29,7 +29,7 @@ "RestRequestorConsumer0": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRESTRequestor/apex/event/GetEvent", "httpMethod": "GET", @@ -58,7 +58,7 @@ "RestRequestorConsumer1": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRESTRequestor/apex/event/GetEvent", "httpMethod": "GET", @@ -78,7 +78,7 @@ "RestRequestorProducer0": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" @@ -103,7 +103,7 @@ "RestRequestorProducer1": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetProducerAlone.json b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetProducerAlone.json index a635e6c72..4fcbf59d9 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetProducerAlone.json +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FileGetProducerAlone.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -31,7 +31,7 @@ "RestRequestorProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePost.json b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePost.json index 9db89ce89..fe5af67ee 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePost.json +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePost.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -29,7 +29,7 @@ "RestRequestorConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRESTRequestor/apex/event/PostEvent", "httpMethod": "POST", @@ -49,7 +49,7 @@ "RestRequestorProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePut.json b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePut.json index 3eebe3d8a..e78446447 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePut.json +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/resources/prodcons/File2RESTRequest2FilePut.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -29,7 +29,7 @@ "RestRequestorConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRESTRequestor/apex/event/PutEvent", "httpMethod": "PUT", @@ -49,7 +49,7 @@ "RestRequestorProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTREQUESTOR", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RestRequestorCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerConsumer.java index 8cf0c8f9c..94063af20 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerConsumer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerConsumer.java @@ -56,9 +56,6 @@ public class ApexRestServerConsumer implements ApexEventConsumer, Runnable { // The amount of time to wait in milliseconds between checks that the consumer thread has stopped private static final long REST_SERVER_CONSUMER_WAIT_SLEEP_TIME = 50; - // The REST parameters read from the parameter service - private RESTServerCarrierTechnologyParameters restConsumerProperties; - // The event receiver that will receive events from this consumer private ApexEventReceiver eventReceiver; @@ -84,7 +81,7 @@ public class ApexRestServerConsumer implements ApexEventConsumer, Runnable { * * @return the next candidate value for a Execution ID */ - private static synchronized long getNextExecutionID() { + private static synchronized long getNextExecutionId() { return nextExecutionID.getAndIncrement(); } @@ -102,14 +99,16 @@ public class ApexRestServerConsumer implements ApexEventConsumer, Runnable { this.name = consumerName; // Check and get the REST Properties - if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RESTServerCarrierTechnologyParameters)) { + if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestServerCarrierTechnologyParameters)) { final String errorMessage = "specified consumer properties are not applicable to REST Server consumer (" + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - restConsumerProperties = - (RESTServerCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); + + // The REST parameters read from the parameter service + RestServerCarrierTechnologyParameters restConsumerProperties = + (RestServerCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); // Check if we are in synchronous mode if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) { @@ -131,12 +130,12 @@ public class ApexRestServerConsumer implements ApexEventConsumer, Runnable { } // Compose the URI for the standalone server - final String baseURI = String.format(BASE_URI_TEMPLATE, restConsumerProperties.getHost(), + final String baseUrl = String.format(BASE_URI_TEMPLATE, restConsumerProperties.getHost(), restConsumerProperties.getPort()); // Instantiate the standalone server final ResourceConfig rc = new ResourceConfig(RestServerEndpoint.class, AccessControlFilter.class); - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(baseURI), rc); + server = GrizzlyHttpServerFactory.createHttpServer(URI.create(baseUrl), rc); while (!server.isStarted()) { ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME); @@ -201,10 +200,11 @@ public class ApexRestServerConsumer implements ApexEventConsumer, Runnable { */ public Response receiveEvent(final String event) { // Get an execution ID for the event - final long executionId = getNextExecutionID(); + final long executionId = getNextExecutionId(); if (LOGGER.isDebugEnabled()) { - LOGGER.debug(name + ": sending event " + name + '_' + executionId + " to Apex, event=" + event); + String message = name + ": sending event " + name + '_' + executionId + " to Apex, event=" + event; + LOGGER.debug(message); } try { @@ -222,7 +222,8 @@ public class ApexRestServerConsumer implements ApexEventConsumer, Runnable { // Wait until the event is in the cache of events sent to apex do { ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME); - } while (!synchronousEventCache.existsEventToApex(executionId)); + } + while (!synchronousEventCache.existsEventToApex(executionId)); // Now wait for the reply or for the event to time put do { @@ -238,7 +239,8 @@ public class ApexRestServerConsumer implements ApexEventConsumer, Runnable { // Return the event as a response to the call return Response.status(Response.Status.OK.getStatusCode()).entity(responseEvent.toString()).build(); } - } while (synchronousEventCache.existsEventToApex(executionId)); + } + while (synchronousEventCache.existsEventToApex(executionId)); // The event timed out final String errorMessage = "processing of event on event consumer " + name + " timed out, event=" + event; diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerProducer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerProducer.java index e51482ce4..cacdb3408 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerProducer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/ApexRestServerProducer.java @@ -41,9 +41,6 @@ import org.slf4j.LoggerFactory; public class ApexRestServerProducer implements ApexEventProducer { private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestServerProducer.class); - // The REST carrier properties - private RESTServerCarrierTechnologyParameters restProducerProperties; - // The name for this producer private String name = null; @@ -62,14 +59,16 @@ public class ApexRestServerProducer implements ApexEventProducer { this.name = producerName; // Check and get the REST Properties - if (!(producerParameters.getCarrierTechnologyParameters() instanceof RESTServerCarrierTechnologyParameters)) { + if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestServerCarrierTechnologyParameters)) { final String errorMessage = "specified producer properties are not applicable to REST Server producer (" + this.name + ")"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - restProducerProperties = - (RESTServerCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + + // The REST carrier properties + RestServerCarrierTechnologyParameters restProducerProperties = + (RestServerCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); // Check if host and port are defined if (restProducerProperties.getHost() != null || restProducerProperties.getPort() != -1 @@ -131,7 +130,8 @@ public class ApexRestServerProducer implements ApexEventProducer { @Override public void sendEvent(final long executionId, final String eventName, final Object event) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug(name + ": event " + executionId + ':' + eventName + " recevied from Apex, event=" + event); + String message = name + ": event " + executionId + ':' + eventName + " recevied from Apex, event=" + event; + LOGGER.debug(message); } // If we are not synchronized, then exit @@ -163,5 +163,7 @@ public class ApexRestServerProducer implements ApexEventProducer { * @see org.onap.policy.apex.service.engine.event.ApexEventProducer#stop() */ @Override - public void stop() {} + public void stop() { + // Implementation not required on this class + } } diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RESTServerCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RESTServerCarrierTechnologyParameters.java deleted file mode 100644 index cd7f388f2..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RESTServerCarrierTechnologyParameters.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.plugins.event.carrier.restserver; - -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ValidationStatus; - -/** - * Apex parameters for REST as an event carrier technology with Apex as a REST client. - * - * The parameters for this plugin are: - *
    - *
  1. standalone: A flag indicating if APEX should start a standalone HTTP server to process REST requests (true) or - * whether it should use an underlying servlet infrastructure such as Apache Tomcat (False). This parameter is legal - * only on REST server event inputs. - *
  2. host: The host name to use when setting up a standalone HTTP server. This parameter is legal only on REST server - * event inputs in standalone mode. - *
  3. port: The port to use when setting up a standalone HTTP server. This parameter is legal only on REST server event - * inputs in standalone mode. - *
- * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class RESTServerCarrierTechnologyParameters extends CarrierTechnologyParameters { - // @formatter:off - private static final int MIN_USER_PORT = 1024; - private static final int MAX_USER_PORT = 65535; - - /** The label of this carrier technology. */ - public static final String RESTSERVER_CARRIER_TECHNOLOGY_LABEL = "RESTSERVER"; - - /** The producer plugin class for the REST carrier technology. */ - public static final String RESTSERVER_EVENT_PRODUCER_PLUGIN_CLASS = ApexRestServerProducer.class.getCanonicalName(); - - /** The consumer plugin class for the REST carrier technology. */ - public static final String RESTSERVER_EVENT_CONSUMER_PLUGIN_CLASS = ApexRestServerConsumer.class.getCanonicalName(); - - // REST server parameters - private boolean standalone = false; - private String host = null; - private int port = -1; - // @formatter:on - - /** - * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter - * service. - */ - public RESTServerCarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the web socket carrier technology - this.setLabel(RESTSERVER_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(RESTSERVER_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(RESTSERVER_EVENT_CONSUMER_PLUGIN_CLASS); - } - - /** - * Check if the REST server is running in standalone mode or is using an underlying servlet infrastructure to manage - * requests. - * - * @return true if in standalone mode - */ - public boolean isStandalone() { - return standalone; - } - - /** - * Gets the host. - * - * @return the host - */ - public String getHost() { - return host; - } - - /** - * Gets the port. - * - * @return the port - */ - public int getPort() { - return port; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = super.validate(); - - // Check if host is defined, it is only defined on REST server consumers - if (standalone) { - if (host != null && host.trim().length() == 0) { - result.setResult("host", ValidationStatus.INVALID, - "host not specified, host must be specified as a string"); - } - - // Check if port is defined, it is only defined on REST server consumers - if (port != -1 && port < MIN_USER_PORT || port > MAX_USER_PORT) { - result.setResult("port", ValidationStatus.INVALID, - "[" + port + "] invalid, must be specified as 1024 <= port <= 65535"); - } - } else { - if (host != null) { - result.setResult("host", ValidationStatus.INVALID, "host is specified only in standalone mode"); - } - if (port != -1) { - result.setResult("port", ValidationStatus.INVALID, "port is specified only in standalone mode"); - } - } - - return result; - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerCarrierTechnologyParameters.java new file mode 100644 index 000000000..76ec577b8 --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restserver/src/main/java/org/onap/policy/apex/plugins/event/carrier/restserver/RestServerCarrierTechnologyParameters.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.plugins.event.carrier.restserver; + +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; + +/** + * Apex parameters for REST as an event carrier technology with Apex as a REST client. + * + *

The parameters for this plugin are: + *

    + *
  1. standalone: A flag indicating if APEX should start a standalone HTTP server to process REST requests (true) or + * whether it should use an underlying servlet infrastructure such as Apache Tomcat (False). This parameter is legal + * only on REST server event inputs. + *
  2. host: The host name to use when setting up a standalone HTTP server. This parameter is legal only on REST server + * event inputs in standalone mode. + *
  3. port: The port to use when setting up a standalone HTTP server. This parameter is legal only on REST server event + * inputs in standalone mode. + *
+ * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class RestServerCarrierTechnologyParameters extends CarrierTechnologyParameters { + // @formatter:off + private static final int MIN_USER_PORT = 1024; + private static final int MAX_USER_PORT = 65535; + + /** The label of this carrier technology. */ + public static final String RESTSERVER_CARRIER_TECHNOLOGY_LABEL = "RESTSERVER"; + + /** The producer plugin class for the REST carrier technology. */ + public static final String RESTSERVER_EVENT_PRODUCER_PLUGIN_CLASS = ApexRestServerProducer.class.getCanonicalName(); + + /** The consumer plugin class for the REST carrier technology. */ + public static final String RESTSERVER_EVENT_CONSUMER_PLUGIN_CLASS = ApexRestServerConsumer.class.getCanonicalName(); + + // REST server parameters + private boolean standalone = false; + private String host = null; + private int port = -1; + // @formatter:on + + /** + * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter + * service. + */ + public RestServerCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the web socket carrier technology + this.setLabel(RESTSERVER_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(RESTSERVER_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(RESTSERVER_EVENT_CONSUMER_PLUGIN_CLASS); + } + + /** + * Check if the REST server is running in standalone mode or is using an underlying servlet infrastructure to manage + * requests. + * + * @return true if in standalone mode + */ + public boolean isStandalone() { + return standalone; + } + + /** + * Gets the host. + * + * @return the host + */ + public String getHost() { + return host; + } + + /** + * Gets the port. + * + * @return the port + */ + public int getPort() { + return port; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); + + // Check if host is defined, it is only defined on REST server consumers + if (standalone) { + if (host != null && host.trim().length() == 0) { + result.setResult("host", ValidationStatus.INVALID, + "host not specified, host must be specified as a string"); + } + + // Check if port is defined, it is only defined on REST server consumers + if (port != -1 && port < MIN_USER_PORT || port > MAX_USER_PORT) { + result.setResult("port", ValidationStatus.INVALID, + "[" + port + "] invalid, must be specified as 1024 <= port <= 65535"); + } + } else { + if (host != null) { + result.setResult("host", ValidationStatus.INVALID, "host is specified only in standalone mode"); + } + if (port != -1) { + result.setResult("port", ValidationStatus.INVALID, "port is specified only in standalone mode"); + } + } + + return result; + } +} 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 beee10fd0..f8524fcfd 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 @@ -57,21 +57,21 @@ 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(); + new LinkedHashMap<>(); // The ID of this event input. This gets injected from the URL. @PathParam("eventInput") - private String eventInputID = null; + private String eventInputId = null; /** * Register an Apex consumer with the REST server end point. * - * @param consumerEventInputID The event input ID that indicates this consumer shoud be used + * @param consumerEventInputId The event input ID that indicates this consumer shoud be used * @param consumer The consumer to register */ - public static void registerApexRestServerConsumer(final String consumerEventInputID, + public static void registerApexRestServerConsumer(final String consumerEventInputId, final ApexRestServerConsumer consumer) { - consumerMap.put(consumerEventInputID, consumer); + consumerMap.put(consumerEventInputId, consumer); } /** @@ -102,7 +102,8 @@ public class RestServerEndpoint { postEventMessagesReceived++; if (LOGGER.isDebugEnabled()) { - LOGGER.debug("event input " + eventInputID + ", received POST of event \"" + jsonString + "\""); + String message = "event input " + eventInputId + ", received POST of event \"" + jsonString + "\""; + LOGGER.debug(message); } // Common handler method for POST and PUT requests @@ -121,7 +122,8 @@ public class RestServerEndpoint { putEventMessagesReceived++; if (LOGGER.isDebugEnabled()) { - LOGGER.debug("event input \"" + eventInputID + "\", received PUT of event \"" + jsonString + "\""); + String message = "event input \"" + eventInputId + "\", received PUT of event \"" + jsonString + "\""; + LOGGER.debug(message); } // Common handler method for POST and PUT requests @@ -136,10 +138,10 @@ public class RestServerEndpoint { */ private Response handleEvent(final String jsonString) { // Find the correct consumer for this REST message - final ApexRestServerConsumer eventConsumer = consumerMap.get(eventInputID); + final ApexRestServerConsumer eventConsumer = consumerMap.get(eventInputId); if (eventConsumer == null) { final String errorMessage = - "event input " + eventInputID + " is not defined in the Apex configuration file"; + "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(); diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketConsumer.java index e80efa2ee..fe3e47b82 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketConsumer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketConsumer.java @@ -50,9 +50,6 @@ public class ApexWebSocketConsumer implements ApexEventConsumer, WsStringMessage // Get a reference to the logger private static final Logger LOGGER = LoggerFactory.getLogger(ApexWebSocketConsumer.class); - // The Web Socket properties - private WEBSOCKETCarrierTechnologyParameters webSocketConsumerProperties; - // The web socket messager, may be WS a server or a client private WsStringMessager wsStringMessager; @@ -79,12 +76,14 @@ public class ApexWebSocketConsumer implements ApexEventConsumer, WsStringMessage this.name = consumerName; // Check and get the Kafka Properties - if (!(consumerParameters.getCarrierTechnologyParameters() instanceof WEBSOCKETCarrierTechnologyParameters)) { + if (!(consumerParameters.getCarrierTechnologyParameters() instanceof WebSocketCarrierTechnologyParameters)) { LOGGER.warn("specified consumer properties are not applicable to a web socket consumer"); throw new ApexEventException("specified consumer properties are not applicable to a web socket consumer"); } - webSocketConsumerProperties = - (WEBSOCKETCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); + + // The Web Socket properties + WebSocketCarrierTechnologyParameters webSocketConsumerProperties = + (WebSocketCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); // Check if this is a server or a client Web Socket if (webSocketConsumerProperties.isWsClient()) { diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketProducer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketProducer.java index 6be8a3d1a..7dd1ab947 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketProducer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/ApexWebSocketProducer.java @@ -46,9 +46,6 @@ public class ApexWebSocketProducer implements ApexEventProducer, WsStringMessage // Get a reference to the logger private static final Logger LOGGER = LoggerFactory.getLogger(ApexWebSocketProducer.class); - // The Web Socket properties - private WEBSOCKETCarrierTechnologyParameters webSocketProducerProperties; - // The web socket messager, may be WS a server or a client private WsStringMessager wsStringMessager; @@ -60,23 +57,25 @@ public class ApexWebSocketProducer implements ApexEventProducer, WsStringMessage @Override public void init(final String producerName, final EventHandlerParameters producerParameters) - throws ApexEventException { + throws ApexEventException { this.name = producerName; // Check and get the web socket Properties - if (!(producerParameters.getCarrierTechnologyParameters() instanceof WEBSOCKETCarrierTechnologyParameters)) { - LOGGER.warn( - "specified producer properties for " + this.name + "are not applicable to a web socket producer"); + if (!(producerParameters.getCarrierTechnologyParameters() instanceof WebSocketCarrierTechnologyParameters)) { + String message = "specified producer properties for " + this.name + + "are not applicable to a web socket producer"; + LOGGER.warn(message); throw new ApexEventException("specified producer properties are not applicable to a web socket producer"); } - webSocketProducerProperties = - (WEBSOCKETCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + // The Web Socket properties + WebSocketCarrierTechnologyParameters webSocketProducerProperties = + (WebSocketCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); // Check if this is a server or a client Web Socket if (webSocketProducerProperties.isWsClient()) { // Create a WS client wsStringMessager = new WsStringMessageClient(webSocketProducerProperties.getHost(), - webSocketProducerProperties.getPort()); + webSocketProducerProperties.getPort()); } else { wsStringMessager = new WsStringMessageServer(webSocketProducerProperties.getPort()); } @@ -85,7 +84,8 @@ public class ApexWebSocketProducer implements ApexEventProducer, WsStringMessage try { wsStringMessager.start(this); } catch (final MessagingException e) { - LOGGER.warn("could not start web socket producer (" + this.name + ")"); + String message = "could not start web socket producer (" + this.name + ")"; + LOGGER.warn(message); } } @@ -130,8 +130,8 @@ public class ApexWebSocketProducer implements ApexEventProducer, WsStringMessage @Override public void sendEvent(final long executionId, final String eventName, final Object event) { // Check if this is a synchronized event, if so we have received a reply - final SynchronousEventCache synchronousEventCache = - (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS); + final SynchronousEventCache synchronousEventCache = (SynchronousEventCache) peerReferenceMap + .get(EventHandlerPeeredMode.SYNCHRONOUS); if (synchronousEventCache != null) { synchronousEventCache.removeCachedEventToApexIfExists(executionId); } @@ -160,7 +160,8 @@ public class ApexWebSocketProducer implements ApexEventProducer, WsStringMessage */ @Override public void receiveString(final String messageString) { - LOGGER.warn("received message \"" + messageString + "\" on web socket producer (" + this.name - + ") , no messages should be received on a web socket producer"); + String message = "received message \"" + messageString + "\" on web socket producer (" + this.name + + ") , no messages should be received on a web socket producer"; + LOGGER.warn(message); } } diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WEBSOCKETCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WEBSOCKETCarrierTechnologyParameters.java deleted file mode 100644 index e04a81d1d..000000000 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WEBSOCKETCarrierTechnologyParameters.java +++ /dev/null @@ -1,116 +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.event.carrier.websocket; - -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ValidationStatus; - -/** - * Apex parameters for Kafka as an event carrier technology. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class WEBSOCKETCarrierTechnologyParameters extends CarrierTechnologyParameters { - // @formatter:off - private static final int MIN_USER_PORT = 1024; - private static final int MAX_USER_PORT = 65535; - - /** The label of this carrier technology. */ - public static final String WEB_SCOKET_CARRIER_TECHNOLOGY_LABEL = "WEBSOCKET"; - - /** The producer plugin class for the web socket carrier technology. */ - public static final String WEB_SCOKET_EVENT_PRODUCER_PLUGIN_CLASS = ApexWebSocketProducer.class.getCanonicalName(); - - /** The consumer plugin class for the web socket carrier technology. */ - public static final String KWEB_SCOKET_EVENT_CONSUMER_PLUGIN_CLASS = ApexWebSocketConsumer.class.getCanonicalName(); - - // Default parameter values - private static final String DEFAULT_HOST = "localhost"; - private static final int DEFAULT_PORT = -1; - - // Web socket parameters - private boolean wsClient = true; - private String host = DEFAULT_HOST; - private int port = DEFAULT_PORT; - // @formatter:on - - /** - * Constructor to create a web socket carrier technology parameters instance and register the instance with the - * parameter service. - */ - public WEBSOCKETCarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the web socket carrier technology - this.setLabel(WEB_SCOKET_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(WEB_SCOKET_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(KWEB_SCOKET_EVENT_CONSUMER_PLUGIN_CLASS); - } - - /** - * Gets the host. - * - * @return the host - */ - public String getHost() { - return host; - } - - /** - * Gets the port. - * - * @return the port - */ - public int getPort() { - return port; - } - - /** - * Checks if is ws client. - * - * @return true, if checks if is ws client - */ - public boolean isWsClient() { - return wsClient; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = super.validate(); - - if (wsClient && (host == null || host.trim().length() == 0)) { - result.setResult("host", ValidationStatus.INVALID, "host not specified, must be host as a string"); - } - - if (port < MIN_USER_PORT || port > MAX_USER_PORT) { - result.setResult("port", ValidationStatus.INVALID, - "[" + port + "] invalid, must be specified as 1024 <= port <= 65535"); - } - - return result; - } -} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WebSocketCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WebSocketCarrierTechnologyParameters.java new file mode 100644 index 000000000..9febeb45b --- /dev/null +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-websocket/src/main/java/org/onap/policy/apex/plugins/event/carrier/websocket/WebSocketCarrierTechnologyParameters.java @@ -0,0 +1,116 @@ +/*- + * ============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.event.carrier.websocket; + +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; + +/** + * Apex parameters for Kafka as an event carrier technology. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class WebSocketCarrierTechnologyParameters extends CarrierTechnologyParameters { + // @formatter:off + private static final int MIN_USER_PORT = 1024; + private static final int MAX_USER_PORT = 65535; + + /** The label of this carrier technology. */ + public static final String WEB_SCOKET_CARRIER_TECHNOLOGY_LABEL = "WEBSOCKET"; + + /** The producer plugin class for the web socket carrier technology. */ + public static final String WEB_SCOKET_EVENT_PRODUCER_PLUGIN_CLASS = ApexWebSocketProducer.class.getCanonicalName(); + + /** The consumer plugin class for the web socket carrier technology. */ + public static final String KWEB_SCOKET_EVENT_CONSUMER_PLUGIN_CLASS = ApexWebSocketConsumer.class.getCanonicalName(); + + // Default parameter values + private static final String DEFAULT_HOST = "localhost"; + private static final int DEFAULT_PORT = -1; + + // Web socket parameters + private boolean wsClient = true; + private String host = DEFAULT_HOST; + private int port = DEFAULT_PORT; + // @formatter:on + + /** + * Constructor to create a web socket carrier technology parameters instance and register the instance with the + * parameter service. + */ + public WebSocketCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the web socket carrier technology + this.setLabel(WEB_SCOKET_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(WEB_SCOKET_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(KWEB_SCOKET_EVENT_CONSUMER_PLUGIN_CLASS); + } + + /** + * Gets the host. + * + * @return the host + */ + public String getHost() { + return host; + } + + /** + * Gets the port. + * + * @return the port + */ + public int getPort() { + return port; + } + + /** + * Checks if is ws client. + * + * @return true, if checks if is ws client + */ + public boolean isWsClient() { + return wsClient; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); + + if (wsClient && (host == null || host.trim().length() == 0)) { + result.setResult("host", ValidationStatus.INVALID, "host not specified, must be host as a string"); + } + + if (port < MIN_USER_PORT || port > MAX_USER_PORT) { + result.setResult("port", ValidationStatus.INVALID, + "[" + port + "] invalid, must be specified as 1024 <= port <= 65535"); + } + + return result; + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSObjectEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSObjectEventConverter.java deleted file mode 100644 index 6c21070c2..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSObjectEventConverter.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.plugins.event.protocol.jms; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -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.event.ApexEventProtocolConverter; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class Apex2JMSObjectEventConverter converts {@link ApexEvent} instances into string instances of - * object message events for JMS. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public final class Apex2JMSObjectEventConverter implements ApexEventProtocolConverter { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JMSObjectEventConverter.class); - - // JMS event protocol parameters on the consumer (JMS->Apex) sides - private JMSObjectEventProtocolParameters eventProtocolParameters = null; - - /** - * Constructor to create the Apex to JMS Object converter. - * - * @throws ApexEventException - * the apex event exception - */ - public Apex2JMSObjectEventConverter() throws ApexEventException { - // Nothing specific to initiate for this plugin - } - - @Override - public void init(final EventProtocolParameters parameters) { - // Check if properties have been set for JMS object event conversion as a consumer. They may not be set because - // JMS may not be in use - // on both sides of Apex - if (!(parameters instanceof JMSObjectEventProtocolParameters)) { - final String errormessage = "specified Event Protocol Parameters properties of type \"" - + parameters.getClass().getCanonicalName() + "\" are not applicable to a " - + Apex2JMSObjectEventConverter.class.getName() + " converter"; - LOGGER.error(errormessage); - } else { - this.eventProtocolParameters = (JMSObjectEventProtocolParameters) parameters; - } - - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) - */ - @Override - public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { - // Look for a "getObject()" method on the incoming object, if there is no such method, then we cannot fetch the - // object from JMS - Method getObjectMethod; - try { - getObjectMethod = eventObject.getClass().getMethod("getObject", (Class[]) null); - } catch (Exception e) { - final String errorMessage = "message \"" + eventObject - + "\" received from JMS does not have a \"getObject()\" method"; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - - Object jmsIncomingObject; - try { - jmsIncomingObject = getObjectMethod.invoke(eventObject, (Object[]) null); - } catch (final Exception e) { - final String errorMessage = "object contained in message \"" + eventObject - + "\" received from JMS could not be retrieved as a Java object"; - LOGGER.debug(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - - // Check that the consumer parameters for JMS->Apex messaging have been set - if (eventProtocolParameters == null) { - final String errorMessage = "consumer parameters for JMS events consumed by Apex are not set in the Apex configuration for this engine"; - LOGGER.debug(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - - // Create the Apex event - // @formatter:off - final ApexEvent apexEvent = new ApexEvent( - jmsIncomingObject.getClass().getSimpleName() + eventProtocolParameters.getIncomingEventSuffix(), - eventProtocolParameters.getIncomingEventVersion(), - jmsIncomingObject.toString().getClass().getPackage().getName(), - eventProtocolParameters.getIncomingEventSource(), - eventProtocolParameters.getIncomingEventTarget()); - // @formattter:on - - // Set the data on the apex event as the incoming object - apexEvent.put(jmsIncomingObject.getClass().getSimpleName(), jmsIncomingObject); - - // Return the event in a single element - final ArrayList eventList = new ArrayList<>(); - eventList.add(apexEvent); - return eventList; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy.apex.service.engine.event.ApexEvent) - */ - @Override - public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { - // Check the Apex event - if (apexEvent == null) { - LOGGER.warn("event processing failed, Apex event is null"); - throw new ApexEventException("event processing failed, Apex event is null"); - } - - // Check that the Apex event has a single parameter - if (apexEvent.size() != 1) { - final String errorMessage = "event processing failed, Apex event must have one and only one parameter for JMS Object handling"; - LOGGER.warn(errorMessage); - throw new ApexEventException(errorMessage); - } - - // Return the single object from the Apex event message - return apexEvent.values().iterator().next(); - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSTextEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSTextEventConverter.java deleted file mode 100644 index e845a4a08..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JMSTextEventConverter.java +++ /dev/null @@ -1,102 +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.event.protocol.jms; - -import java.lang.reflect.Method; -import java.util.List; - -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.event.ApexEventRuntimeException; -import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JSONEventConverter; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class Apex2JMSTextEventConverter converts {@link ApexEvent} instances into string instances of - * text message events for JMS. It is a proxy for the built in - * {@link org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JSONEventConverter} plugin. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public final class Apex2JMSTextEventConverter extends Apex2JSONEventConverter { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JMSTextEventConverter.class); - - /** - * Constructor to create the Apex to JMS Object converter. - * - * @throws ApexEventException the apex event exception - */ - public Apex2JMSTextEventConverter() throws ApexEventException {} - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) - */ - @Override - public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { - // Look for a "getText()" method on the incoming object, if there is no such method, then we cannot fetch the - // text from JMS - Method getTextMethod; - try { - getTextMethod = eventObject.getClass().getMethod("getText", (Class[]) null); - } catch (Exception e) { - final String errorMessage = "message \"" + eventObject - + "\" received from JMS does not have a \"getText()\" method"; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - - - String jmsString; - try { - jmsString = (String) getTextMethod.invoke(eventObject, (Object[]) null); - } catch (final Exception e) { - final String errorMessage = "object contained in message \"" + eventObject - + "\" received from JMS could not be retrieved as a Java String"; - LOGGER.debug(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - - // Use the generic JSON plugin from here - return super.toApexEvent(eventName, jmsString); - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy.apex.service.engine. - * event. ApexEvent) - */ - @Override - public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { - // Check the Apex event - if (apexEvent == null) { - LOGGER.warn("event processing failed, Apex event is null"); - throw new ApexEventException("event processing failed, Apex event is null"); - } - - // Return the Apex event as a string object - return super.fromApexEvent(apexEvent); - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsObjectEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsObjectEventConverter.java new file mode 100644 index 000000000..ca02709fe --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsObjectEventConverter.java @@ -0,0 +1,153 @@ +/*- + * ============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.event.protocol.jms; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +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.event.ApexEventProtocolConverter; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class Apex2JMSObjectEventConverter converts {@link ApexEvent} instances into string instances of object message + * events for JMS. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public final class Apex2JmsObjectEventConverter implements ApexEventProtocolConverter { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JmsObjectEventConverter.class); + + // JMS event protocol parameters on the consumer (JMS->Apex) sides + private JmsObjectEventProtocolParameters eventProtocolParameters = null; + + /** + * Constructor to create the Apex to JMS Object converter. + * + * @throws ApexEventException the apex event exception + */ + public Apex2JmsObjectEventConverter() throws ApexEventException { + // Nothing specific to initiate for this plugin + } + + @Override + public void init(final EventProtocolParameters parameters) { + // Check if properties have been set for JMS object event conversion as a consumer. They may not be set because + // JMS may not be in use + // on both sides of Apex + if (!(parameters instanceof JmsObjectEventProtocolParameters)) { + final String errormessage = "specified Event Protocol Parameters properties of type \"" + + parameters.getClass().getCanonicalName() + "\" are not applicable to a " + + Apex2JmsObjectEventConverter.class.getName() + " converter"; + LOGGER.error(errormessage); + } else { + this.eventProtocolParameters = (JmsObjectEventProtocolParameters) parameters; + } + + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) + */ + @Override + public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { + // Look for a "getObject()" method on the incoming object, if there is no such method, then we cannot fetch the + // object from JMS + Method getObjectMethod; + try { + getObjectMethod = eventObject.getClass().getMethod("getObject", (Class[]) null); + } catch (Exception e) { + final String errorMessage = "message \"" + eventObject + + "\" received from JMS does not have a \"getObject()\" method"; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + + Object jmsIncomingObject; + try { + jmsIncomingObject = getObjectMethod.invoke(eventObject, (Object[]) null); + } catch (final Exception e) { + final String errorMessage = "object contained in message \"" + eventObject + + "\" received from JMS could not be retrieved as a Java object"; + LOGGER.debug(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + + // Check that the consumer parameters for JMS->Apex messaging have been set + if (eventProtocolParameters == null) { + final String errorMessage = "consumer parameters for JMS events consumed by " + + "Apex are not set in the Apex configuration for this engine"; + LOGGER.debug(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + + // Create the Apex event + // @formatter:off + final ApexEvent apexEvent = new ApexEvent( + jmsIncomingObject.getClass().getSimpleName() + eventProtocolParameters.getIncomingEventSuffix(), + eventProtocolParameters.getIncomingEventVersion(), + jmsIncomingObject.toString().getClass().getPackage().getName(), + eventProtocolParameters.getIncomingEventSource(), + eventProtocolParameters.getIncomingEventTarget()); + // @formatter:on + + // Set the data on the apex event as the incoming object + apexEvent.put(jmsIncomingObject.getClass().getSimpleName(), jmsIncomingObject); + + // Return the event in a single element + final ArrayList eventList = new ArrayList<>(); + eventList.add(apexEvent); + return eventList; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent + * (org.onap.policy.apex.service.engine.event.ApexEvent) + */ + @Override + public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { + // Check the Apex event + if (apexEvent == null) { + LOGGER.warn("event processing failed, Apex event is null"); + throw new ApexEventException("event processing failed, Apex event is null"); + } + + // Check that the Apex event has a single parameter + if (apexEvent.size() != 1) { + final String errorMessage = "event processing failed, " + + "Apex event must have one and only one parameter for JMS Object handling"; + LOGGER.warn(errorMessage); + throw new ApexEventException(errorMessage); + } + + // Return the single object from the Apex event message + return apexEvent.values().iterator().next(); + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsTextEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsTextEventConverter.java new file mode 100644 index 000000000..1c44dd111 --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/Apex2JmsTextEventConverter.java @@ -0,0 +1,95 @@ +/*- + * ============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.event.protocol.jms; + +import java.lang.reflect.Method; +import java.util.List; + +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.event.ApexEventRuntimeException; +import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JsonEventConverter; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class Apex2JMSTextEventConverter converts {@link ApexEvent} instances into string instances of + * text message events for JMS. It is a proxy for the built in + * {@link org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JsonEventConverter} plugin. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public final class Apex2JmsTextEventConverter extends Apex2JsonEventConverter { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JmsTextEventConverter.class); + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) + */ + @Override + public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { + // Look for a "getText()" method on the incoming object, if there is no such method, then we cannot fetch the + // text from JMS + Method getTextMethod; + try { + getTextMethod = eventObject.getClass().getMethod("getText", (Class[]) null); + } catch (Exception e) { + final String errorMessage = "message \"" + eventObject + + "\" received from JMS does not have a \"getText()\" method"; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + + + String jmsString; + try { + jmsString = (String) getTextMethod.invoke(eventObject, (Object[]) null); + } catch (final Exception e) { + final String errorMessage = "object contained in message \"" + eventObject + + "\" received from JMS could not be retrieved as a Java String"; + LOGGER.debug(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + + // Use the generic JSON plugin from here + return super.toApexEvent(eventName, jmsString); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy.apex.service.engine. + * event. ApexEvent) + */ + @Override + public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { + // Check the Apex event + if (apexEvent == null) { + LOGGER.warn("event processing failed, Apex event is null"); + throw new ApexEventException("event processing failed, Apex event is null"); + } + + // Return the Apex event as a string object + return super.fromApexEvent(apexEvent); + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSObjectEventProtocolParameters.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSObjectEventProtocolParameters.java deleted file mode 100644 index 83aef4e9d..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSObjectEventProtocolParameters.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.plugins.event.protocol.jms; - -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; - -/** - * Event protocol parameters for JMS Object messages as an event protocol. - * - *

- * On reception of an a JMS {@code javax.jms.ObjectMessage}, the JMS Object plugin unmarshals the message as follows: - *

    - *
  1. It extracts the Java object from the {@code javax.jms.ObjectMessage} instance.
  2. - *
  3. It creates an {@link org.onap.policy.apex.service.engine.event.ApexEvent} instance to hold the java object.
  4. - *
  5. It sets the name of the Apex event to be the simple class name of the incoming Java object and appends the value - * of the {@code incomingEventSuffix} parameter to it.
  6. - *
  7. It sets the version of the incoming event to the value of the {@code incomingEventVersion} parameter.
  8. - *
  9. It sets the name space of the incoming event to be the value of the package of the class of the incoming Java - * object.
  10. - *
  11. It sets the source of the incoming event to the value of the {@code incomingEventSource} parameter.
  12. - *
  13. It sets the target of the incoming event to the value of the {@code incomingEventTarget} parameter.
  14. - *
  15. It puts a single entry into the Apex event map with the the simple class name of the incoming Java object being - * the key of the entry and the actual incoming object as the value of the entry.
  16. - *
- *

- * When sending an object to JMS, the plugin expects to receive an Apex event with a single entry. The plugin marshals - * the value of that entry to an object that can be sent by JMS as a {@code javax.jms.ObjectMessage} instance. - *

- * The parameters for this plugin are: - *

    - *
  1. incomingEventSuffix: The suffix to append to the simple name of incoming Java class instances when they are - * encapsulated in Apex events. The parameter defaults to the string value {@code IncomingEvent}.
  2. - *
  3. incomingEventVersion: The event version to use for incoming Java class instances when they are encapsulated in - * Apex events. The parameter defaults to the string value {@code 1.0.0}.
  4. - *
  5. incomingEventSource: The event source to use for incoming Java class instances when they are encapsulated in Apex - * events. The parameter defaults to the string value {@code JMS}.
  6. - *
  7. incomingEventTarget: The event target to use for incoming Java class instances when they are encapsulated in Apex - * events. The parameter defaults to the string value {@code Apex}.
  8. - *
- * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JMSObjectEventProtocolParameters extends EventProtocolParameters { - /** The label of this event protocol. */ - public static final String JMS_OBJECT_EVENT_PROTOCOL_LABEL = "JMSOBJECT"; - - //@formatter:off - // Default parameter values - private static final String DEFAULT_INCOMING_EVENT_SUFFIX = "IncomingEvent"; - private static final String DEFAULT_INCOMING_EVENT_VERSION = "1.0.0"; - private static final String DEFAULT_INCOMING_EVENT_SOURCE = "JMS"; - private static final String DEFAULT_INCOMING_EVENT_TARGET = "Apex"; - - // JMS carrier parameters - private String incomingEventSuffix = DEFAULT_INCOMING_EVENT_SUFFIX; - private String incomingEventVersion = DEFAULT_INCOMING_EVENT_VERSION; - private String incomingEventSource = DEFAULT_INCOMING_EVENT_SOURCE; - private String incomingEventTarget = DEFAULT_INCOMING_EVENT_TARGET; - //@formatter:off - - /** - * Constructor to create a JSON event protocol parameter instance and register the instance with the parameter service. - */ - public JMSObjectEventProtocolParameters() { - super(JMSObjectEventProtocolParameters.class.getCanonicalName()); - - // Set the event protocol properties for the JMS Text event protocol - this.setLabel(JMS_OBJECT_EVENT_PROTOCOL_LABEL); - - // Set the event protocol plugin class - this.setEventProtocolPluginClass(Apex2JMSObjectEventConverter.class.getCanonicalName()); - } - - /** - * Gets the incoming event version. - * - * @return the incoming event version - */ - public String getIncomingEventVersion() { - return incomingEventVersion; - } - - /** - * Gets the incoming event source. - * - * @return the incoming event source - */ - public String getIncomingEventSource() { - return incomingEventSource; - } - - /** - * Gets the incoming event target. - * - * @return the incoming event target - */ - public String getIncomingEventTarget() { - return incomingEventTarget; - } - - /** - * Gets the incoming event suffix. - * - * @return the incoming event suffix - */ - public String getIncomingEventSuffix() { - return incomingEventSuffix; - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSTextEventProtocolParameters.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSTextEventProtocolParameters.java deleted file mode 100644 index b3a9154ff..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JMSTextEventProtocolParameters.java +++ /dev/null @@ -1,56 +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.event.protocol.jms; - -import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters; - -/** - * Event protocol parameters for JMS Text messages as an event protocol. - *

- * Text messages received and sent over JMS in ~Text format are assumed to be in a JSON format that Apex can understand. - * Therefore this plugin is a subclass of the built in JSON event protocol plugin. - *

- * On reception of a JMS {@code javax.jms.TextMessage} message, the JMS Text plugin unmarshals the message the JMS text - * message and passes it to its JSON superclass unmarshaling for processing. - *

- * When sending an Apex event, the plugin uses its underlying JSON superclass to marshal the event to a JSON string and - * passes that string to the JSON carrier plugin for sending. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JMSTextEventProtocolParameters extends JSONEventProtocolParameters { - /** The label of this event protocol. */ - public static final String JMS_TEXT_EVENT_PROTOCOL_LABEL = "JMSTEXT"; - - /** - * Constructor to create a JSON event protocol parameter instance and register the instance with the parameter - * service. - */ - public JMSTextEventProtocolParameters() { - super(JMSTextEventProtocolParameters.class.getCanonicalName(), JMS_TEXT_EVENT_PROTOCOL_LABEL); - - // Set the event protocol properties for the JMS Text event protocol - this.setLabel(JMS_TEXT_EVENT_PROTOCOL_LABEL); - - // Set the event protocol plugin class - this.setEventProtocolPluginClass(Apex2JMSTextEventConverter.class.getCanonicalName()); - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsObjectEventProtocolParameters.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsObjectEventProtocolParameters.java new file mode 100644 index 000000000..3c15a7825 --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsObjectEventProtocolParameters.java @@ -0,0 +1,127 @@ +/*- + * ============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.event.protocol.jms; + +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; + +/** + * Event protocol parameters for JMS Object messages as an event protocol. + * + *

On reception of an a JMS {@code javax.jms.ObjectMessage}, the JMS Object plugin unmarshals the message as follows: + *

    + *
  1. It extracts the Java object from the {@code javax.jms.ObjectMessage} instance.
  2. + *
  3. It creates an {@link org.onap.policy.apex.service.engine.event.ApexEvent} instance to hold the java object.
  4. + *
  5. It sets the name of the Apex event to be the simple class name of the incoming Java object and appends the value + * of the {@code incomingEventSuffix} parameter to it.
  6. + *
  7. It sets the version of the incoming event to the value of the {@code incomingEventVersion} parameter.
  8. + *
  9. It sets the name space of the incoming event to be the value of the package of the class of the incoming Java + * object.
  10. + *
  11. It sets the source of the incoming event to the value of the {@code incomingEventSource} parameter.
  12. + *
  13. It sets the target of the incoming event to the value of the {@code incomingEventTarget} parameter.
  14. + *
  15. It puts a single entry into the Apex event map with the the simple class name of the incoming Java object being + * the key of the entry and the actual incoming object as the value of the entry.
  16. + *
+ * + *

When sending an object to JMS, the plugin expects to receive an Apex event with a single entry. The plugin + * marshals the value of that entry to an object that can be sent by JMS as a {@code javax.jms.ObjectMessage} instance. + * + *

The parameters for this plugin are: + *

    + *
  1. incomingEventSuffix: The suffix to append to the simple name of incoming Java class instances when they are + * encapsulated in Apex events. The parameter defaults to the string value {@code IncomingEvent}.
  2. + *
  3. incomingEventVersion: The event version to use for incoming Java class instances when they are encapsulated in + * Apex events. The parameter defaults to the string value {@code 1.0.0}.
  4. + *
  5. incomingEventSource: The event source to use for incoming Java class instances when they are encapsulated in Apex + * events. The parameter defaults to the string value {@code JMS}.
  6. + *
  7. incomingEventTarget: The event target to use for incoming Java class instances when they are encapsulated in Apex + * events. The parameter defaults to the string value {@code Apex}.
  8. + *
+ * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JmsObjectEventProtocolParameters extends EventProtocolParameters { + /** The label of this event protocol. */ + public static final String JMS_OBJECT_EVENT_PROTOCOL_LABEL = "JMSOBJECT"; + + //@formatter:off + // Default parameter values + private static final String DEFAULT_INCOMING_EVENT_SUFFIX = "IncomingEvent"; + private static final String DEFAULT_INCOMING_EVENT_VERSION = "1.0.0"; + private static final String DEFAULT_INCOMING_EVENT_SOURCE = "JMS"; + private static final String DEFAULT_INCOMING_EVENT_TARGET = "Apex"; + + // JMS carrier parameters + private String incomingEventSuffix = DEFAULT_INCOMING_EVENT_SUFFIX; + private String incomingEventVersion = DEFAULT_INCOMING_EVENT_VERSION; + private String incomingEventSource = DEFAULT_INCOMING_EVENT_SOURCE; + private String incomingEventTarget = DEFAULT_INCOMING_EVENT_TARGET; + //@formatter:off + + /** + * Constructor to create a JSON event protocol parameter instance and register the instance with the + * parameter service. + */ + public JmsObjectEventProtocolParameters() { + super(JmsObjectEventProtocolParameters.class.getCanonicalName()); + + // Set the event protocol properties for the JMS Text event protocol + this.setLabel(JMS_OBJECT_EVENT_PROTOCOL_LABEL); + + // Set the event protocol plugin class + this.setEventProtocolPluginClass(Apex2JmsObjectEventConverter.class.getCanonicalName()); + } + + /** + * Gets the incoming event version. + * + * @return the incoming event version + */ + public String getIncomingEventVersion() { + return incomingEventVersion; + } + + /** + * Gets the incoming event source. + * + * @return the incoming event source + */ + public String getIncomingEventSource() { + return incomingEventSource; + } + + /** + * Gets the incoming event target. + * + * @return the incoming event target + */ + public String getIncomingEventTarget() { + return incomingEventTarget; + } + + /** + * Gets the incoming event suffix. + * + * @return the incoming event suffix + */ + public String getIncomingEventSuffix() { + return incomingEventSuffix; + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsTextEventProtocolParameters.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsTextEventProtocolParameters.java new file mode 100644 index 000000000..67b211a08 --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-jms/src/main/java/org/onap/policy/apex/plugins/event/protocol/jms/JmsTextEventProtocolParameters.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.plugins.event.protocol.jms; + +import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; + +/** + * Event protocol parameters for JMS Text messages as an event protocol. + * + *

Text messages received and sent over JMS in ~Text format are assumed to be in a JSON format that Apex can + * understand. Therefore this plugin is a subclass of the built in JSON event protocol plugin. + * + *

On reception of a JMS {@code javax.jms.TextMessage} message, the JMS Text plugin unmarshals the message the JMS + * text message and passes it to its JSON superclass unmarshaling for processing. + * + *

When sending an Apex event, the plugin uses its underlying JSON superclass to marshal the event to a JSON string + * and passes that string to the JSON carrier plugin for sending. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JmsTextEventProtocolParameters extends JsonEventProtocolParameters { + /** The label of this event protocol. */ + public static final String JMS_TEXT_EVENT_PROTOCOL_LABEL = "JMSTEXT"; + + /** + * Constructor to create a JSON event protocol parameter instance and register the instance with the parameter + * service. + */ + public JmsTextEventProtocolParameters() { + super(JmsTextEventProtocolParameters.class.getCanonicalName(), JMS_TEXT_EVENT_PROTOCOL_LABEL); + + // Set the event protocol properties for the JMS Text event protocol + this.setLabel(JMS_TEXT_EVENT_PROTOCOL_LABEL); + + // Set the event protocol plugin class + this.setEventProtocolPluginClass(Apex2JmsTextEventConverter.class.getCanonicalName()); + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XMLEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XMLEventConverter.java deleted file mode 100644 index 76bae6833..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XMLEventConverter.java +++ /dev/null @@ -1,206 +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.event.protocol.xml; - -import java.io.ByteArrayInputStream; -import java.io.StringWriter; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; - -import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.ObjectFactory; -import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent; -import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData; -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.event.ApexEventProtocolConverter; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; -import org.xml.sax.SAXException; - -/** - * The Class Apex2XMLEventConverter converts {@link ApexEvent} instances into string instances of {@link XMLApexEvent} - * that are XML representations of Apex events defined in JAXB. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public final class Apex2XMLEventConverter implements ApexEventProtocolConverter { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2XMLEventConverter.class); - - private static final String MODEL_SCHEMA_NAME = "xml/apex-event.xsd"; - - // XML Unmarshaller and marshaller and object factory for events - private Unmarshaller unmarshaller; - private Marshaller marshaller; - private ObjectFactory objectFactory = new ObjectFactory(); - - /** - * Constructor to create the Apex to XML converter. - * - * @throws ApexEventException the apex event exception - */ - public Apex2XMLEventConverter() throws ApexEventException { - try { - final URL schemaURL = ResourceUtils.getUrlResource(MODEL_SCHEMA_NAME); - final Schema apexEventSchema = - SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaURL); - - final JAXBContext jaxbContext = JAXBContext.newInstance(XMLApexEvent.class); - - // Set up the unmarshaller to carry out validation - unmarshaller = jaxbContext.createUnmarshaller(); - unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); - unmarshaller.setSchema(apexEventSchema); - - // Set up the marshaller - marshaller = jaxbContext.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - marshaller.setSchema(apexEventSchema); - } catch (JAXBException | SAXException e) { - LOGGER.error("Unable to set up marshalling and unmarshalling for XML events", e); - throw new ApexEventException("Unable to set up marshalling and unmarshalling for XML events", e); - } - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter#init(org.onap.policy.apex.service. - * parameters. eventprotocol.EventProtocolParameters) - */ - @Override - public void init(final EventProtocolParameters parameters) {} - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) - */ - @Override - public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { - // Check the XML event - if (eventObject == null) { - LOGGER.warn("event processing failed, XML event is null"); - throw new ApexEventException("event processing failed, XML event is null"); - } - - // Cast the event to a string, if our conversion is correctly configured, this cast should always work - String xmlEventString = null; - try { - xmlEventString = (String) eventObject; - } catch (final Exception e) { - final String errorMessage = "error converting event \"" + eventObject + "\" to a string"; - LOGGER.debug(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - - // The XML event - XMLApexEvent xmlApexEvent = null; - - // Use JAXB to read and verify the event from the XML string - try { - final StreamSource source = new StreamSource(new ByteArrayInputStream(xmlEventString.getBytes())); - final JAXBElement rootElement = unmarshaller.unmarshal(source, XMLApexEvent.class); - xmlApexEvent = rootElement.getValue(); - } catch (final JAXBException e) { - LOGGER.warn("Unable to unmarshal Apex XML event\n" + xmlEventString, e); - throw new ApexEventException("Unable to unmarshal Apex XML event\n" + xmlEventString, e); - } - - // Create the Apex event - final ApexEvent apexEvent = new ApexEvent(xmlApexEvent.getName(), xmlApexEvent.getVersion(), - xmlApexEvent.getNameSpace(), xmlApexEvent.getSource(), xmlApexEvent.getTarget()); - - // Set the data on the apex event - for (final XMLApexEventData xmlData : xmlApexEvent.getData()) { - apexEvent.put(xmlData.getKey(), xmlData.getValue()); - } - - // Return the event in a single element - final ArrayList eventList = new ArrayList(); - eventList.add(apexEvent); - return eventList; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy.apex.service.engine. - * event. ApexEvent) - */ - @Override - public String fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { - // Check the Apex event - if (apexEvent == null) { - LOGGER.warn("event processing failed, Apex event is null"); - throw new ApexEventException("event processing failed, Apex event is null"); - } - - // Get the Apex event data - final List xmlDataList = new ArrayList(); - - try { - for (final Entry apexDataEntry : apexEvent.entrySet()) { - // Add an XML event data item - if (apexDataEntry.getValue() != null) { - xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), apexDataEntry.getValue().toString())); - } else { - xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), "")); - } - } - } catch (final Exception e) { - LOGGER.warn("Unable to transfer Apex event data to XML\n" + apexEvent, e); - throw new ApexEventException("Unable to transfer Apex event data to XML\n" + apexEvent, e); - } - - // Create the XML event - final XMLApexEvent xmlApexEvent = new XMLApexEvent(apexEvent.getName(), apexEvent.getVersion(), - apexEvent.getNameSpace(), apexEvent.getSource(), apexEvent.getTarget(), xmlDataList); - - // Write the event into a DOM document - try { - // Marshal the event into XML - final StringWriter writer = new StringWriter(); - marshaller.marshal(objectFactory.createXmlApexEvent(xmlApexEvent), writer); - - // Return the event as XML in a string - return writer.toString(); - } catch (final JAXBException e) { - LOGGER.warn("Unable to unmarshal Apex event to XML\n" + apexEvent, e); - throw new ApexEventException("Unable to unmarshal Apex event to XML\n" + apexEvent, e); - } - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XmlEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XmlEventConverter.java new file mode 100644 index 000000000..767c24fdd --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/Apex2XmlEventConverter.java @@ -0,0 +1,208 @@ +/*- + * ============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.event.protocol.xml; + +import java.io.ByteArrayInputStream; +import java.io.StringWriter; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; + +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.ObjectFactory; +import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent; +import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData; +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.event.ApexEventProtocolConverter; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; +import org.xml.sax.SAXException; + +/** + * The Class Apex2XMLEventConverter converts {@link ApexEvent} instances into string instances of {@link XMLApexEvent} + * that are XML representations of Apex events defined in JAXB. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public final class Apex2XmlEventConverter implements ApexEventProtocolConverter { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2XmlEventConverter.class); + + private static final String MODEL_SCHEMA_NAME = "xml/apex-event.xsd"; + + // XML Unmarshaller and marshaller and object factory for events + private Unmarshaller unmarshaller; + private Marshaller marshaller; + private ObjectFactory objectFactory = new ObjectFactory(); + + /** + * Constructor to create the Apex to XML converter. + * + * @throws ApexEventException the apex event exception + */ + public Apex2XmlEventConverter() throws ApexEventException { + try { + final URL schemaUrl = ResourceUtils.getUrlResource(MODEL_SCHEMA_NAME); + final Schema apexEventSchema = + SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaUrl); + + final JAXBContext jaxbContext = JAXBContext.newInstance(XMLApexEvent.class); + + // Set up the unmarshaller to carry out validation + unmarshaller = jaxbContext.createUnmarshaller(); + unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); + unmarshaller.setSchema(apexEventSchema); + + // Set up the marshaller + marshaller = jaxbContext.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + marshaller.setSchema(apexEventSchema); + } catch (JAXBException | SAXException e) { + LOGGER.error("Unable to set up marshalling and unmarshalling for XML events", e); + throw new ApexEventException("Unable to set up marshalling and unmarshalling for XML events", e); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter#init(org.onap.policy.apex.service. + * parameters. eventprotocol.EventProtocolParameters) + */ + @Override + public void init(final EventProtocolParameters parameters) { + // No initialization necessary on this class + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) + */ + @Override + public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { + // Check the XML event + if (eventObject == null) { + LOGGER.warn("event processing failed, XML event is null"); + throw new ApexEventException("event processing failed, XML event is null"); + } + + // Cast the event to a string, if our conversion is correctly configured, this cast should always work + String xmlEventString = null; + try { + xmlEventString = (String) eventObject; + } catch (final Exception e) { + final String errorMessage = "error converting event \"" + eventObject + "\" to a string"; + LOGGER.debug(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + + // The XML event + XMLApexEvent xmlApexEvent = null; + + // Use JAXB to read and verify the event from the XML string + try { + final StreamSource source = new StreamSource(new ByteArrayInputStream(xmlEventString.getBytes())); + final JAXBElement rootElement = unmarshaller.unmarshal(source, XMLApexEvent.class); + xmlApexEvent = rootElement.getValue(); + } catch (final JAXBException e) { + LOGGER.warn("Unable to unmarshal Apex XML event\n" + xmlEventString, e); + throw new ApexEventException("Unable to unmarshal Apex XML event\n" + xmlEventString, e); + } + + // Create the Apex event + final ApexEvent apexEvent = new ApexEvent(xmlApexEvent.getName(), xmlApexEvent.getVersion(), + xmlApexEvent.getNameSpace(), xmlApexEvent.getSource(), xmlApexEvent.getTarget()); + + // Set the data on the apex event + for (final XMLApexEventData xmlData : xmlApexEvent.getData()) { + apexEvent.put(xmlData.getKey(), xmlData.getValue()); + } + + // Return the event in a single element + final ArrayList eventList = new ArrayList<>(); + eventList.add(apexEvent); + return eventList; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy.apex.service.engine. + * event. ApexEvent) + */ + @Override + public String fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { + // Check the Apex event + if (apexEvent == null) { + LOGGER.warn("event processing failed, Apex event is null"); + throw new ApexEventException("event processing failed, Apex event is null"); + } + + // Get the Apex event data + final List xmlDataList = new ArrayList<>(); + + try { + for (final Entry apexDataEntry : apexEvent.entrySet()) { + // Add an XML event data item + if (apexDataEntry.getValue() != null) { + xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), apexDataEntry.getValue().toString())); + } else { + xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), "")); + } + } + } catch (final Exception e) { + LOGGER.warn("Unable to transfer Apex event data to XML\n" + apexEvent, e); + throw new ApexEventException("Unable to transfer Apex event data to XML\n" + apexEvent, e); + } + + // Create the XML event + final XMLApexEvent xmlApexEvent = new XMLApexEvent(apexEvent.getName(), apexEvent.getVersion(), + apexEvent.getNameSpace(), apexEvent.getSource(), apexEvent.getTarget(), xmlDataList); + + // Write the event into a DOM document + try { + // Marshal the event into XML + final StringWriter writer = new StringWriter(); + marshaller.marshal(objectFactory.createXmlApexEvent(xmlApexEvent), writer); + + // Return the event as XML in a string + return writer.toString(); + } catch (final JAXBException e) { + LOGGER.warn("Unable to unmarshal Apex event to XML\n" + apexEvent, e); + throw new ApexEventException("Unable to unmarshal Apex event to XML\n" + apexEvent, e); + } + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventProtocolParameters.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventProtocolParameters.java deleted file mode 100644 index 0eeb497a1..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/main/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventProtocolParameters.java +++ /dev/null @@ -1,53 +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.event.protocol.xml; - -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextTokenDelimitedParameters; - -/** - * Event protocol parameters for XML as an event protocol. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class XMLEventProtocolParameters extends EventProtocolTextTokenDelimitedParameters { - /** The label of this carrier technology. */ - public static final String XML_EVENT_PROTOCOL_LABEL = "XML"; - - // Constants for the text delimiter token - private static final String XML_TEXT_DELIMITER_TOKEN = " event0000DataMap = new HashMap(); - event0000DataMap.put("TestSlogan", "This is a test slogan"); - event0000DataMap.put("TestMatchCase", 12345); - event0000DataMap.put("TestTimestamp", event0000StartTime.getTime()); - event0000DataMap.put("TestTemperature", 34.5445667); - - final ApexEvent apexEvent0000 = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.sample.events", "test", "apex"); - apexEvent0000.putAll(event0000DataMap); - - final String apexEvent0000XMLString = xmlEventConverter.fromApexEvent(apexEvent0000); - - logger.debug(apexEvent0000XMLString); - - assertTrue(apexEvent0000XMLString.contains("Event0000")); - assertTrue(apexEvent0000XMLString.contains("0.0.1")); - assertTrue(apexEvent0000XMLString.contains("This is a test slogan")); - assertTrue(apexEvent0000XMLString.contains("12345")); - assertTrue(apexEvent0000XMLString.contains("" + event0000StartTime.getTime() + "")); - assertTrue(apexEvent0000XMLString.contains("34.5445667")); - - final Date event0004StartTime = new Date(1434363272000L); - final Map event0004DataMap = new HashMap(); - event0004DataMap.put("TestSlogan", "Test slogan for External Event"); - event0004DataMap.put("TestMatchCase", new Integer(2)); - event0004DataMap.put("TestTimestamp", new Long(event0004StartTime.getTime())); - event0004DataMap.put("TestTemperature", new Double(1064.43)); - event0004DataMap.put("TestMatchCaseSelected", new Integer(2)); - event0004DataMap.put("TestMatchStateTime", new Long(1434370506078L)); - event0004DataMap.put("TestEstablishCaseSelected", new Integer(0)); - event0004DataMap.put("TestEstablishStateTime", new Long(1434370506085L)); - event0004DataMap.put("TestDecideCaseSelected", new Integer(3)); - event0004DataMap.put("TestDecideStateTime", new Long(1434370506092L)); - event0004DataMap.put("TestActCaseSelected", new Integer(2)); - event0004DataMap.put("TestActStateTime", new Long(1434370506095L)); - - final ApexEvent apexEvent0004 = - new ApexEvent("Event0004", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - apexEvent0004.putAll(event0004DataMap); - - final String apexEvent0004XMLString = xmlEventConverter.fromApexEvent(apexEvent0004); - - logger.debug(apexEvent0004XMLString); - - assertTrue(apexEvent0004XMLString.contains("Event0004")); - assertTrue(apexEvent0004XMLString.contains("0.0.1")); - assertTrue(apexEvent0004XMLString.contains("Test slogan for External Event")); - assertTrue(apexEvent0004XMLString.contains("1434370506078")); - assertTrue(apexEvent0004XMLString.contains("" + event0004StartTime.getTime() + "")); - assertTrue(apexEvent0004XMLString.contains("1064.43")); - } catch (final Exception e) { - e.printStackTrace(); - throw new ApexException("Exception reading Apex event xml file", e); - } - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXMLTaggedEventConsumer.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXMLTaggedEventConsumer.java deleted file mode 100644 index e02c86a45..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXMLTaggedEventConsumer.java +++ /dev/null @@ -1,336 +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.event.protocol.xml; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.HeaderDelimitedTextBlockReader; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.TextBlock; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestXMLTaggedEventConsumer { - @Test - public void testGarbageTextLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream("hello there".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventGarbageBeforeLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "Garbage1469781869268".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268Rubbish".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268Rubbish".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268Rubbish"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testGarbageTextMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream("hello\nthere".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\n\n".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventGarbageBeforeMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "Garbage\n\n\n1469781869268\n\n\n".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventGarbageBeforeAfterMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "Garbage\n\n\n1469781869268\n\nRubbish\n\n" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventGarbageAfterMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "\n\n1469781869268\n\nRubbish".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testPartialEventsLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "14697818692681469781869268" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268Rubbish\nRefuse" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268RubbishRefuse" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268RubbishRefuse"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testPartialEventsMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "1469781869268\n\n\n\n\n".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventsMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "\n\n1469781869268\n\n\n\n1469781869268\n\n" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n"); - assertFalse(textBlock.isEndOfText()); - - textBlock = xmlTaggedReader.readTextBlock(); - assertEquals(textBlock.getText(), - "\n\n1469781869268\n"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventsGarbageBeforeMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "Garbage\n\n\n1469781869268\n\n\n\n\n1469781869268\n\n" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n"); - assertFalse(textBlock.isEndOfText()); - - textBlock = xmlTaggedReader.readTextBlock(); - assertEquals(textBlock.getText(), - "\n\n1469781869268\n"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventsGarbageBeforeAfterMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "Garbage\n\n\n1469781869268\n\nRubbish\n\n\n1469781869268\n\nRefuse\n" - .getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish"); - assertFalse(textBlock.isEndOfText()); - - textBlock = xmlTaggedReader.readTextBlock(); - assertEquals(textBlock.getText(), - "\n\n1469781869268\n\nRefuse"); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventsGarbageAfterMultiLine() throws IOException { - final InputStream xmlInputStream = new ByteArrayInputStream( - "\n\n1469781869268\n\nRubbish".getBytes()); - - final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish"); - assertTrue(textBlock.isEndOfText()); - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlEventHandler.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlEventHandler.java new file mode 100644 index 000000000..1e42bef30 --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlEventHandler.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.plugins.event.protocol.xml; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class TestApexXMLEventHandlerURL. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestXmlEventHandler { + private static final XLogger logger = XLoggerFactory.getXLogger(TestXmlEventHandler.class); + + /** + * Test XML to apex event. + * + * @throws ApexException on Apex event handling errors + */ + @Test + public void testXmltoApexEvent() throws ApexException { + try { + final Apex2XmlEventConverter xmlEventConverter = new Apex2XmlEventConverter(); + assertNotNull(xmlEventConverter); + + final String apexEventXmlStringIn = XmlEventGenerator.xmlEvent(); + + logger.debug("input event\n" + apexEventXmlStringIn); + + for (final ApexEvent apexEvent : xmlEventConverter.toApexEvent("XMLEventName", apexEventXmlStringIn)) { + assertNotNull(apexEvent); + + logger.debug(apexEvent.toString()); + + assertTrue(apexEvent.getName().equals("Event0000") || apexEvent.getName().equals("Event0100")); + assertTrue(apexEvent.getVersion().equals("0.0.1")); + assertTrue(apexEvent.getNameSpace().equals("org.onap.policy.apex.sample.events")); + assertTrue(apexEvent.getSource().equals("test")); + assertTrue(apexEvent.getTarget().equals("apex")); + assertTrue(apexEvent.get("TestSlogan").toString().startsWith("Test slogan for External Event")); + + final Object testMatchCaseSelected = apexEvent.get("TestMatchCaseSelected"); + assertTrue(testMatchCaseSelected == null); + } + } catch (final Exception e) { + e.printStackTrace(); + throw new ApexException("Exception reading Apex event xml file", e); + } + } + + /** + * Test apex event to xml. + * + * @throws ApexException on Apex event handling errors + */ + @Test + public void testApexEventToXml() throws ApexException { + try { + final Apex2XmlEventConverter xmlEventConverter = new Apex2XmlEventConverter(); + assertNotNull(xmlEventConverter); + + final Date event0000StartTime = new Date(); + final Map event0000DataMap = new HashMap(); + event0000DataMap.put("TestSlogan", "This is a test slogan"); + event0000DataMap.put("TestMatchCase", 12345); + event0000DataMap.put("TestTimestamp", event0000StartTime.getTime()); + event0000DataMap.put("TestTemperature", 34.5445667); + + final ApexEvent apexEvent0000 = + new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.sample.events", "test", "apex"); + apexEvent0000.putAll(event0000DataMap); + + final String apexEvent0000XmlString = xmlEventConverter.fromApexEvent(apexEvent0000); + + logger.debug(apexEvent0000XmlString); + + assertTrue(apexEvent0000XmlString.contains("Event0000")); + assertTrue(apexEvent0000XmlString.contains("0.0.1")); + assertTrue(apexEvent0000XmlString.contains("This is a test slogan")); + assertTrue(apexEvent0000XmlString.contains("12345")); + assertTrue(apexEvent0000XmlString.contains("" + event0000StartTime.getTime() + "")); + assertTrue(apexEvent0000XmlString.contains("34.5445667")); + + final Date event0004StartTime = new Date(1434363272000L); + final Map event0004DataMap = new HashMap(); + event0004DataMap.put("TestSlogan", "Test slogan for External Event"); + event0004DataMap.put("TestMatchCase", new Integer(2)); + event0004DataMap.put("TestTimestamp", new Long(event0004StartTime.getTime())); + event0004DataMap.put("TestTemperature", new Double(1064.43)); + event0004DataMap.put("TestMatchCaseSelected", new Integer(2)); + event0004DataMap.put("TestMatchStateTime", new Long(1434370506078L)); + event0004DataMap.put("TestEstablishCaseSelected", new Integer(0)); + event0004DataMap.put("TestEstablishStateTime", new Long(1434370506085L)); + event0004DataMap.put("TestDecideCaseSelected", new Integer(3)); + event0004DataMap.put("TestDecideStateTime", new Long(1434370506092L)); + event0004DataMap.put("TestActCaseSelected", new Integer(2)); + event0004DataMap.put("TestActStateTime", new Long(1434370506095L)); + + final ApexEvent apexEvent0004 = + new ApexEvent("Event0004", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); + apexEvent0004.putAll(event0004DataMap); + + final String apexEvent0004XmlString = xmlEventConverter.fromApexEvent(apexEvent0004); + + logger.debug(apexEvent0004XmlString); + + assertTrue(apexEvent0004XmlString.contains("Event0004")); + assertTrue(apexEvent0004XmlString.contains("0.0.1")); + assertTrue(apexEvent0004XmlString.contains("Test slogan for External Event")); + assertTrue(apexEvent0004XmlString.contains("1434370506078")); + assertTrue(apexEvent0004XmlString.contains("" + event0004StartTime.getTime() + "")); + assertTrue(apexEvent0004XmlString.contains("1064.43")); + } catch (final Exception e) { + e.printStackTrace(); + throw new ApexException("Exception reading Apex event xml file", e); + } + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlTaggedEventConsumer.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlTaggedEventConsumer.java new file mode 100644 index 000000000..475373a7c --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/TestXmlTaggedEventConsumer.java @@ -0,0 +1,446 @@ +/*- + * ============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.event.protocol.xml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.HeaderDelimitedTextBlockReader; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.TextBlock; + +/** + * The Class TestXmlTaggedEventConsumer. + */ +public class TestXmlTaggedEventConsumer { + + /** + * Test garbage text line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testGarbageTextLine() throws IOException { + final InputStream xmlInputStream = new ByteArrayInputStream("hello there".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268", textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full event garbage before line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventGarbageBeforeLine() throws IOException { + final InputStream xmlInputStream = new ByteArrayInputStream( + "Garbage1469781869268".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268Rubbish" + .getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268Rubbish".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268Rubbish", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test garbage text multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testGarbageTextMultiLine() throws IOException { + final InputStream xmlInputStream = new ByteArrayInputStream("hello\nthere".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\n\n".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full event garbage before multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventGarbageBeforeMultiLine() throws IOException { + final InputStream xmlInputStream = new ByteArrayInputStream( + "Garbage\n\n\n1469781869268\n\n\n" + .getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full event garbage before after multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventGarbageBeforeAfterMultiLine() throws IOException { + String garbageString = "Garbage\n\n\n1469781869268" + + "\n\nRubbish\n\n"; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full event garbage after multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventGarbageAfterMultiLine() throws IOException { + final InputStream xmlInputStream = new ByteArrayInputStream( + "\n\n1469781869268\n\nRubbish" + .getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test partial events line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testPartialEventsLine() throws IOException { + String garbageString = "1469781869268" + + "1469781869268"; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268" + + ""; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268" + + "Rubbish\nRefuse"; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("1469781869268" + + "RubbishRefuse"; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n\n\n".getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n", textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full events multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventsMultiLine() throws IOException { + String garbageString = "\n\n1469781869268\n" + + "\n\n\n1469781869268\n\n"; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n", + textBlock.getText()); + assertFalse(textBlock.isEndOfText()); + + textBlock = xmlTaggedReader.readTextBlock(); + assertEquals("\n\n1469781869268\n", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full events garbage before multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventsGarbageBeforeMultiLine() throws IOException { + String garbageString = "Garbage\n\n\n1469781869268\n" + + "\n\n\n\n1469781869268\n\n"; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n", + textBlock.getText()); + assertFalse(textBlock.isEndOfText()); + + textBlock = xmlTaggedReader.readTextBlock(); + assertEquals("\n\n1469781869268\n", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full events garbage before after multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventsGarbageBeforeAfterMultiLine() throws IOException { + String garbageString = "Garbage\n\n\n1469781869268\n" + + "\nRubbish\n\n\n1469781869268\n" + + "\nRefuse\n"; + final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish", + textBlock.getText()); + assertFalse(textBlock.isEndOfText()); + + textBlock = xmlTaggedReader.readTextBlock(); + assertEquals("\n\n1469781869268\n\nRefuse", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + /** + * Test full events garbage after multi line. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testFullEventsGarbageAfterMultiLine() throws IOException { + final InputStream xmlInputStream = new ByteArrayInputStream( + "\n\n1469781869268\n\nRubbish" + .getBytes()); + + final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("\n\n1469781869268\n\nRubbish", + textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventGenerator.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventGenerator.java deleted file mode 100644 index 765f098de..000000000 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XMLEventGenerator.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.plugins.event.protocol.xml; - -import java.util.Random; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class XMLEventGenerator { - 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 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 void main(final String[] args) { - if (args.length != 1) { - System.err.println("usage EventGenerator #events"); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage EventGenerator #events"); - e.printStackTrace(); - return; - } - - System.out.println(xmlEvents(eventCount)); - } - - public static int getNextEventNo() { - return nextEventNo; - } -} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlEventGenerator.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlEventGenerator.java new file mode 100644 index 000000000..f85d9119e --- /dev/null +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlEventGenerator.java @@ -0,0 +1,125 @@ +/*- + * ============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.event.protocol.xml; + +import java.util.Random; + +/** + * The Class XmlEventGenerator. + */ +public class XmlEventGenerator { + 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(); + } + + /** + * 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(); + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + if (args.length != 1) { + System.err.println("usage EventGenerator #events"); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage EventGenerator #events"); + e.printStackTrace(); + return; + } + + System.out.println(xmlEvents(eventCount)); + } + + /** + * Gets the next event no. + * + * @return the next event no + */ + public static int getNextEventNo() { + return nextEventNo; + } +} diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java index f81c3a914..4bf10e4ae 100644 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java @@ -38,9 +38,8 @@ import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; -import org.yaml.snakeyaml.Yaml; - import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; /** * The Class Apex2YamlEventConverter converts {@link ApexEvent} instances to and from YAML string representations of @@ -104,11 +103,10 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { // If the incoming YAML did not create a map it is a primitive type or a collection so we // convert it into a map for processing Map yamlMap; - if (yamlObject != null && yamlObject instanceof Map) { + if (yamlObject instanceof Map) { // We already have a map so just cast the object yamlMap = (Map) yamlObject; - } - else { + } else { // Create a single entry map, new map creation and assignment is to avoid a // type checking warning LinkedHashMap newYamlMap = new LinkedHashMap<>(); @@ -173,7 +171,7 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { continue; } - yamlMap.put(fieldName, apexEvent.get(fieldName)); + yamlMap.put(fieldName, apexEvent.get(fieldName)); } // Use Snake YAML to convert the APEX event to YAML @@ -187,11 +185,9 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { * @param eventName the name of the event * @param yamlMap the YAML map that holds the event * @return the apex event that we have converted the JSON object into - * @throws ApexEventException - * thrown on unmarshaling exceptions + * @throws ApexEventException thrown on unmarshaling exceptions */ - private ApexEvent yamlMap2ApexEvent(final String eventName, final Map yamlMap) - throws ApexEventException { + private ApexEvent yamlMap2ApexEvent(final String eventName, final Map yamlMap) throws ApexEventException { // Process the mandatory Apex header final ApexEvent apexEvent = processApexEventHeader(eventName, yamlMap); @@ -236,16 +232,10 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { * @throws ApexEventRuntimeException the apex event runtime exception * @throws ApexEventException on invalid events with missing header fields */ - private ApexEvent processApexEventHeader(final String eventName, final Map yamlMap) + private ApexEvent processApexEventHeader(final String eventName, final Map yamlMap) throws ApexEventException { - // Get the event header fields - // @formatter:off - String name = getYamlStringField(yamlMap, ApexEvent.NAME_HEADER_FIELD, yamlPars.getNameAlias(), ApexEvent.NAME_REGEXP, false); - String version = getYamlStringField(yamlMap, ApexEvent.VERSION_HEADER_FIELD, yamlPars.getVersionAlias(), ApexEvent.VERSION_REGEXP, false); - String namespace = getYamlStringField(yamlMap, ApexEvent.NAMESPACE_HEADER_FIELD, yamlPars.getNameSpaceAlias(), ApexEvent.NAMESPACE_REGEXP, false); - String source = getYamlStringField(yamlMap, ApexEvent.SOURCE_HEADER_FIELD, yamlPars.getSourceAlias(), ApexEvent.SOURCE_REGEXP, false); - String target = getYamlStringField(yamlMap, ApexEvent.TARGET_HEADER_FIELD, yamlPars.getTargetAlias(), ApexEvent.TARGET_REGEXP, false); - // @formatter:on + String name = getYamlStringField(yamlMap, ApexEvent.NAME_HEADER_FIELD, yamlPars.getNameAlias(), + ApexEvent.NAME_REGEXP, false); // Check that an event name has been specified if (name == null && eventName == null) { @@ -256,14 +246,16 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { // Check if an event name was specified on the event parameters if (eventName != null) { if (name != null && !eventName.equals(name)) { - LOGGER.warn("The incoming event name \"{}\" does not match the configured event name \"{}\", using configured event name", - name, eventName); + LOGGER.warn("The incoming event name \"{}\" does not match the configured event name \"{}\", " + + "using configured event name", name, eventName); } name = eventName; } // Now, find the event definition in the model service. If version is null, the newest event // definition in the model service is used + String version = getYamlStringField(yamlMap, ApexEvent.VERSION_HEADER_FIELD, yamlPars.getVersionAlias(), + ApexEvent.VERSION_REGEXP, false); final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(name, version); if (eventDefinition == null) { throw new ApexEventRuntimeException("an event definition for an event named \"" + name @@ -276,6 +268,8 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { } // Check the name space is OK if it is defined, if not, use the name space from the model + String namespace = getYamlStringField(yamlMap, ApexEvent.NAMESPACE_HEADER_FIELD, yamlPars.getNameSpaceAlias(), + ApexEvent.NAMESPACE_REGEXP, false); if (namespace != null) { if (!namespace.equals(eventDefinition.getNameSpace())) { throw new ApexEventRuntimeException("namespace \"" + namespace + "\" on event \"" + name @@ -287,11 +281,15 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { } // For source, use the defined source only if the source is not found on the incoming event + String source = getYamlStringField(yamlMap, ApexEvent.SOURCE_HEADER_FIELD, yamlPars.getSourceAlias(), + ApexEvent.SOURCE_REGEXP, false); if (source == null) { source = eventDefinition.getSource(); } // For target, use the defined source only if the source is not found on the incoming event + String target = getYamlStringField(yamlMap, ApexEvent.TARGET_HEADER_FIELD, yamlPars.getTargetAlias(), + ApexEvent.TARGET_REGEXP, false); if (target == null) { target = eventDefinition.getTarget(); } @@ -302,22 +300,16 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { /** * This method gets an event string field from a JSON object. * - * @param yamlMap - * the YAML containing the YAML representation of the incoming event - * @param fieldName - * the field name to find in the event - * @param fieldAlias - * the alias for the field to find in the event, overrides the field name if it is not null - * @param fieldRE - * the regular expression to check the field against for validity - * @param mandatory - * true if the field is mandatory + * @param yamlMap the YAML containing the YAML representation of the incoming event + * @param fieldName the field name to find in the event + * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null + * @param fieldRegexp the regular expression to check the field against for validity + * @param mandatory true if the field is mandatory * @return the value of the field in the JSON object or null if the field is optional - * @throws ApexEventRuntimeException - * the apex event runtime exception + * @throws ApexEventRuntimeException the apex event runtime exception */ private String getYamlStringField(final Map yamlMap, final String fieldName, final String fieldAlias, - final String fieldRE, final boolean mandatory) { + final String fieldRegexp, final boolean mandatory) { // Get the YAML field for the string field final Object yamlField = getYamlField(yamlMap, fieldName, fieldAlias, mandatory); @@ -335,12 +327,12 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { final String fieldValueString = (String) yamlField; // Is regular expression checking required - if (fieldRE == null) { + if (fieldRegexp == null) { return fieldValueString; } // Check the event field against its regular expression - if (!fieldValueString.matches(fieldRE)) { + if (!fieldValueString.matches(fieldRegexp)) { throw new ApexEventRuntimeException( "field \"" + fieldName + "\" with value \"" + fieldValueString + "\" is invalid"); } @@ -351,17 +343,12 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { /** * This method gets an event field from a YAML object. * - * @param yamlMap - * the YAML containing the YAML representation of the incoming event - * @param fieldName - * the field name to find in the event - * @param fieldAlias - * the alias for the field to find in the event, overrides the field name if it is not null - * @param mandatory - * true if the field is mandatory + * @param yamlMap the YAML containing the YAML representation of the incoming event + * @param fieldName the field name to find in the event + * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null + * @param mandatory true if the field is mandatory * @return the value of the field in the YAML object or null if the field is optional - * @throws ApexEventRuntimeException - * the apex event runtime exception + * @throws ApexEventRuntimeException the apex event runtime exception */ private Object getYamlField(final Map yamlMap, final String fieldName, final String fieldAlias, final boolean mandatory) { diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlEventProtocolParameters.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlEventProtocolParameters.java index 861e9cd8f..09a7f54aa 100644 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlEventProtocolParameters.java +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlEventProtocolParameters.java @@ -25,7 +25,7 @@ import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextTo /** * Event protocol parameters for YAML as an event protocol. * - * The parameters for this plugin are: + *

The parameters for this plugin are: *

    *
  1. nameAlias: The field in a YAML event to use as an alias for the event name. This parameter is * optional. diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlEventProtocol.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlEventProtocol.java index c5f6cb781..1d2a1d9f7 100644 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlEventProtocol.java +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlEventProtocol.java @@ -49,7 +49,16 @@ import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.TextBlock; import org.onap.policy.common.parameters.ParameterService; +/** + * The Class TestYamlEventProtocol. + */ public class TestYamlEventProtocol { + + /** + * Register test events and schemas. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @BeforeClass public static void registerTestEventsAndSchemas() throws IOException { SchemaParameters schemaParameters = new SchemaParameters(); @@ -62,20 +71,20 @@ public class TestYamlEventProtocol { "java.lang.Integer"); schemas.getSchemasMap().put(simpleIntSchema.getKey(), simpleIntSchema); - AxContextSchema simpleDoubleSchema = new AxContextSchema(new AxArtifactKey("SimpleDoubleSchema", "0.0.1"), "JAVA", - "java.lang.Double"); + AxContextSchema simpleDoubleSchema = new AxContextSchema(new AxArtifactKey("SimpleDoubleSchema", "0.0.1"), + "JAVA", "java.lang.Double"); schemas.getSchemasMap().put(simpleDoubleSchema.getKey(), simpleDoubleSchema); - AxContextSchema simpleStringSchema = new AxContextSchema(new AxArtifactKey("SimpleStringSchema", "0.0.1"), "JAVA", - "java.lang.String"); + AxContextSchema simpleStringSchema = new AxContextSchema(new AxArtifactKey("SimpleStringSchema", "0.0.1"), + "JAVA", "java.lang.String"); schemas.getSchemasMap().put(simpleStringSchema.getKey(), simpleStringSchema); AxContextSchema arrayListSchema = new AxContextSchema(new AxArtifactKey("ArrayListSchema", "0.0.1"), "JAVA", "java.util.ArrayList"); schemas.getSchemasMap().put(arrayListSchema.getKey(), arrayListSchema); - AxContextSchema linkedHashMapSchema = new AxContextSchema(new AxArtifactKey("LinkedHashMapSchema", "0.0.1"), "JAVA", - "java.util.LinkedHashMap"); + AxContextSchema linkedHashMapSchema = new AxContextSchema(new AxArtifactKey("LinkedHashMapSchema", "0.0.1"), + "JAVA", "java.util.LinkedHashMap"); schemas.getSchemasMap().put(linkedHashMapSchema.getKey(), linkedHashMapSchema); ModelService.registerModel(AxContextSchemas.class, schemas); @@ -105,11 +114,9 @@ public class TestYamlEventProtocol { AxEvent testEvent3 = new AxEvent(new AxArtifactKey("TestEvent3", "0.0.1")); testEvent3.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml"); - AxField te3Field0 = new AxField(new AxReferenceKey(testEvent3.getKey(), "american"), - arrayListSchema.getKey()); + AxField te3Field0 = new AxField(new AxReferenceKey(testEvent3.getKey(), "american"), arrayListSchema.getKey()); testEvent3.getParameterMap().put("american", te3Field0); - AxField te3Field1 = new AxField(new AxReferenceKey(testEvent3.getKey(), "national"), - arrayListSchema.getKey()); + AxField te3Field1 = new AxField(new AxReferenceKey(testEvent3.getKey(), "national"), arrayListSchema.getKey()); testEvent3.getParameterMap().put("national", te3Field1); events.getEventMap().put(testEvent3.getKey(), testEvent3); @@ -139,24 +146,19 @@ public class TestYamlEventProtocol { AxEvent testEvent7 = new AxEvent(new AxArtifactKey("TestEvent7", "0.0.1")); testEvent7.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml"); - AxField te7Field0 = new AxField(new AxReferenceKey(testEvent7.getKey(), "time"), - simpleIntSchema.getKey()); + AxField te7Field0 = new AxField(new AxReferenceKey(testEvent7.getKey(), "time"), simpleIntSchema.getKey()); testEvent7.getParameterMap().put("time", te7Field0); - AxField te7Field1 = new AxField(new AxReferenceKey(testEvent7.getKey(), "player"), - simpleStringSchema.getKey()); + AxField te7Field1 = new AxField(new AxReferenceKey(testEvent7.getKey(), "player"), simpleStringSchema.getKey()); testEvent7.getParameterMap().put("player", te7Field1); - AxField te7Field2 = new AxField(new AxReferenceKey(testEvent7.getKey(), "action"), - simpleStringSchema.getKey()); + AxField te7Field2 = new AxField(new AxReferenceKey(testEvent7.getKey(), "action"), simpleStringSchema.getKey()); testEvent7.getParameterMap().put("action", te7Field2); events.getEventMap().put(testEvent7.getKey(), testEvent7); AxEvent testEvent8 = new AxEvent(new AxArtifactKey("TestEvent8", "0.0.1")); testEvent8.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml"); - AxField te8Field0 = new AxField(new AxReferenceKey(testEvent8.getKey(), "hr"), - arrayListSchema.getKey()); + AxField te8Field0 = new AxField(new AxReferenceKey(testEvent8.getKey(), "hr"), arrayListSchema.getKey()); testEvent8.getParameterMap().put("hr", te8Field0); - AxField te8Field1 = new AxField(new AxReferenceKey(testEvent8.getKey(), "rbi"), - arrayListSchema.getKey()); + AxField te8Field1 = new AxField(new AxReferenceKey(testEvent8.getKey(), "rbi"), arrayListSchema.getKey()); testEvent8.getParameterMap().put("rbi", te8Field1); events.getEventMap().put(testEvent8.getKey(), testEvent8); @@ -196,12 +198,21 @@ public class TestYamlEventProtocol { ModelService.registerModel(AxEvents.class, events); } + /** + * Unregister test events and schemas. + */ @AfterClass public static void unregisterTestEventsAndSchemas() { ModelService.clear(); ParameterService.clear(); } + /** + * Test yaml processing. + * + * @throws ApexEventException the apex event exception + * @throws IOException Signals that an I/O exception has occurred. + */ @Test public void testYamlProcessing() throws ApexEventException, IOException { try { @@ -227,8 +238,18 @@ public class TestYamlEventProtocol { testYamlDecodeEncode("TestEvent11", 1, 4, "TOSCA0"); } - private void testYamlDecodeEncode(final String eventName, final int eventCount, final int parCount, final String fileName) - throws ApexEventException, IOException { + /** + * Test yaml decode encode. + * + * @param eventName the event name + * @param eventCount the event count + * @param parCount the par count + * @param fileName the file name + * @throws ApexEventException the apex event exception + * @throws IOException Signals that an I/O exception has occurred. + */ + private void testYamlDecodeEncode(final String eventName, final int eventCount, final int parCount, + final String fileName) throws ApexEventException, IOException { YamlEventProtocolParameters parameters = new YamlEventProtocolParameters(); parameters.setDelimiterAtStart(false); @@ -239,16 +260,17 @@ public class TestYamlEventProtocol { FileInputStream fileInputStream = new FileInputStream(new File(filePath)); HeaderDelimitedTextBlockReader reader = new HeaderDelimitedTextBlockReader(parameters); reader.init(fileInputStream); - + List eventList = new ArrayList<>(); - + TextBlock textBlock; do { - textBlock = reader.readTextBlock(); - - eventList.addAll(converter.toApexEvent(eventName, textBlock.getText())); - } while (!textBlock.isEndOfText()); - + textBlock = reader.readTextBlock(); + + eventList.addAll(converter.toApexEvent(eventName, textBlock.getText())); + } + while (!textBlock.isEndOfText()); + fileInputStream.close(); assertEquals(eventCount, eventList.size()); @@ -257,7 +279,8 @@ public class TestYamlEventProtocol { assertEquals(parCount, eventList.get(0).size()); String eventYaml = (String) converter.fromApexEvent(eventList.get(eventNo)); - String expectedYaml = TextFileUtils.getTextFileAsString("src/test/resources/yaml_out/" + fileName + '_' + eventNo + ".yaml"); + String expectedYaml = TextFileUtils + .getTextFileAsString("src/test/resources/yaml_out/" + fileName + '_' + eventNo + ".yaml"); assertEquals(expectedYaml.replaceAll("\\s*", ""), eventYaml.replaceAll("\\s*", "")); } } diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlPluginStability.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlPluginStability.java index 57b4b72d6..d033de56d 100644 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlPluginStability.java +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/TestYamlPluginStability.java @@ -17,6 +17,7 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ + package org.onap.policy.apex.plugins.event.protocol.yaml; import static org.junit.Assert.assertEquals; @@ -44,9 +45,17 @@ import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; import org.onap.policy.common.parameters.ParameterService; +/** + * The Class TestYamlPluginStability. + */ public class TestYamlPluginStability { static AxEvent testEvent; + /** + * Register test events and schemas. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @BeforeClass public static void registerTestEventsAndSchemas() throws IOException { SchemaParameters schemaParameters = new SchemaParameters(); @@ -69,8 +78,6 @@ public class TestYamlPluginStability { ModelService.registerModel(AxContextSchemas.class, schemas); - AxEvents events = new AxEvents(); - testEvent = new AxEvent(new AxArtifactKey("TestEvent", "0.0.1")); testEvent.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml"); AxField teField0 = new AxField(new AxReferenceKey(testEvent.getKey(), "intValue"), simpleIntSchema.getKey()); @@ -81,17 +88,27 @@ public class TestYamlPluginStability { AxField teField2 = new AxField(new AxReferenceKey(testEvent.getKey(), "stringValue"), simpleStringSchema.getKey(), true); testEvent.getParameterMap().put("stringValue", teField2); + + AxEvents events = new AxEvents(); events.getEventMap().put(testEvent.getKey(), testEvent); ModelService.registerModel(AxEvents.class, events); } + /** + * Unregister test events and schemas. + */ @AfterClass public static void unregisterTestEventsAndSchemas() { ModelService.clear(); ParameterService.clear(); } + /** + * Test stability. + * + * @throws ApexEventException the apex event exception + */ @Test public void testStability() throws ApexEventException { Apex2YamlEventConverter converter = new Apex2YamlEventConverter(); @@ -220,7 +237,8 @@ public class TestYamlPluginStability { e.getMessage().substring(0, 77)); } - yamlInputString = "doubleValue: 123.45\n" + "intValue: 123\n" + "stringValue: org.onap.policy.apex.plugins.event.protocol.yaml"; + yamlInputString = "doubleValue: 123.45\n" + "intValue: 123\n" + + "stringValue: org.onap.policy.apex.plugins.event.protocol.yaml"; eventList = converter.toApexEvent("TestEvent", yamlInputString); assertEquals("org.onap.policy.apex.plugins.event.protocol.yaml", eventList.get(0).getNameSpace()); @@ -249,7 +267,7 @@ public class TestYamlPluginStability { } pars.setTargetAlias(null); - yamlInputString = "doubleValue: 123.45\n" + "intValue: ~\n"+ "stringValue: MyString"; + yamlInputString = "doubleValue: 123.45\n" + "intValue: ~\n" + "stringValue: MyString"; try { converter.toApexEvent("TestEvent", yamlInputString); fail("this test should throw an exception"); diff --git a/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaStateFinalizerExecutor.java b/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaStateFinalizerExecutor.java index 4fff29092..8577d18fb 100644 --- a/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaStateFinalizerExecutor.java +++ b/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaStateFinalizerExecutor.java @@ -65,17 +65,17 @@ public class JavaStateFinalizerExecutor extends StateFinalizerExecutor { /** * Executes the executor for the state finalizer logic in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields for finalisation * @return The state output for the state * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public String execute(final long executionID, final Map incomingFields) + public String execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Check and execute the Java logic boolean returnValue = false; @@ -84,7 +84,7 @@ public class JavaStateFinalizerExecutor extends StateFinalizerExecutor { // StateFinalizerExecutionContext executor) throws ApexException" // to invoke the // task logic in the Java class - final Method method = stateFinalizerLogicObject.getClass().getDeclaredMethod("getStateOutput", + final Method method = stateFinalizerLogicObject.getClass().getDeclaredMethod("getStateOutput", (Class[]) new Class[] { StateFinalizerExecutionContext.class }); returnValue = (boolean) method.invoke(stateFinalizerLogicObject, getExecutionContext()); } catch (final Exception e) { diff --git a/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskExecutor.java b/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskExecutor.java index 753f08b7e..829434dc3 100644 --- a/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskExecutor.java +++ b/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskExecutor.java @@ -66,17 +66,17 @@ public class JavaTaskExecutor extends TaskExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields * @return The outgoing fields * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public Map execute(final long executionID, final Map incomingFields) + public Map execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Check and execute the Java logic boolean returnValue = false; @@ -84,7 +84,7 @@ public class JavaTaskExecutor extends TaskExecutor { // Find and call the method with the signature "public boolean getEvent(final TaskExecutionContext executor) // throws ApexException" to invoke the // task logic in the Java class - final Method method = taskLogicObject.getClass().getDeclaredMethod("getEvent", + final Method method = taskLogicObject.getClass().getDeclaredMethod("getEvent", (Class[]) new Class[] { TaskExecutionContext.class }); returnValue = (boolean) method.invoke(taskLogicObject, getExecutionContext()); } catch (final Exception e) { diff --git a/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskSelectExecutor.java b/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskSelectExecutor.java index a42ff2cfa..e642972af 100644 --- a/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskSelectExecutor.java +++ b/plugins/plugins-executor/plugins-executor-java/src/main/java/org/onap/policy/apex/plugins/executor/java/JavaTaskSelectExecutor.java @@ -66,17 +66,17 @@ public class JavaTaskSelectExecutor extends TaskSelectExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingEvent the incoming event * @return The outgoing event * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public AxArtifactKey execute(final long executionID, final EnEvent incomingEvent) + public AxArtifactKey execute(final long executionId, final EnEvent incomingEvent) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingEvent); + executePre(executionId, incomingEvent); // Check and execute the Java logic boolean returnValue = false; @@ -84,7 +84,7 @@ public class JavaTaskSelectExecutor extends TaskSelectExecutor { // Find and call the method with the signature "public boolean getTask(final TaskSelectionExecutionContext // executor)" to invoke the task selection // logic in the Java class - final Method method = taskSelectionLogicObject.getClass().getDeclaredMethod("getTask", + final Method method = taskSelectionLogicObject.getClass().getDeclaredMethod("getTask", (Class[]) new Class[] { TaskSelectionExecutionContext.class }); returnValue = (boolean) method.invoke(taskSelectionLogicObject, getExecutionContext()); } catch (final Exception e) { diff --git a/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptStateFinalizerExecutor.java b/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptStateFinalizerExecutor.java index 7b91c5975..bc3062d13 100644 --- a/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptStateFinalizerExecutor.java +++ b/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptStateFinalizerExecutor.java @@ -70,17 +70,17 @@ public class JavascriptStateFinalizerExecutor extends StateFinalizerExecutor { /** * Executes the executor for the state finalizer logic in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields for finalisation * @return The state output for the state * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public String execute(final long executionID, final Map incomingFields) + public String execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Set up the Javascript engine engine.put("executor", getExecutionContext()); diff --git a/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutor.java b/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutor.java index 38be929c0..14e4ba384 100644 --- a/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutor.java +++ b/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutor.java @@ -69,17 +69,17 @@ public class JavascriptTaskExecutor extends TaskExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields * @return The outgoing fields * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public Map execute(final long executionID, final Map incomingFields) + public Map execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Set up the Javascript engine engine.put("executor", getExecutionContext()); diff --git a/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskSelectExecutor.java b/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskSelectExecutor.java index 570b33b2a..adeb73f88 100644 --- a/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskSelectExecutor.java +++ b/plugins/plugins-executor/plugins-executor-javascript/src/main/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskSelectExecutor.java @@ -44,6 +44,10 @@ public class JavascriptTaskSelectExecutor extends TaskSelectExecutor { // Logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavascriptTaskSelectExecutor.class); + // Recurring string constants + private static final String TSL_FAILED_PREFIX = + "execute: task selection logic failed to set a return value for state \""; + // Javascript engine private ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); private CompiledScript compiled = null; @@ -61,9 +65,9 @@ public class JavascriptTaskSelectExecutor extends TaskSelectExecutor { compiled = ((Compilable) engine).compile(getSubject().getTaskSelectionLogic().getLogic()); } catch (final ScriptException e) { LOGGER.error("execute: task selection logic failed to compile for state \"" + getSubject().getKey().getId() - + "\""); - throw new StateMachineException( - "task selection logic failed to compile for state \"" + getSubject().getKey().getId() + "\"", e); + + "\""); + throw new StateMachineException("task selection logic failed to compile for state \"" + + getSubject().getKey().getId() + "\"", e); } } @@ -71,17 +75,17 @@ public class JavascriptTaskSelectExecutor extends TaskSelectExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingEvent the incoming event * @return The outgoing event * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public AxArtifactKey execute(final long executionID, final EnEvent incomingEvent) - throws StateMachineException, ContextException { + public AxArtifactKey execute(final long executionId, final EnEvent incomingEvent) + throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingEvent); + executePre(executionId, incomingEvent); // Set up the Javascript engine engine.put("executor", getExecutionContext()); @@ -95,27 +99,24 @@ public class JavascriptTaskSelectExecutor extends TaskSelectExecutor { compiled.eval(engine.getContext()); } } catch (final ScriptException e) { - LOGGER.error( - "execute: task selection logic failed to run for state \"" + getSubject().getKey().getId() + "\""); + LOGGER.error("execute: task selection logic failed to run for state \"" + getSubject().getKey().getId() + + "\""); throw new StateMachineException( - "task selection logic failed to run for state \"" + getSubject().getKey().getId() + "\"", e); + "task selection logic failed to run for state \"" + getSubject().getKey().getId() + "\"", + e); } try { final Object ret = engine.get("returnValue"); if (ret == null) { - LOGGER.error("execute: task selection logic failed to set a return value for state \"" - + getSubject().getKey().getId() + "\""); - throw new StateMachineException( - "execute: task selection logic failed to set a return value for state \"" - + getSubject().getKey().getId() + "\""); + LOGGER.error(TSL_FAILED_PREFIX + getSubject().getKey().getId() + "\""); + throw new StateMachineException(TSL_FAILED_PREFIX + getSubject().getKey().getId() + "\""); } returnValue = (Boolean) ret; } catch (NullPointerException | ClassCastException e) { LOGGER.error("execute: task selection logic failed to set a correct return value for state \"" - + getSubject().getKey().getId() + "\"", e); - throw new StateMachineException("execute: task selection logic failed to set a return value for state \"" - + getSubject().getKey().getId() + "\"", e); + + getSubject().getKey().getId() + "\"", e); + throw new StateMachineException(TSL_FAILED_PREFIX + getSubject().getKey().getId() + "\"", e); } // Do the execution post work @@ -137,8 +138,8 @@ public class JavascriptTaskSelectExecutor extends TaskSelectExecutor { @Override public void cleanUp() throws StateMachineException { LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + "," - + getSubject().getTaskSelectionLogic().getLogicFlavour() + "," - + getSubject().getTaskSelectionLogic().getLogic()); + + getSubject().getTaskSelectionLogic().getLogicFlavour() + "," + + getSubject().getTaskSelectionLogic().getLogic()); engine = null; } } diff --git a/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyStateFinalizerExecutor.java b/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyStateFinalizerExecutor.java index f8f66e5d2..9e9024401 100644 --- a/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyStateFinalizerExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyStateFinalizerExecutor.java @@ -70,17 +70,17 @@ public class JrubyStateFinalizerExecutor extends StateFinalizerExecutor { /** * Executes the executor for the state finalizer logic in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields for finalisation * @return The state output for the state * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public String execute(final long executionID, final Map incomingFields) + public String execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Check and execute the JRuby logic container.put("executor", getExecutionContext()); diff --git a/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskExecutor.java b/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskExecutor.java index 56b28d02e..d49423486 100644 --- a/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskExecutor.java @@ -70,17 +70,17 @@ public class JrubyTaskExecutor extends TaskExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields * @return The outgoing fields * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public Map execute(final long executionID, final Map incomingFields) + public Map execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Check and execute the JRuby logic container.put("executor", getExecutionContext()); diff --git a/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskSelectExecutor.java b/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskSelectExecutor.java index 8405f4e60..b3ce7e0fd 100644 --- a/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskSelectExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jruby/src/main/java/org/onap/policy/apex/plugins/executor/jruby/JrubyTaskSelectExecutor.java @@ -71,17 +71,17 @@ public class JrubyTaskSelectExecutor extends TaskSelectExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingEvent the incoming event * @return The outgoing event * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public AxArtifactKey execute(final long executionID, final EnEvent incomingEvent) + public AxArtifactKey execute(final long executionId, final EnEvent incomingEvent) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingEvent); + executePre(executionId, incomingEvent); // Check and execute the JRuby logic container.put("executor", getExecutionContext()); diff --git a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonStateFinalizerExecutor.java b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonStateFinalizerExecutor.java index ea8f027c5..ecd9f7ae1 100644 --- a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonStateFinalizerExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonStateFinalizerExecutor.java @@ -75,20 +75,20 @@ public class JythonStateFinalizerExecutor extends StateFinalizerExecutor { /** * Executes the executor for the state finalizer logic in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields for finalisation * @return The state output for the state * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public String execute(final long executionID, final Map incomingFields) + public String execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { boolean returnValue = false; // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); try { diff --git a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java index e1c0f096a..39ca0dc43 100644 --- a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java @@ -77,20 +77,20 @@ public class JythonTaskExecutor extends TaskExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields * @return The outgoing fields * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public Map execute(final long executionID, final Map incomingFields) + public Map execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { boolean returnValue = false; // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); try { diff --git a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java index 4f4d38a19..3ff061fa4 100644 --- a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java @@ -43,6 +43,10 @@ import org.slf4j.ext.XLoggerFactory; public class JythonTaskSelectExecutor extends TaskSelectExecutor { private static final XLogger LOGGER = XLoggerFactory.getXLogger(JythonTaskSelectExecutor.class); + // Recurring string constants + private static final String TSL_FAILED_PREFIX = + "execute: task selection logic failed to set a return value for state \""; + // The Jython interpreter private final PythonInterpreter interpreter = new PythonInterpreter(); private PyCode compiled = null; @@ -77,20 +81,20 @@ public class JythonTaskSelectExecutor extends TaskSelectExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingEvent the incoming event * @return The outgoing event * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public AxArtifactKey execute(final long executionID, final EnEvent incomingEvent) + public AxArtifactKey execute(final long executionId, final EnEvent incomingEvent) throws StateMachineException, ContextException { boolean returnValue = false; // Do execution pre work - executePre(executionID, incomingEvent); + executePre(executionId, incomingEvent); try { // Check and execute the Jython logic @@ -103,10 +107,10 @@ public class JythonTaskSelectExecutor extends TaskSelectExecutor { try { final Object ret = interpreter.get("returnValue", java.lang.Boolean.class); if (ret == null) { - LOGGER.error("execute: task selection logic failed to set a return value for state \"" + LOGGER.error(TSL_FAILED_PREFIX + getSubject().getKey().getId() + "\""); throw new StateMachineException( - "execute: task selection logic failed to set a return value for state \"" + TSL_FAILED_PREFIX + getSubject().getKey().getId() + "\""); } returnValue = (Boolean) ret; @@ -114,7 +118,7 @@ public class JythonTaskSelectExecutor extends TaskSelectExecutor { LOGGER.error("execute: task selection logic failed to set a correct return value for state \"" + getSubject().getKey().getId() + "\"", e); throw new StateMachineException( - "execute: task selection logic failed to set a return value for state \"" + TSL_FAILED_PREFIX + getSubject().getKey().getId() + "\"", e); } diff --git a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MVELExecutorParameters.java b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MVELExecutorParameters.java deleted file mode 100644 index 21d124212..000000000 --- a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MVELExecutorParameters.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.plugins.executor.mvel; - -import org.onap.policy.apex.core.engine.ExecutorParameters; - -/** - * This class provides executor parameters for the MVEL Executor plugin. It specifies the classes that provide the MVEL - * implementations of the abstract classes {@link org.onap.policy.apex.core.engine.executor.TaskExecutor}, - * {@link org.onap.policy.apex.core.engine.executor.TaskSelectExecutor}, and - * {@link org.onap.policy.apex.core.engine.executor.StateFinalizerExecutor}. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class MVELExecutorParameters extends ExecutorParameters { - /** - * Constructor that sets the abstract implementation classes. - */ - public MVELExecutorParameters() { - this.setTaskExecutorPluginClass(MvelTaskExecutor.class.getCanonicalName()); - this.setTaskSelectionExecutorPluginClass(MvelTaskSelectExecutor.class.getCanonicalName()); - this.setStateFinalizerExecutorPluginClass(MvelStateFinalizerExecutor.class.getCanonicalName()); - } -} diff --git a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelExecutorParameters.java b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelExecutorParameters.java new file mode 100644 index 000000000..7b57ad446 --- /dev/null +++ b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelExecutorParameters.java @@ -0,0 +1,42 @@ +/*- + * ============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.mvel; + +import org.onap.policy.apex.core.engine.ExecutorParameters; + +/** + * This class provides executor parameters for the MVEL Executor plugin. It specifies the classes that provide the MVEL + * implementations of the abstract classes {@link org.onap.policy.apex.core.engine.executor.TaskExecutor}, + * {@link org.onap.policy.apex.core.engine.executor.TaskSelectExecutor}, and + * {@link org.onap.policy.apex.core.engine.executor.StateFinalizerExecutor}. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class MvelExecutorParameters extends ExecutorParameters { + /** + * Constructor that sets the abstract implementation classes. + */ + public MvelExecutorParameters() { + this.setTaskExecutorPluginClass(MvelTaskExecutor.class.getCanonicalName()); + this.setTaskSelectionExecutorPluginClass(MvelTaskSelectExecutor.class.getCanonicalName()); + this.setStateFinalizerExecutorPluginClass(MvelStateFinalizerExecutor.class.getCanonicalName()); + } +} diff --git a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelStateFinalizerExecutor.java b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelStateFinalizerExecutor.java index ea39c6d74..5086259a8 100644 --- a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelStateFinalizerExecutor.java +++ b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelStateFinalizerExecutor.java @@ -68,17 +68,17 @@ public class MvelStateFinalizerExecutor extends StateFinalizerExecutor { /** * Executes the executor for the state finalizer logic in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields for finalisation * @return The state output for the state * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public String execute(final long executionID, final Map incomingFields) + public String execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Check and execute the MVEL logic argumentNotNull(compiled, "MVEL state finalizer logic not compiled."); diff --git a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskExecutor.java b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskExecutor.java index 966a8004a..457539411 100644 --- a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskExecutor.java +++ b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskExecutor.java @@ -68,17 +68,17 @@ public class MvelTaskExecutor extends TaskExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingFields the incoming fields * @return The outgoing fields * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public Map execute(final long executionID, final Map incomingFields) + public Map execute(final long executionId, final Map incomingFields) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingFields); + executePre(executionId, incomingFields); // Check and execute the MVEL logic argumentNotNull(compiled, "MVEL task not compiled."); diff --git a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskSelectExecutor.java b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskSelectExecutor.java index 4991fbade..b07c5e260 100644 --- a/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskSelectExecutor.java +++ b/plugins/plugins-executor/plugins-executor-mvel/src/main/java/org/onap/policy/apex/plugins/executor/mvel/MvelTaskSelectExecutor.java @@ -69,17 +69,17 @@ public class MvelTaskSelectExecutor extends TaskSelectExecutor { /** * Executes the executor for the task in a sequential manner. * - * @param executionID the execution ID for the current APEX policy execution + * @param executionId the execution ID for the current APEX policy execution * @param incomingEvent the incoming event * @return The outgoing event * @throws StateMachineException on an execution error * @throws ContextException on context errors */ @Override - public AxArtifactKey execute(final long executionID, final EnEvent incomingEvent) + public AxArtifactKey execute(final long executionId, final EnEvent incomingEvent) throws StateMachineException, ContextException { // Do execution pre work - executePre(executionID, incomingEvent); + executePre(executionId, incomingEvent); // Check and execute the MVEL logic argumentNotNull(compiled, "MVEL task not compiled."); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java index 3840e915d..a9b862d41 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java @@ -20,6 +20,8 @@ package org.onap.policy.apex.service.engine.engdep; +import com.google.common.eventbus.Subscribe; + import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -50,17 +52,14 @@ import org.onap.policy.apex.service.engine.runtime.EngineService; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; -import com.google.common.eventbus.Subscribe; - /** - * The listener interface for receiving engDepMessage events. The class that is interested in - * processing a engDepMessage event implements this interface, and the object created with that - * class is registered with a component using the component's addEngDepMessageListener - * method. When the engDepMessage event occurs, that object's appropriate method is invoked. + * The listener interface for receiving engDepMessage events. The class that is interested in processing a engDepMessage + * event implements this interface, and the object created with that class is registered with a component using the + * component's addEngDepMessageListener method. When the engDepMessage event occurs, that object's + * appropriate method is invoked. * - *

    This class uses a queue to buffer incoming messages. When the listener is called, it places the - * incoming message on the queue. A thread runs which removes the messages from the queue and - * forwards them to the Apex engine. + *

    This class uses a queue to buffer incoming messages. When the listener is called, it places the incoming message + * on the queue. A thread runs which removes the messages from the queue and forwards them to the Apex engine. * * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com) */ @@ -83,9 +82,8 @@ public class EngDepMessageListener implements MessageListener, Runnable private final BlockingQueue> messageQueue = new LinkedBlockingDeque<>(); /** - * Instantiates a new EngDep message listener for listening for messages coming in from the - * Deployment client. The apexService is the Apex service to send the messages - * onto. + * Instantiates a new EngDep message listener for listening for messages coming in from the Deployment client. The + * apexService is the Apex service to send the messages onto. * * @param apexService the Apex engine service */ @@ -94,8 +92,8 @@ public class EngDepMessageListener implements MessageListener, Runnable } /** - * This method is an implementation of the message listener. It receives a message and places it - * on the queue for processing by the message listening thread. + * This method is an implementation of the message listener. It receives a message and places it on the queue for + * processing by the message listening thread. * * @param data the data * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage @@ -106,8 +104,8 @@ public class EngDepMessageListener implements MessageListener, Runnable public void onMessage(final MessageBlock data) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("message received from client application {} port {}", - data.getConnection().getRemoteSocketAddress().getAddress(), - data.getConnection().getRemoteSocketAddress().getPort()); + data.getConnection().getRemoteSocketAddress().getAddress(), + data.getConnection().getRemoteSocketAddress().getPort()); } messageQueue.add(data); } @@ -115,8 +113,7 @@ public class EngDepMessageListener implements MessageListener, Runnable /* * (non-Javadoc) * - * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage(java.lang. - * String) + * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage(java.lang. String) */ @Override public void onMessage(final String messageString) { @@ -148,8 +145,7 @@ public class EngDepMessageListener implements MessageListener, Runnable } /** - * Runs the message listening thread. Here, the messages come in on the message queue and are - * processed one by one + * Runs the message listening thread. Here, the messages come in on the message queue and are processed one by one */ @Override public void run() { @@ -173,8 +169,8 @@ public class EngDepMessageListener implements MessageListener, Runnable } /** - * This method handles EngDep messages as they come in. It uses the inevitable switch statement - * to handle the messages. + * This method handles EngDep messages as they come in. It uses the inevitable switch statement to handle the + * messages. * * @param message the incoming EngDep message * @param webSocket the web socket on which the message came in @@ -195,7 +191,7 @@ public class EngDepMessageListener implements MessageListener, Runnable enDepAction = (EngDepAction) message.getAction(); } else { throw new ApexException(message.getAction().getClass().getName() - + "action on received message invalid, action must be of type \"EnDepAction\""); + + "action on received message invalid, action must be of type \"EnDepAction\""); } // Handle each incoming message using the inevitable switch statement for the EngDep @@ -204,12 +200,12 @@ public class EngDepMessageListener implements MessageListener, Runnable case GET_ENGINE_SERVICE_INFO: final GetEngineServiceInfo engineServiceInformationMessage = (GetEngineServiceInfo) message; LOGGER.debug("getting engine service information for engine service " + apexService.getKey().getId() - + " . . ."); + + " . . ."); // Send a reply with the engine service information sendServiceInfoReply(webSocket, engineServiceInformationMessage, apexService.getKey(), - apexService.getEngineKeys(), apexService.getApexModelKey()); - LOGGER.debug( - "returned engine service information for engine service " + apexService.getKey().getId()); + apexService.getEngineKeys(), apexService.getApexModelKey()); + LOGGER.debug("returned engine service information for engine service " + + apexService.getKey().getId()); break; case UPDATE_MODEL: @@ -217,10 +213,10 @@ public class EngDepMessageListener implements MessageListener, Runnable LOGGER.debug("updating model in engine {} . . .", updateModelMessage.getTarget().getId()); // Update the model apexService.updateModel(updateModelMessage.getTarget(), updateModelMessage.getMessageData(), - updateModelMessage.isForceInstall()); + updateModelMessage.isForceInstall()); // Send a reply indicating the message action worked sendReply(webSocket, updateModelMessage, true, - "updated model in engine " + updateModelMessage.getTarget().getId()); + "updated model in engine " + updateModelMessage.getTarget().getId()); LOGGER.debug("updated model in engine service {}", updateModelMessage.getTarget().getId()); break; @@ -231,7 +227,7 @@ public class EngDepMessageListener implements MessageListener, Runnable apexService.start(startEngineMessage.getTarget()); // Send a reply indicating the message action worked sendReply(webSocket, startEngineMessage, true, - "started engine " + startEngineMessage.getTarget().getId()); + "started engine " + startEngineMessage.getTarget().getId()); LOGGER.debug("started engine {}", startEngineMessage.getTarget().getId()); break; @@ -242,33 +238,33 @@ public class EngDepMessageListener implements MessageListener, Runnable apexService.stop(stopEngineMessage.getTarget()); // Send a reply indicating the message action worked sendReply(webSocket, stopEngineMessage, true, - "stopped engine " + stopEngineMessage.getTarget().getId()); + "stopped engine " + stopEngineMessage.getTarget().getId()); LOGGER.debug("stopping engine {}", stopEngineMessage.getTarget().getId()); break; case START_PERIODIC_EVENTS: final StartPeriodicEvents startPeriodicEventsMessage = (StartPeriodicEvents) message; LOGGER.debug("starting periodic events on engine {} . . .", - startPeriodicEventsMessage.getTarget().getId()); + startPeriodicEventsMessage.getTarget().getId()); // Start periodic events with the period specified in the message final Long period = Long.parseLong(startPeriodicEventsMessage.getMessageData()); apexService.startPeriodicEvents(period); // Send a reply indicating the message action worked - sendReply(webSocket, startPeriodicEventsMessage, true, "started periodic events on engine " - + startPeriodicEventsMessage.getTarget().getId() + " with period " + period); - LOGGER.debug("started periodic events on engine " + startPeriodicEventsMessage.getTarget().getId() - + " with period " + period); + String periodicStartedMessage = "started periodic events on engine " + + startPeriodicEventsMessage.getTarget().getId() + " with period " + period; + sendReply(webSocket, startPeriodicEventsMessage, true, periodicStartedMessage); + LOGGER.debug(periodicStartedMessage); break; case STOP_PERIODIC_EVENTS: final StopPeriodicEvents stopPeriodicEventsMessage = (StopPeriodicEvents) message; LOGGER.debug("stopping periodic events on engine {} . . .", - stopPeriodicEventsMessage.getTarget().getId()); + stopPeriodicEventsMessage.getTarget().getId()); // Stop periodic events apexService.stopPeriodicEvents(); // Send a reply indicating the message action worked - sendReply(webSocket, stopPeriodicEventsMessage, true, - "stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getId()); + sendReply(webSocket, stopPeriodicEventsMessage, true, "stopped periodic events on engine " + + stopPeriodicEventsMessage.getTarget().getId()); LOGGER.debug("stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getId()); break; @@ -277,7 +273,7 @@ public class EngDepMessageListener implements MessageListener, Runnable LOGGER.debug("getting status for engine{} . . .", getEngineStatusMessage.getTarget().getId()); // Send a reply with the engine status sendReply(webSocket, getEngineStatusMessage, true, - apexService.getStatus(getEngineStatusMessage.getTarget())); + apexService.getStatus(getEngineStatusMessage.getTarget())); LOGGER.debug("returned status for engine {}", getEngineStatusMessage.getTarget().getId()); break; @@ -313,7 +309,7 @@ public class EngDepMessageListener implements MessageListener, Runnable * @param messageData the message data */ private void sendReply(final WebSocket client, final Message requestMessage, final boolean result, - final String messageData) { + final String messageData) { LOGGER.entry(result, messageData); if (client == null || !client.isOpen()) { @@ -321,8 +317,9 @@ public class EngDepMessageListener implements MessageListener, Runnable return; } - LOGGER.debug("sending {} to web socket {}", requestMessage.getAction(), - client.getRemoteSocketAddress().toString()); + String replyString = "sending " + requestMessage.getAction() + " to web socket " + + client.getRemoteSocketAddress().toString(); + LOGGER.debug(replyString); final Response responseMessage = new Response(requestMessage.getTarget(), result, requestMessage); responseMessage.setMessageData(messageData); @@ -344,14 +341,15 @@ public class EngDepMessageListener implements MessageListener, Runnable * @param apexModelKey the apex model key */ private void sendServiceInfoReply(final WebSocket client, final Message requestMessage, - final AxArtifactKey engineServiceKey, final Collection engineKeyCollection, - final AxArtifactKey apexModelKey) { + final AxArtifactKey engineServiceKey, final Collection engineKeyCollection, + final AxArtifactKey apexModelKey) { LOGGER.entry(); - LOGGER.debug("sending {} to web socket {}", requestMessage.getAction(), - client.getRemoteSocketAddress().toString()); + String sendingMessage = "sending " + requestMessage.getAction() + " to web socket " + + client.getRemoteSocketAddress().toString(); + LOGGER.debug(sendingMessage); - final EngineServiceInfoResponse responseMessage = - new EngineServiceInfoResponse(requestMessage.getTarget(), true, requestMessage); + final EngineServiceInfoResponse responseMessage = new EngineServiceInfoResponse(requestMessage.getTarget(), + true, requestMessage); responseMessage.setMessageData("engine service information"); responseMessage.setEngineServiceKey(engineServiceKey); responseMessage.setEngineKeyArray(engineKeyCollection); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java index 86589ac81..7ebcad830 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java @@ -22,14 +22,13 @@ package org.onap.policy.apex.service.engine.engdep; import java.net.InetSocketAddress; -import org.onap.policy.apex.service.engine.runtime.EngineService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - import org.onap.policy.apex.core.infrastructure.messaging.MessagingService; import org.onap.policy.apex.core.infrastructure.messaging.MessagingServiceFactory; import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils; import org.onap.policy.apex.core.protocols.Message; +import org.onap.policy.apex.service.engine.runtime.EngineService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; /** * The Class EngDepMessagingService is used to encapsulate the server side of EngDep communication. diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java index 38762ea97..8c7911bce 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java @@ -37,6 +37,9 @@ import org.slf4j.ext.XLoggerFactory; * @author Liam Fallon (liam.fallon@ericsson.com) */ public class ApexEvent extends HashMap implements Serializable { + // Recurring string constants + private static final String EVENT_PREAMBLE = "event \""; + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEvent.class); private static final long serialVersionUID = -4451918242101961685L; @@ -111,7 +114,7 @@ public class ApexEvent extends HashMap implements Serializable { // An identifier for the current event execution. The default value here will always be unique // in a single JVM - private long executionID = ApexEvent.getNextExecutionID(); + private long executionId = ApexEvent.getNextExecutionId(); // A string holding a message that indicates why processing of this event threw an exception private String exceptionMessage; @@ -122,7 +125,7 @@ public class ApexEvent extends HashMap implements Serializable { * * @return the next candidate value for a Execution ID */ - private static synchronized long getNextExecutionID() { + private static synchronized long getNextExecutionId() { return nextExecutionID.getAndIncrement(); } @@ -139,11 +142,11 @@ public class ApexEvent extends HashMap implements Serializable { public ApexEvent(final String name, final String version, final String nameSpace, final String source, final String target) throws ApexEventException { // @formatter:off - this.name = validateField("name", name, NAME_REGEXP); - this.version = validateField("version", version, VERSION_REGEXP); - this.nameSpace = validateField("nameSpace", nameSpace, NAMESPACE_REGEXP); - this.source = validateField("source", source, SOURCE_REGEXP); - this.target = validateField("target", target, TARGET_REGEXP); + this.name = validateField(NAME_HEADER_FIELD, name, NAME_REGEXP); + this.version = validateField(VERSION_HEADER_FIELD, version, VERSION_REGEXP); + this.nameSpace = validateField(NAMESPACE_HEADER_FIELD, nameSpace, NAMESPACE_REGEXP); + this.source = validateField(SOURCE_HEADER_FIELD, source, SOURCE_REGEXP); + this.target = validateField(TARGET_HEADER_FIELD, target, TARGET_REGEXP); // @formatter:on } @@ -161,10 +164,10 @@ public class ApexEvent extends HashMap implements Serializable { if (fieldValue.matches(fieldRegexp)) { return fieldValue; } else { - LOGGER.warn("event \"" + name + ": field \"" + fieldName + "=" + fieldValue - + "\" is illegal. It doesn't match regex '" + fieldRegexp + "'"); - throw new ApexEventException( - "event \"" + name + ": field \"" + fieldName + "=" + fieldValue + "\" is illegal"); + String message = EVENT_PREAMBLE + name + ": field \"" + fieldName + "=" + fieldValue + + "\" is illegal. It doesn't match regex '" + fieldRegexp + "'"; + LOGGER.warn(message); + throw new ApexEventException(message); } } @@ -179,8 +182,9 @@ public class ApexEvent extends HashMap implements Serializable { if (key.matches(AxReferenceKey.LOCAL_NAME_REGEXP)) { return key; } else { - LOGGER.warn("event \"" + name + ": key \"" + key + "\" is illegal"); - throw new ApexEventException("event \"" + name + ": key \"" + key + "\" is illegal"); + String message = EVENT_PREAMBLE + name + ": key \"" + key + "\" is illegal"; + LOGGER.warn(message); + throw new ApexEventException(message); } } @@ -234,8 +238,8 @@ public class ApexEvent extends HashMap implements Serializable { * * @return the executionID */ - public long getExecutionID() { - return executionID; + public long getExecutionId() { + return executionId; } /** @@ -243,10 +247,10 @@ public class ApexEvent extends HashMap implements Serializable { * unique in the current JVM. For some applications/deployments this executionID may need to * globally unique * - * @param executionID the executionID + * @param executionId the executionID */ - public void setExecutionID(final long executionID) { - this.executionID = executionID; + public void setExecutionId(final long executionId) { + this.executionId = executionId; } /** @@ -330,7 +334,7 @@ public class ApexEvent extends HashMap implements Serializable { builder.append(",target="); builder.append(target); builder.append(",executionID="); - builder.append(executionID); + builder.append(executionId); builder.append(",exceptionMessage="); builder.append(exceptionMessage); builder.append(","); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java index b34d5185c..32f87a7cc 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java @@ -86,7 +86,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { private final EngineServiceEventInterface engineServiceEventInterface; // Timing information - private long period = 0; + private long eventGeneratorPeriod = 0; private long firstEventTime = 0; private long lastEventTime = 0; private long eventCount = 0; @@ -102,7 +102,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { final long period) { // Save the engine service reference and delay this.engineServiceEventInterface = engineServiceEventInterface; - this.period = period; + this.eventGeneratorPeriod = period; timer = new Timer(ApexPeriodicEventGenerator.class.getSimpleName(), true); timer.schedule(this, period, period); @@ -128,7 +128,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { eventCount++; // Set the fields in the periodic event - periodicEventMap.put(PERIODIC_DELAY, period); + periodicEventMap.put(PERIODIC_DELAY, eventGeneratorPeriod); periodicEventMap.put(PERIODIC_FIRST_TIME, firstEventTime); periodicEventMap.put(PERIODIC_LAST_TIME, lastEventTime); periodicEventMap.put(PERIODIC_CURRENT_TIME, currentEventTime); @@ -170,7 +170,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { */ @Override public String toString() { - return "ApexPeriodicEventGenerator [period=" + period + ", firstEventTime=" + firstEventTime + return "ApexPeriodicEventGenerator [period=" + eventGeneratorPeriod + ", firstEventTime=" + firstEventTime + ", lastEventTime=" + lastEventTime + ", eventCount=" + eventCount + "]"; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java index 1830fc0e5..5e48a5894 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java @@ -33,9 +33,8 @@ import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** - * This class holds a cache of the synchronous events sent into Apex and that have not yet been - * replied to. It runs a thread to time out events that have not been replied to in the specified - * timeout. + * This class holds a cache of the synchronous events sent into Apex and that have not yet been replied to. It runs a + * thread to time out events that have not been replied to in the specified timeout. * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -55,11 +54,10 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { private long synchronousEventTimeout = DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT; // Map holding outstanding synchronous events - private final Map> toApexEventMap = new HashMap>(); + private final Map> toApexEventMap = new HashMap<>(); // Map holding reply events - private final Map> fromApexEventMap = - new HashMap>(); + private final Map> fromApexEventMap = new HashMap<>(); // The message listener thread and stopping flag private final Thread synchronousEventCacheThread; @@ -71,11 +69,10 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { * @param peeredMode the peered mode for which to return the reference * @param consumer the consumer that is populating the cache * @param producer the producer that is emptying the cache - * @param synchronousEventTimeout the time in milliseconds to wait for the reply to a sent - * synchronous event + * @param synchronousEventTimeout the time in milliseconds to wait for the reply to a sent synchronous event */ public SynchronousEventCache(final EventHandlerPeeredMode peeredMode, final ApexEventConsumer consumer, - final ApexEventProducer producer, final long synchronousEventTimeout) { + final ApexEventProducer producer, final long synchronousEventTimeout) { super(peeredMode, consumer, producer); if (synchronousEventTimeout != 0) { @@ -211,7 +208,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { // Check if there are any unprocessed events if (!toApexEventMap.isEmpty()) { - LOGGER.warn(toApexEventMap.size() + " synchronous events dropped due to system shutdown"); + String message = toApexEventMap.size() + " synchronous events dropped due to system shutdown"; + LOGGER.warn(message); } toApexEventMap.clear(); @@ -226,7 +224,7 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { * @param event the event to cache */ private void cacheSynchronizedEvent(final Map> eventCacheMap, - final long executionId, final Object event) { + final long executionId, final Object event) { LOGGER.entry("Adding event with execution ID: " + executionId); // Check if the event is already in the cache @@ -234,7 +232,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { // If there was no sent event then the event timed out or some unexpected event was // received final String errorMessage = "an event with ID " + executionId - + " already exists in the synchronous event cache, execution IDs must be unique in the system"; + + " already exists in the synchronous event cache, " + + "execution IDs must be unique in the system"; LOGGER.warn(errorMessage); throw new ApexEventRuntimeException(errorMessage); } @@ -243,7 +242,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { eventCacheMap.put(executionId, new SimpleEntry(System.currentTimeMillis(), event)); if (LOGGER.isDebugEnabled()) { - LOGGER.debug("event has been cached:" + event); + String message = "event has been cached:" + event; + LOGGER.debug(message); } LOGGER.exit("Added: " + executionId); @@ -257,7 +257,7 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { * @return The removed event */ private Object removeCachedEventIfExists(final Map> eventCacheMap, - final long executionId) { + final long executionId) { LOGGER.entry("Removing: " + executionId); final SimpleEntry removedEventEntry = eventCacheMap.remove(executionId); @@ -273,8 +273,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { } /** - * Time out events on an event cache map. Events that have a timeout longer than the configured - * timeout are timed out. + * Time out events on an event cache map. Events that have a timeout longer than the configured timeout are timed + * out. * * @param eventCacheMap the event cache to operate on */ @@ -293,12 +293,13 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { } // Remove timed out events from the map - for (final long timedoutEventExecutionID : timedOutEventSet) { + for (final long timedoutEventExecutionId : timedOutEventSet) { // Remove the map entry and issue a warning - final SimpleEntry timedOutEventEntry = eventCacheMap.remove(timedoutEventExecutionID); + final SimpleEntry timedOutEventEntry = eventCacheMap.remove(timedoutEventExecutionId); - LOGGER.warn("synchronous event timed out, reply not received in " + synchronousEventTimeout - + " milliseconds on event " + timedOutEventEntry.getValue()); + String message = "synchronous event timed out, reply not received in " + synchronousEventTimeout + + " milliseconds on event " + timedOutEventEntry.getValue(); + LOGGER.warn(message); } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java index 8f54c049b..5c44f2d7d 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java @@ -36,11 +36,6 @@ public class EventConsumerFactory { // The logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventConsumerFactory.class); - /** - * Empty constructor with no generic overloading. - */ - public EventConsumerFactory() {} - /** * Create an event consumer of the required type for the specified consumer technology. * diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java index 9bbbad362..727f77995 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java @@ -36,11 +36,6 @@ public class EventProducerFactory { // The logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProducerFactory.class); - /** - * Empty constructor with no generic overloading. - */ - public EventProducerFactory() {} - /** * Create an event producer of the required type for the specified producer technology. * diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java index 34690cc7d..5fce2c89f 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java @@ -23,19 +23,18 @@ package org.onap.policy.apex.service.engine.event.impl.enevent; import java.util.ArrayList; import java.util.List; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.event.ApexEventConverter; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - import org.onap.policy.apex.core.engine.engine.ApexEngine; 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.service.ModelService; import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.event.ApexEventConverter; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; /** * The Class ApexEvent2EnEventConverter converts externally facing {@link ApexEvent} instances to @@ -90,7 +89,7 @@ public final class ApexEvent2EnEventConverter implements ApexEventConverter { axEvent.getNameSpace(), axEvent.getSource(), axEvent.getTarget()); // Copy the ExecutionID from the EnEvent into the ApexEvent - apexEvent.setExecutionID(enEvent.getExecutionId()); + apexEvent.setExecutionId(enEvent.getExecutionId()); // Copy he exception message to the Apex event if it is set if (enEvent.getExceptionMessage() != null) { @@ -101,7 +100,7 @@ public final class ApexEvent2EnEventConverter implements ApexEventConverter { apexEvent.putAll(enEvent); // Return the event in a single element - final ArrayList eventList = new ArrayList(); + final ArrayList eventList = new ArrayList<>(); eventList.add(apexEvent); return eventList; } @@ -136,7 +135,7 @@ public final class ApexEvent2EnEventConverter implements ApexEventConverter { enEvent.putAll(apexEvent); // copy the ExecutionID from the ApexEvent into the EnEvent - enEvent.setExecutionId(apexEvent.getExecutionID()); + enEvent.setExecutionId(apexEvent.getExecutionId()); return enEvent; } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java deleted file mode 100644 index 84d19fc62..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java +++ /dev/null @@ -1,217 +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.event.impl.filecarrierplugin; - -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.ApexFileEventConsumer; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.producer.ApexFileEventProducer; -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ValidationStatus; -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * This class holds the parameters that allows transport of events into and out of Apex using files and standard input - * and output. - * - *

    - * The following parameters are defined: - *

      - *
    1. fileName: The full path to the file from which to read events or to which to write events. - *
    2. standardIO: If this flag is set to true, then standard input is used to read events in or standard output is used - * to write events and the fileName parameter is ignored if present - *
    3. standardError: If this flag is set to true, then standard error is used to write events - *
    4. streamingMode: If this flag is set to true, then streaming mode is set for reading events and event handling will - * wait on the input stream for events until the stream is closed. If streaming model is off, then event reading - * completes when the end of input is detected. - *
    5. startDelay: The amount of milliseconds to wait at startup startup before processing the first event. - *
    - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class FILECarrierTechnologyParameters extends CarrierTechnologyParameters { - // @formatter:off - /** The label of this carrier technology. */ - public static final String FILE_CARRIER_TECHNOLOGY_LABEL = "FILE"; - - /** The producer plugin class for the FILE carrier technology. */ - public static final String FILE_EVENT_PRODUCER_PLUGIN_CLASS = ApexFileEventProducer.class.getCanonicalName(); - - /** The consumer plugin class for the FILE carrier technology. */ - public static final String FILE_EVENT_CONSUMER_PLUGIN_CLASS = ApexFileEventConsumer.class.getCanonicalName(); - - private String fileName; - private boolean standardIO = false; - private boolean standardError = false; - private boolean streamingMode = false; - private long startDelay = 0; - // @formatter:on - - /** - * Constructor to create a file carrier technology parameters instance and register the instance with the parameter - * service. - */ - public FILECarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the FILE carrier technology - this.setLabel(FILE_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(FILE_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(FILE_EVENT_CONSUMER_PLUGIN_CLASS); - } - - /** - * Gets the file name from which to read or to which to write events. - * - * @return the file name from which to read or to which to write events - */ - public String getFileName() { - return ResourceUtils.getFilePath4Resource(fileName); - } - - /** - * Checks if is standard IO should be used for input or output. - * - * @return true, if standard IO should be used for input or output - */ - public boolean isStandardIO() { - return standardIO; - } - - /** - * Checks if is standard error should be used for output. - * - * @return true, if standard error should be used for output - */ - public boolean isStandardError() { - return standardError; - } - - /** - * Checks if is streaming mode is on. - * - * @return true, if streaming mode is on - */ - public boolean isStreamingMode() { - return streamingMode; - } - - /** - * Sets the file name from which to read or to which to write events. - * - * @param fileName the file name from which to read or to which to write events - */ - public void setFileName(final String fileName) { - this.fileName = fileName; - } - - /** - * Sets if standard IO should be used for event input or output. - * - * @param standardIO if standard IO should be used for event input or output - */ - public void setStandardIO(final boolean standardIO) { - this.standardIO = standardIO; - } - - /** - * Sets if standard error should be used for event output. - * - * @param standardError if standard error should be used for event output - */ - public void setStandardError(final boolean standardError) { - this.standardError = standardError; - } - - /** - * Sets streaming mode. - * - * @param streamingMode the streaming mode value - */ - public void setStreamingMode(final boolean streamingMode) { - this.streamingMode = streamingMode; - } - - /** - * Gets the delay in milliseconds before the plugin starts processing. - * - * @return the delay - */ - public long getStartDelay() { - return startDelay; - } - - /** - * Sets the delay in milliseconds before the plugin starts processing. - * - * @param startDelay the delay - */ - public void setStartDelay(final long startDelay) { - this.startDelay = startDelay; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters# toString() - */ - @Override - public String toString() { - return "FILECarrierTechnologyParameters [fileName=" + fileName + ", standardIO=" + standardIO - + ", standardError=" + standardError + ", streamingMode=" + streamingMode + ", startDelay=" - + startDelay + "]"; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.common.parameters.ParameterGroup#getName() - */ - @Override - public String getName() { - return this.getLabel(); - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = super.validate(); - - if (!standardIO && !standardError && (fileName == null || fileName.trim().length() == 0)) { - result.setResult("fileName", ValidationStatus.INVALID, - "fileName not specified or is blank or null, it must be specified as a valid file location"); - } - - if (standardIO || standardError) { - streamingMode = true; - } - - if (startDelay < 0) { - result.setResult("startDelay", ValidationStatus.INVALID, - "startDelay must be zero or a positive number of milliseconds"); - } - - return result; - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParameters.java new file mode 100644 index 000000000..cbfe18016 --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParameters.java @@ -0,0 +1,212 @@ +/*- + * ============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.event.impl.filecarrierplugin; + +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.ApexFileEventConsumer; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.producer.ApexFileEventProducer; +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * This class holds the parameters that allows transport of events into and out of Apex using files and standard input + * and output. + * + *

    The following parameters are defined:

    1. fileName: The full path to the file from which to read events or to + * which to write events.
    2. standardIO: If this flag is set to true, then standard input is used to read events in or + * standard output is used to write events and the fileName parameter is ignored if present
    3. standardError: If this + * flag is set to true, then standard error is used to write events
    4. streamingMode: If this flag is set to true, then + * streaming mode is set for reading events and event handling will wait on the input stream for events until the stream + * is closed. If streaming model is off, then event reading completes when the end of input is detected.
    5. startDelay: + * The amount of milliseconds to wait at startup startup before processing the first event.
    + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class FileCarrierTechnologyParameters extends CarrierTechnologyParameters { + // @formatter:off + /** The label of this carrier technology. */ + public static final String FILE_CARRIER_TECHNOLOGY_LABEL = "FILE"; + + /** The producer plugin class for the FILE carrier technology. */ + public static final String FILE_EVENT_PRODUCER_PLUGIN_CLASS = ApexFileEventProducer.class.getCanonicalName(); + + /** The consumer plugin class for the FILE carrier technology. */ + public static final String FILE_EVENT_CONSUMER_PLUGIN_CLASS = ApexFileEventConsumer.class.getCanonicalName(); + + private String fileName; + private boolean standardIo = false; + private boolean standardError = false; + private boolean streamingMode = false; + private long startDelay = 0; + // @formatter:on + + /** + * Constructor to create a file carrier technology parameters instance and register the instance with the parameter + * service. + */ + public FileCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the FILE carrier technology + this.setLabel(FILE_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(FILE_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(FILE_EVENT_CONSUMER_PLUGIN_CLASS); + } + + /** + * Gets the file name from which to read or to which to write events. + * + * @return the file name from which to read or to which to write events + */ + public String getFileName() { + return ResourceUtils.getFilePath4Resource(fileName); + } + + /** + * Checks if is standard IO should be used for input or output. + * + * @return true, if standard IO should be used for input or output + */ + public boolean isStandardIo() { + return standardIo; + } + + /** + * Checks if is standard error should be used for output. + * + * @return true, if standard error should be used for output + */ + public boolean isStandardError() { + return standardError; + } + + /** + * Checks if is streaming mode is on. + * + * @return true, if streaming mode is on + */ + public boolean isStreamingMode() { + return streamingMode; + } + + /** + * Sets the file name from which to read or to which to write events. + * + * @param fileName the file name from which to read or to which to write events + */ + public void setFileName(final String fileName) { + this.fileName = fileName; + } + + /** + * Sets if standard IO should be used for event input or output. + * + * @param standardIo if standard IO should be used for event input or output + */ + public void setStandardIo(final boolean standardIo) { + this.standardIo = standardIo; + } + + /** + * Sets if standard error should be used for event output. + * + * @param standardError if standard error should be used for event output + */ + public void setStandardError(final boolean standardError) { + this.standardError = standardError; + } + + /** + * Sets streaming mode. + * + * @param streamingMode the streaming mode value + */ + public void setStreamingMode(final boolean streamingMode) { + this.streamingMode = streamingMode; + } + + /** + * Gets the delay in milliseconds before the plugin starts processing. + * + * @return the delay + */ + public long getStartDelay() { + return startDelay; + } + + /** + * Sets the delay in milliseconds before the plugin starts processing. + * + * @param startDelay the delay + */ + public void setStartDelay(final long startDelay) { + this.startDelay = startDelay; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters# toString() + */ + @Override + public String toString() { + return "FILECarrierTechnologyParameters [fileName=" + fileName + ", standardIO=" + standardIo + + ", standardError=" + standardError + ", streamingMode=" + streamingMode + ", startDelay=" + + startDelay + "]"; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.common.parameters.ParameterGroup#getName() + */ + @Override + public String getName() { + return this.getLabel(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); + + if (!standardIo && !standardError && (fileName == null || fileName.trim().length() == 0)) { + result.setResult("fileName", ValidationStatus.INVALID, "fileName not specified or is blank or null, " + + "it must be specified as a valid file location"); + } + + if (standardIo || standardError) { + streamingMode = true; + } + + if (startDelay < 0) { + result.setResult("startDelay", ValidationStatus.INVALID, + "startDelay must be zero or a positive number of milliseconds"); + } + + return result; + } +} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java index 7521c3a08..0f0996fb8 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java @@ -33,23 +33,25 @@ import org.onap.policy.apex.service.engine.event.ApexEventConsumer; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventReceiver; import org.onap.policy.apex.service.engine.event.PeeredReference; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Concrete implementation an Apex event consumer that reads events from a file. This consumer also - * implements ApexEventProducer and therefore can be used as a synchronous consumer. + * Concrete implementation an Apex event consumer that reads events from a file. This consumer also implements + * ApexEventProducer and therefore can be used as a synchronous consumer. * * @author Liam Fallon (liam.fallon@ericsson.com) */ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { - // Get a reference to the logger private static final Logger LOGGER = LoggerFactory.getLogger(ApexFileEventConsumer.class); + // Recurring string constants + private static final String APEX_FILE_CONSUMER_PREAMBLE = "ApexFileConsumer \""; + // The input stream to read events from private InputStream eventInputStream; @@ -66,35 +68,34 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { private String consumerName = null; // The specific carrier technology parameters for this consumer - private FILECarrierTechnologyParameters fileCarrierTechnologyParameters; + private FileCarrierTechnologyParameters fileCarrierTechnologyParameters; // The peer references for this event handler - private final Map peerReferenceMap = - new EnumMap<>(EventHandlerPeeredMode.class); + private final Map peerReferenceMap = new EnumMap<>( + EventHandlerPeeredMode.class); // Holds the next identifier for event execution. private static AtomicLong nextExecutionID = new AtomicLong(0L); /** - * Private utility to get the next candidate value for a Execution ID. This value will always be - * unique in a single JVM + * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single + * JVM * * @return the next candidate value for a Execution ID */ - private static synchronized long getNextExecutionID() { + private static synchronized long getNextExecutionId() { return nextExecutionID.getAndIncrement(); } /* * (non-Javadoc) * - * @see - * org.onap.policy.apex.apps.uservice.consumer.ApexEventConsumer#init(org.onap.policy.apex.apps. + * @see org.onap.policy.apex.apps.uservice.consumer.ApexEventConsumer#init(org.onap.policy.apex.apps. * uservice.consumer.ApexEventReceiver) */ @Override public void init(final String name, final EventHandlerParameters consumerParameters, - final ApexEventReceiver incomingEventReceiver) throws ApexEventException { + final ApexEventReceiver incomingEventReceiver) throws ApexEventException { this.eventReceiver = incomingEventReceiver; this.consumerName = name; @@ -106,18 +107,18 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { } // Check and get the file Properties - if (!(consumerParameters.getCarrierTechnologyParameters() instanceof FILECarrierTechnologyParameters)) { + if (!(consumerParameters.getCarrierTechnologyParameters() instanceof FileCarrierTechnologyParameters)) { final String errorMessage = "specified consumer properties for ApexFileConsumer \"" + consumerName - + "\" are not applicable to a File consumer"; + + "\" are not applicable to a File consumer"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - fileCarrierTechnologyParameters = - (FILECarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); + fileCarrierTechnologyParameters = (FileCarrierTechnologyParameters) consumerParameters + .getCarrierTechnologyParameters(); // Open the file producing events try { - if (fileCarrierTechnologyParameters.isStandardIO()) { + if (fileCarrierTechnologyParameters.isStandardIo()) { eventInputStream = System.in; } else { eventInputStream = new FileInputStream(fileCarrierTechnologyParameters.getFileName()); @@ -125,10 +126,11 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { // Get an event composer for our event source textBlockReader = new TextBlockReaderFactory().getTaggedReader(eventInputStream, - consumerParameters.getEventProtocolParameters()); + consumerParameters.getEventProtocolParameters()); } catch (final IOException e) { - final String errorMessage = "ApexFileConsumer \"" + consumerName + "\" failed to open file for reading: \"" - + fileCarrierTechnologyParameters.getFileName() + "\""; + final String errorMessage = APEX_FILE_CONSUMER_PREAMBLE + consumerName + + "\" failed to open file for reading: \"" + fileCarrierTechnologyParameters.getFileName() + + "\""; LOGGER.warn(errorMessage, e); throw new ApexEventException(errorMessage, e); } @@ -195,7 +197,7 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { // Check that we have been initialized in async or sync mode if (eventReceiver == null) { LOGGER.warn("\"{}\" has not been initilaized for either asynchronous or synchronous event handling", - consumerName); + consumerName); return; } @@ -209,18 +211,19 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { // Process the event from the text block if there is one there if (textBlock.getText() != null) { - eventReceiver.receiveEvent(getNextExecutionID(), textBlock.getText()); + eventReceiver.receiveEvent(getNextExecutionId(), textBlock.getText()); } - } while (!textBlock.isEndOfText()); + } + while (!textBlock.isEndOfText()); } catch (final Exception e) { LOGGER.warn("\"" + consumerName + "\" failed to read event from file: \"" - + fileCarrierTechnologyParameters.getFileName() + "\"", e); + + fileCarrierTechnologyParameters.getFileName() + "\"", e); } finally { try { eventInputStream.close(); } catch (final IOException e) { - LOGGER.warn("ApexFileConsumer \"" + consumerName + "\" failed to close file: \"" - + fileCarrierTechnologyParameters.getFileName() + "\"", e); + LOGGER.warn(APEX_FILE_CONSUMER_PREAMBLE + consumerName + "\" failed to close file: \"" + + fileCarrierTechnologyParameters.getFileName() + "\"", e); } } @@ -236,8 +239,8 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { try { eventInputStream.close(); } catch (final IOException e) { - LOGGER.warn("ApexFileConsumer \"" + consumerName + "\" failed to close file for reading: \"" - + fileCarrierTechnologyParameters.getFileName() + "\"", e); + LOGGER.warn(APEX_FILE_CONSUMER_PREAMBLE + consumerName + "\" failed to close file for reading: \"" + + fileCarrierTechnologyParameters.getFileName() + "\"", e); } if (consumerThread.isAlive() && !consumerThread.isInterrupted()) { diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java index b286f8afe..bd7310d0a 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java @@ -93,12 +93,29 @@ public class CharacterDelimitedTextBlockReader implements TextBlockReader { return new TextBlock(eofOnInputStream, null); } - // The initial nesting level of incoming text blocks is always zero - int nestingLevel = 0; + // Read the block of text + final StringBuilder textBlockBuilder = readTextBlockText(); + // Condition the text block and return it + final String textBlock = textBlockBuilder.toString().trim(); + if (textBlock.length() > 0) { + return new TextBlock(eofOnInputStream, textBlock); + } else { + return new TextBlock(eofOnInputStream, null); + } + } + + /** + * Read a block of text. + * @return A string builder containing the text + * @throws IOException on read errors + */ + private StringBuilder readTextBlockText() throws IOException { // Holder for the text block final StringBuilder textBlockBuilder = new StringBuilder(); + int nestingLevel = 0; + // Read the next text block while (true) { final char nextChar = (char) inputStream.read(); @@ -106,13 +123,13 @@ public class CharacterDelimitedTextBlockReader implements TextBlockReader { // Check for EOF if (nextChar == (char) -1) { eofOnInputStream = true; - break; + return textBlockBuilder; } if (nextChar == startTagChar) { nestingLevel++; } else if (nestingLevel == 0 && !Character.isWhitespace(nextChar)) { - LOGGER.warn("invalid input on consumer: " + nextChar); + LOGGER.warn("invalid input on consumer: {}", nextChar); continue; } @@ -125,17 +142,9 @@ public class CharacterDelimitedTextBlockReader implements TextBlockReader { } if (nestingLevel == 0) { - break; + return textBlockBuilder; } } } - - // Condition the text block and return it - final String textBlock = textBlockBuilder.toString().trim(); - if (textBlock.length() > 0) { - return new TextBlock(eofOnInputStream, textBlock); - } else { - return new TextBlock(eofOnInputStream, null); - } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java index 07185c024..982044022 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java @@ -162,7 +162,7 @@ public class HeaderDelimitedTextBlockReader implements TextBlockReader, Runnable // Condition the text block and return it final String textBlock = textBlockBuilder.toString().trim(); - final boolean endOfText = (eofOnInputStream && textLineQueue.isEmpty() ? true : false); + final boolean endOfText = eofOnInputStream && textLineQueue.isEmpty(); if (textBlock.length() > 0) { return new TextBlock(endOfText, textBlock); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java index d5f9ff1b2..e12b772df 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java @@ -32,7 +32,7 @@ import org.onap.policy.apex.service.engine.event.ApexEventProducer; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; import org.onap.policy.apex.service.engine.event.PeeredReference; import org.onap.policy.apex.service.engine.event.SynchronousEventCache; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; import org.slf4j.Logger; @@ -74,20 +74,20 @@ public class ApexFileEventProducer implements ApexEventProducer { } // Check and get the file Properties - if (!(producerParameters.getCarrierTechnologyParameters() instanceof FILECarrierTechnologyParameters)) { + if (!(producerParameters.getCarrierTechnologyParameters() instanceof FileCarrierTechnologyParameters)) { final String errorMessage = "specified producer properties for ApexFileProducer \"" + producerName + "\" are not applicable to a FILE producer"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - final FILECarrierTechnologyParameters fileCarrierTechnologyParameters = - (FILECarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + final FileCarrierTechnologyParameters fileCarrierTechnologyParameters = + (FileCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); // Now we create a writer for events try { if (fileCarrierTechnologyParameters.isStandardError()) { eventOutputStream = System.err; - } else if (fileCarrierTechnologyParameters.isStandardIO()) { + } else if (fileCarrierTechnologyParameters.isStandardIo()) { eventOutputStream = System.out; } else { eventOutputStream = diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java deleted file mode 100644 index 30e9db722..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java +++ /dev/null @@ -1,438 +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.event.impl.jsonprotocolplugin; - -import java.util.ArrayList; -import java.util.List; - -import org.onap.policy.apex.context.SchemaHelper; -import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory; -import org.onap.policy.apex.model.basicmodel.service.ModelService; -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.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -/** - * The Class Apex2JSONEventConverter converts {@link ApexEvent} instances to and from JSON string - * representations of Apex events. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class Apex2JSONEventConverter implements ApexEventProtocolConverter { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JSONEventConverter.class); - - // The parameters for the JSON event protocol - private JSONEventProtocolParameters jsonPars; - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter#init(org.onap.policy. - * apex.service.parameters.eventprotocol.EventProtocolParameters) - */ - @Override - public void init(final EventProtocolParameters parameters) { - // Check and get the JSON parameters - if (!(parameters instanceof JSONEventProtocolParameters)) { - final String errorMessage = "specified consumer properties are not applicable to the JSON event protocol"; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - - jsonPars = (JSONEventProtocolParameters) parameters; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, - * java.lang.Object) - */ - @Override - public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { - // Check the event eventObject - if (eventObject == null) { - LOGGER.warn("event processing failed, event is null"); - throw new ApexEventException("event processing failed, event is null"); - } - - // Cast the event to a string, if our conversion is correctly configured, this cast should - // always work - String jsonEventString = null; - try { - jsonEventString = (String) eventObject; - } catch (final Exception e) { - final String errorMessage = "error converting event \"" + eventObject + "\" to a string"; - LOGGER.debug(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - - // The list of events we will return - final List eventList = new ArrayList<>(); - - try { - // We may have a single JSON object with a single event or an array of JSON objects - final Object decodedJsonObject = - new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, Object.class); - - // Check if we have a list of objects - if (decodedJsonObject instanceof List) { - // Check if it's a list of JSON objects or a list of strings - @SuppressWarnings("unchecked") - final List decodedJsonList = (List) decodedJsonObject; - - // Decode each of the list elements in sequence - for (final Object jsonListObject : decodedJsonList) { - if (jsonListObject instanceof String) { - eventList.add(jsonStringApexEvent(eventName, (String) jsonListObject)); - } else if (jsonListObject instanceof JsonObject) { - eventList.add(jsonObject2ApexEvent(eventName, (JsonObject) jsonListObject)); - } else { - throw new ApexEventException("incoming event (" + jsonEventString - + ") is a JSON object array containing an invalid object " + jsonListObject); - } - } - } else { - eventList.add(jsonStringApexEvent(eventName, jsonEventString)); - } - } catch (final Exception e) { - final String errorString = - "Failed to unmarshal JSON event: " + e.getMessage() + ", event=" + jsonEventString; - LOGGER.warn(errorString, e); - throw new ApexEventException(errorString, e); - } - - // Return the list of events we have unmarshalled - return eventList; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy. - * apex.service.engine.event.ApexEvent) - */ - @Override - public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { - // Check the Apex event - if (apexEvent == null) { - LOGGER.warn("event processing failed, Apex event is null"); - throw new ApexEventException("event processing failed, Apex event is null"); - } - - // Get the event definition for the event from the model service - final AxEvent eventDefinition = - ModelService.getModel(AxEvents.class).get(apexEvent.getName(), apexEvent.getVersion()); - - // Use a GSON Json object to marshal the Apex event to JSON - final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create(); - final JsonObject jsonObject = new JsonObject(); - - jsonObject.addProperty(ApexEvent.NAME_HEADER_FIELD, apexEvent.getName()); - jsonObject.addProperty(ApexEvent.VERSION_HEADER_FIELD, apexEvent.getVersion()); - jsonObject.addProperty(ApexEvent.NAMESPACE_HEADER_FIELD, apexEvent.getNameSpace()); - jsonObject.addProperty(ApexEvent.SOURCE_HEADER_FIELD, apexEvent.getSource()); - jsonObject.addProperty(ApexEvent.TARGET_HEADER_FIELD, apexEvent.getTarget()); - - if (apexEvent.getExceptionMessage() != null) { - jsonObject.addProperty(ApexEvent.EXCEPTION_MESSAGE_HEADER_FIELD, apexEvent.getExceptionMessage()); - } - - for (final AxField eventField : eventDefinition.getFields()) { - final String fieldName = eventField.getKey().getLocalName(); - - if (!apexEvent.containsKey(fieldName)) { - if (!eventField.getOptional()) { - final String errorMessage = "error parsing " + eventDefinition.getId() + " event to Json. " - + "Field \"" + fieldName + "\" is missing, but is mandatory. Fields: " + apexEvent; - LOGGER.debug(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - continue; - } - - final Object fieldValue = apexEvent.get(fieldName); - - // Get the schema helper - final SchemaHelper fieldSchemaHelper = - new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), eventField.getSchema()); - jsonObject.add(fieldName, (JsonElement) fieldSchemaHelper.marshal2Object(fieldValue)); - } - - // Output JSON string in a pretty format - return gson.toJson(jsonObject); - } - - /** - * This method converts a JSON object into an Apex event. - * - * @param eventName the name of the event - * @param jsonEventString the JSON string that holds the event - * @return the apex event that we have converted the JSON object into - * @throws ApexEventException thrown on unmarshaling exceptions - */ - private ApexEvent jsonStringApexEvent(final String eventName, final String jsonEventString) - throws ApexEventException { - // Use GSON to read the event string - final JsonObject jsonObject = - new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, JsonObject.class); - - if (jsonObject == null || !jsonObject.isJsonObject()) { - throw new ApexEventException( - "incoming event (" + jsonEventString + ") is not a JSON object or an JSON object array"); - } - - return jsonObject2ApexEvent(eventName, jsonObject); - } - - /** - * This method converts a JSON object into an Apex event. - * - * @param eventName the name of the event - * @param jsonObject the JSON object that holds the event - * @return the apex event that we have converted the JSON object into - * @throws ApexEventException thrown on unmarshaling exceptions - */ - private ApexEvent jsonObject2ApexEvent(final String eventName, final JsonObject jsonObject) - throws ApexEventException { - // Process the mandatory Apex header - final ApexEvent apexEvent = processApexEventHeader(eventName, jsonObject); - - // Get the event definition for the event from the model service - final AxEvent eventDefinition = - ModelService.getModel(AxEvents.class).get(apexEvent.getName(), apexEvent.getVersion()); - - // Iterate over the input fields in the event - for (final AxField eventField : eventDefinition.getFields()) { - final String fieldName = eventField.getKey().getLocalName(); - if (!hasJSONField(jsonObject, fieldName)) { - if (!eventField.getOptional()) { - final String errorMessage = "error parsing " + eventDefinition.getId() + " event from Json. " - + "Field \"" + fieldName + "\" is missing, but is mandatory."; - LOGGER.debug(errorMessage); - throw new ApexEventException(errorMessage); - } - continue; - } - - final JsonElement fieldValue = getJSONField(jsonObject, fieldName, null, !eventField.getOptional()); - - if (fieldValue != null && !fieldValue.isJsonNull()) { - // Get the schema helper - final SchemaHelper fieldSchemaHelper = - new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), eventField.getSchema()); - apexEvent.put(fieldName, fieldSchemaHelper.createNewInstance(fieldValue)); - } else { - apexEvent.put(fieldName, null); - } - } - return apexEvent; - - } - - /** - * This method processes the event header of an Apex event. - * - * @param eventName the name of the event - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @return an apex event constructed using the header fields of the event - * @throws ApexEventRuntimeException the apex event runtime exception - * @throws ApexEventException on invalid events with missing header fields - */ - private ApexEvent processApexEventHeader(final String eventName, final JsonObject jsonObject) - throws ApexEventException { - // Get the event header fields - // @formatter:off - String name = getJSONStringField(jsonObject, ApexEvent.NAME_HEADER_FIELD, - jsonPars.getNameAlias(), ApexEvent.NAME_REGEXP, false); - String version = getJSONStringField(jsonObject, ApexEvent.VERSION_HEADER_FIELD, - jsonPars.getVersionAlias(), ApexEvent.VERSION_REGEXP, false); - String namespace = getJSONStringField(jsonObject, ApexEvent.NAMESPACE_HEADER_FIELD, - jsonPars.getNameSpaceAlias(), ApexEvent.NAMESPACE_REGEXP, false); - String source = getJSONStringField(jsonObject, ApexEvent.SOURCE_HEADER_FIELD, - jsonPars.getSourceAlias(), ApexEvent.SOURCE_REGEXP, false); - String target = getJSONStringField(jsonObject, ApexEvent.TARGET_HEADER_FIELD, - jsonPars.getTargetAlias(), ApexEvent.TARGET_REGEXP, false); - // @formatter:on - - // Check that an event name has been specified - if (name == null && eventName == null) { - throw new ApexEventRuntimeException( - "event received without mandatory parameter \"name\" on configuration or on event"); - } - - // Check if an event name was specified on the event parameters - if (eventName != null) { - if (name != null && !eventName.equals(name)) { - LOGGER.warn("The incoming event name \"{}\" does not match the configured event name \"{}\"," - + " using configured event name", name, eventName); - } - name = eventName; - } - - // Now, find the event definition in the model service. If version is null, the newest event - // definition in the model service is used - final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(name, version); - if (eventDefinition == null) { - if (version == null) { - throw new ApexEventRuntimeException( - "an event definition for an event named \"" + name + "\" not found in Apex model"); - } - throw new ApexEventRuntimeException("an event definition for an event named \"" + name - + "\" with version \"" + version + "\" not found in Apex model"); - } - - // Use the defined event version if no version is specified on the incoming fields - if (version == null) { - version = eventDefinition.getKey().getVersion(); - } - - // Check the name space is OK if it is defined, if not, use the name space from the model - if (namespace != null) { - if (!namespace.equals(eventDefinition.getNameSpace())) { - throw new ApexEventRuntimeException( - "namespace \"" + namespace + "\" on event \"" + name + "\" does not match namespace \"" - + eventDefinition.getNameSpace() + "\" for that event in the Apex model"); - } - } else { - namespace = eventDefinition.getNameSpace(); - } - - // For source, use the defined source only if the source is not found on the incoming event - if (source == null) { - source = eventDefinition.getSource(); - } - - // For target, use the defined source only if the source is not found on the incoming event - if (target == null) { - target = eventDefinition.getTarget(); - } - - return new ApexEvent(name, version, namespace, source, target); - } - - /** - * This method gets an event string field from a JSON object. - * - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @param fieldName the field name to find in the event - * @param fieldAlias the alias for the field to find in the event, overrides the field name if - * it is not null - * @param fieldRE the regular expression to check the field against for validity - * @param mandatory true if the field is mandatory - * @return the value of the field in the JSON object or null if the field is optional - * @throws ApexEventRuntimeException the apex event runtime exception - */ - private String getJSONStringField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, - final String fieldRE, final boolean mandatory) { - // Get the JSON field for the string field - final JsonElement jsonField = getJSONField(jsonObject, fieldName, fieldAlias, mandatory); - - // Null strings are allowed - if (jsonField == null || jsonField.isJsonNull()) { - return null; - } - - // Check if this is a string field - String fieldValueString = null; - try { - fieldValueString = jsonField.getAsString(); - } catch (final Exception e) { - // The element is not a string so throw an error - throw new ApexEventRuntimeException("field \"" + fieldName + "\" with type \"" - + jsonField.getClass().getCanonicalName() + "\" is not a string value"); - } - - // Is regular expression checking required - if (fieldRE == null) { - return fieldValueString; - } - - // Check the event field against its regular expression - if (!fieldValueString.matches(fieldRE)) { - throw new ApexEventRuntimeException( - "field \"" + fieldName + "\" with value \"" + fieldValueString + "\" is invalid"); - } - - return fieldValueString; - } - - /** - * This method gets an event field from a JSON object. - * - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @param fieldName the field name to find in the event - * @param fieldAlias the alias for the field to find in the event, overrides the field name if - * it is not null - * @param mandatory true if the field is mandatory - * @return the value of the field in the JSON object or null if the field is optional - * @throws ApexEventRuntimeException the apex event runtime exception - */ - private JsonElement getJSONField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, - final boolean mandatory) { - - // Check if we should use the alias for this field - String fieldToFind = fieldName; - if (fieldAlias != null) { - fieldToFind = fieldAlias; - } - - // Get the event field - final JsonElement eventElement = jsonObject.get(fieldToFind); - if (eventElement == null) { - if (!mandatory) { - return null; - } else { - throw new ApexEventRuntimeException("mandatory field \"" + fieldToFind + "\" is missing"); - } - } - - return eventElement; - } - - /** - * This method if a JSON object has a named field. - * - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @param fieldName the field name to find in the event - * @return true if the field is present - * @throws ApexEventRuntimeException the apex event runtime exception - */ - private boolean hasJSONField(final JsonObject jsonObject, final String fieldName) { - // check for the field - return jsonObject.has(fieldName); - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java new file mode 100644 index 000000000..ce511be7f --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java @@ -0,0 +1,440 @@ +/*- + * ============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.event.impl.jsonprotocolplugin; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.policy.apex.context.SchemaHelper; +import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +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.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class Apex2JSONEventConverter converts {@link ApexEvent} instances to and from JSON string representations of + * Apex events. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class Apex2JsonEventConverter implements ApexEventProtocolConverter { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JsonEventConverter.class); + + // The parameters for the JSON event protocol + private JsonEventProtocolParameters jsonPars; + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter#init(org.onap.policy. + * apex.service.parameters.eventprotocol.EventProtocolParameters) + */ + @Override + public void init(final EventProtocolParameters parameters) { + // Check and get the JSON parameters + if (!(parameters instanceof JsonEventProtocolParameters)) { + final String errorMessage = "specified consumer properties are not applicable to the JSON event protocol"; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + + jsonPars = (JsonEventProtocolParameters) parameters; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) + */ + @Override + public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { + // Check the event eventObject + if (eventObject == null) { + LOGGER.warn("event processing failed, event is null"); + throw new ApexEventException("event processing failed, event is null"); + } + + // Cast the event to a string, if our conversion is correctly configured, this cast should + // always work + String jsonEventString = null; + try { + jsonEventString = (String) eventObject; + } catch (final Exception e) { + final String errorMessage = "error converting event \"" + eventObject + "\" to a string"; + LOGGER.debug(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + + // The list of events we will return + final List eventList = new ArrayList<>(); + + try { + // We may have a single JSON object with a single event or an array of JSON objects + final Object decodedJsonObject = new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, + Object.class); + + // Check if we have a list of objects + if (decodedJsonObject instanceof List) { + // Check if it's a list of JSON objects or a list of strings + @SuppressWarnings("unchecked") + final List decodedJsonList = (List) decodedJsonObject; + + // Decode each of the list elements in sequence + for (final Object jsonListObject : decodedJsonList) { + if (jsonListObject instanceof String) { + eventList.add(jsonStringApexEvent(eventName, (String) jsonListObject)); + } else if (jsonListObject instanceof JsonObject) { + eventList.add(jsonObject2ApexEvent(eventName, (JsonObject) jsonListObject)); + } else { + throw new ApexEventException("incoming event (" + jsonEventString + + ") is a JSON object array containing an invalid object " + jsonListObject); + } + } + } else { + eventList.add(jsonStringApexEvent(eventName, jsonEventString)); + } + } catch (final Exception e) { + final String errorString = "Failed to unmarshal JSON event: " + e.getMessage() + ", event=" + + jsonEventString; + LOGGER.warn(errorString, e); + throw new ApexEventException(errorString, e); + } + + // Return the list of events we have unmarshalled + return eventList; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy. + * apex.service.engine.event.ApexEvent) + */ + @Override + public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { + // Check the Apex event + if (apexEvent == null) { + LOGGER.warn("event processing failed, Apex event is null"); + throw new ApexEventException("event processing failed, Apex event is null"); + } + + // Get the event definition for the event from the model service + final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(apexEvent.getName(), + apexEvent.getVersion()); + + // Use a GSON Json object to marshal the Apex event to JSON + final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create(); + final JsonObject jsonObject = new JsonObject(); + + jsonObject.addProperty(ApexEvent.NAME_HEADER_FIELD, apexEvent.getName()); + jsonObject.addProperty(ApexEvent.VERSION_HEADER_FIELD, apexEvent.getVersion()); + jsonObject.addProperty(ApexEvent.NAMESPACE_HEADER_FIELD, apexEvent.getNameSpace()); + jsonObject.addProperty(ApexEvent.SOURCE_HEADER_FIELD, apexEvent.getSource()); + jsonObject.addProperty(ApexEvent.TARGET_HEADER_FIELD, apexEvent.getTarget()); + + if (apexEvent.getExceptionMessage() != null) { + jsonObject.addProperty(ApexEvent.EXCEPTION_MESSAGE_HEADER_FIELD, apexEvent.getExceptionMessage()); + } + + for (final AxField eventField : eventDefinition.getFields()) { + final String fieldName = eventField.getKey().getLocalName(); + + if (!apexEvent.containsKey(fieldName)) { + if (!eventField.getOptional()) { + final String errorMessage = "error parsing " + eventDefinition.getId() + " event to Json. " + + "Field \"" + fieldName + "\" is missing, but is mandatory. Fields: " + apexEvent; + LOGGER.debug(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + continue; + } + + final Object fieldValue = apexEvent.get(fieldName); + + // Get the schema helper + final SchemaHelper fieldSchemaHelper = new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), + eventField.getSchema()); + jsonObject.add(fieldName, (JsonElement) fieldSchemaHelper.marshal2Object(fieldValue)); + } + + // Output JSON string in a pretty format + return gson.toJson(jsonObject); + } + + /** + * This method converts a JSON object into an Apex event. + * + * @param eventName the name of the event + * @param jsonEventString the JSON string that holds the event + * @return the apex event that we have converted the JSON object into + * @throws ApexEventException thrown on unmarshaling exceptions + */ + private ApexEvent jsonStringApexEvent(final String eventName, final String jsonEventString) + throws ApexEventException { + // Use GSON to read the event string + final JsonObject jsonObject = new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, + JsonObject.class); + + if (jsonObject == null || !jsonObject.isJsonObject()) { + throw new ApexEventException( + "incoming event (" + jsonEventString + ") is not a JSON object or an JSON object array"); + } + + return jsonObject2ApexEvent(eventName, jsonObject); + } + + /** + * This method converts a JSON object into an Apex event. + * + * @param eventName the name of the event + * @param jsonObject the JSON object that holds the event + * @return the apex event that we have converted the JSON object into + * @throws ApexEventException thrown on unmarshaling exceptions + */ + private ApexEvent jsonObject2ApexEvent(final String eventName, final JsonObject jsonObject) + throws ApexEventException { + // Process the mandatory Apex header + final ApexEvent apexEvent = processApexEventHeader(eventName, jsonObject); + + // Get the event definition for the event from the model service + final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(apexEvent.getName(), + apexEvent.getVersion()); + + // Iterate over the input fields in the event + for (final AxField eventField : eventDefinition.getFields()) { + final String fieldName = eventField.getKey().getLocalName(); + if (!hasJsonField(jsonObject, fieldName)) { + if (!eventField.getOptional()) { + final String errorMessage = "error parsing " + eventDefinition.getId() + " event from Json. " + + "Field \"" + fieldName + "\" is missing, but is mandatory."; + LOGGER.debug(errorMessage); + throw new ApexEventException(errorMessage); + } + continue; + } + + final JsonElement fieldValue = getJsonField(jsonObject, fieldName, null, !eventField.getOptional()); + + if (fieldValue != null && !fieldValue.isJsonNull()) { + // Get the schema helper + final SchemaHelper fieldSchemaHelper = new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), + eventField.getSchema()); + apexEvent.put(fieldName, fieldSchemaHelper.createNewInstance(fieldValue)); + } else { + apexEvent.put(fieldName, null); + } + } + return apexEvent; + + } + + /** + * This method processes the event header of an Apex event. + * + * @param eventName the name of the event + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @return an apex event constructed using the header fields of the event + * @throws ApexEventRuntimeException the apex event runtime exception + * @throws ApexEventException on invalid events with missing header fields + */ + private ApexEvent processApexEventHeader(final String eventName, final JsonObject jsonObject) + throws ApexEventException { + String name = getJsonStringField(jsonObject, ApexEvent.NAME_HEADER_FIELD, jsonPars.getNameAlias(), + ApexEvent.NAME_REGEXP, false); + + // Check that an event name has been specified + if (name == null && eventName == null) { + throw new ApexEventRuntimeException( + "event received without mandatory parameter \"name\" on configuration or on event"); + } + + // Check if an event name was specified on the event parameters + if (eventName != null) { + if (name != null && !eventName.equals(name)) { + LOGGER.warn("The incoming event name \"{}\" does not match the configured event name \"{}\"," + + " using configured event name", name, eventName); + } + name = eventName; + } + + // Now, find the event definition in the model service. If version is null, the newest event + // definition in the model service is used + String version = getJsonStringField(jsonObject, ApexEvent.VERSION_HEADER_FIELD, jsonPars.getVersionAlias(), + ApexEvent.VERSION_REGEXP, false); + final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(name, version); + if (eventDefinition == null) { + throwVersionException(name, version); + } + + // Use the defined event version if no version is specified on the incoming fields + if (version == null) { + version = eventDefinition.getKey().getVersion(); + } + + // Check the name space is OK if it is defined, if not, use the name space from the model + String namespace = getJsonStringField(jsonObject, ApexEvent.NAMESPACE_HEADER_FIELD, + jsonPars.getNameSpaceAlias(), ApexEvent.NAMESPACE_REGEXP, false); + if (namespace != null) { + if (!namespace.equals(eventDefinition.getNameSpace())) { + throw new ApexEventRuntimeException("namespace \"" + namespace + "\" on event \"" + name + + "\" does not match namespace \"" + eventDefinition.getNameSpace() + + "\" for that event in the Apex model"); + } + } else { + namespace = eventDefinition.getNameSpace(); + } + + // For source, use the defined source only if the source is not found on the incoming event + String source = getJsonStringField(jsonObject, ApexEvent.SOURCE_HEADER_FIELD, jsonPars.getSourceAlias(), + ApexEvent.SOURCE_REGEXP, false); + if (source == null) { + source = eventDefinition.getSource(); + } + + // For target, use the defined source only if the source is not found on the incoming event + String target = getJsonStringField(jsonObject, ApexEvent.TARGET_HEADER_FIELD, jsonPars.getTargetAlias(), + ApexEvent.TARGET_REGEXP, false); + if (target == null) { + target = eventDefinition.getTarget(); + } + + return new ApexEvent(name, version, namespace, source, target); + } + + /** + * Throw an exception on event name and/or version with the correct text. + * @param name The event name + * @param version The event version + */ + private void throwVersionException(String name, String version) { + if (version == null) { + throw new ApexEventRuntimeException( + "an event definition for an event named \"" + name + "\" not found in Apex model"); + } + else { + throw new ApexEventRuntimeException("an event definition for an event named \"" + name + + "\" with version \"" + version + "\" not found in Apex model"); + } + } + + /** + * This method gets an event string field from a JSON object. + * + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @param fieldName the field name to find in the event + * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null + * @param fieldRegexp the regular expression to check the field against for validity + * @param mandatory true if the field is mandatory + * @return the value of the field in the JSON object or null if the field is optional + * @throws ApexEventRuntimeException the apex event runtime exception + */ + private String getJsonStringField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, + final String fieldRegexp, final boolean mandatory) { + // Get the JSON field for the string field + final JsonElement jsonField = getJsonField(jsonObject, fieldName, fieldAlias, mandatory); + + // Null strings are allowed + if (jsonField == null || jsonField.isJsonNull()) { + return null; + } + + // Check if this is a string field + String fieldValueString = null; + try { + fieldValueString = jsonField.getAsString(); + } catch (final Exception e) { + // The element is not a string so throw an error + throw new ApexEventRuntimeException("field \"" + fieldName + "\" with type \"" + + jsonField.getClass().getCanonicalName() + "\" is not a string value"); + } + + // Is regular expression checking required + if (fieldRegexp == null) { + return fieldValueString; + } + + // Check the event field against its regular expression + if (!fieldValueString.matches(fieldRegexp)) { + throw new ApexEventRuntimeException( + "field \"" + fieldName + "\" with value \"" + fieldValueString + "\" is invalid"); + } + + return fieldValueString; + } + + /** + * This method gets an event field from a JSON object. + * + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @param fieldName the field name to find in the event + * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null + * @param mandatory true if the field is mandatory + * @return the value of the field in the JSON object or null if the field is optional + * @throws ApexEventRuntimeException the apex event runtime exception + */ + private JsonElement getJsonField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, + final boolean mandatory) { + + // Check if we should use the alias for this field + String fieldToFind = fieldName; + if (fieldAlias != null) { + fieldToFind = fieldAlias; + } + + // Get the event field + final JsonElement eventElement = jsonObject.get(fieldToFind); + if (eventElement == null) { + if (!mandatory) { + return null; + } else { + throw new ApexEventRuntimeException("mandatory field \"" + fieldToFind + "\" is missing"); + } + } + + return eventElement; + } + + /** + * This method if a JSON object has a named field. + * + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @param fieldName the field name to find in the event + * @return true if the field is present + * @throws ApexEventRuntimeException the apex event runtime exception + */ + private boolean hasJsonField(final JsonObject jsonObject, final String fieldName) { + // check for the field + return jsonObject.has(fieldName); + } +} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java deleted file mode 100644 index 6efcceb43..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java +++ /dev/null @@ -1,187 +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.event.impl.jsonprotocolplugin; - -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextCharDelimitedParameters; - -/** - * Event protocol parameters for JSON as an event protocol. - * - *

    The parameters for this plugin are: - *

      - *
    1. nameAlias: The field in a JSON event to use as an alias for the event name. This parameter is - * optional. - *
    2. versionAlias: The field in a JSON event to use as an alias for the event version. This - * parameter is optional. - *
    3. nameSpaceAlias: The field in a JSON event to use as an alias for the event name space. This - * parameter is optional. - *
    4. sourceAlias: The field in a JSON event to use as an alias for the event source. This - * parameter is optional. - *
    5. targetAlias: The field in a JSON event to use as an alias for the event target. This - * parameter is optional. - *
    - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JSONEventProtocolParameters extends EventProtocolTextCharDelimitedParameters { - /** The label of this event protocol. */ - public static final String JSON_EVENT_PROTOCOL_LABEL = "JSON"; - - // Constants for text block delimiters - private static final char JSON_TEXT_BLOCK_START_DELIMITER = '{'; - private static final char JSON_TEXT_BLOCK_END_DELIMITER = '}'; - - // Aliases for Apex event header fields - // @formatter:off - private String nameAlias = null; - private String versionAlias = null; - private String nameSpaceAlias = null; - private String sourceAlias = null; - private String targetAlias = null; - // @formatter:on - - /** - * Constructor to create a JSON event protocol parameter instance and register the instance with - * the parameter service. - */ - public JSONEventProtocolParameters() { - this(JSONEventProtocolParameters.class.getCanonicalName(), JSON_EVENT_PROTOCOL_LABEL); - } - - /** - * Constructor to create an event protocol parameters instance with the name of a sub class of - * this class. - * - * @param parameterClassName the class name of a sub class of this class - * @param eventProtocolLabel the name of the event protocol for this plugin - */ - public JSONEventProtocolParameters(final String parameterClassName, final String eventProtocolLabel) { - super(parameterClassName); - - // Set the event protocol properties for the JSON event protocol - this.setLabel(eventProtocolLabel); - - // Set the starting and ending delimiters for text blocks of JSON events - this.setStartChar(JSON_TEXT_BLOCK_START_DELIMITER); - this.setEndChar(JSON_TEXT_BLOCK_END_DELIMITER); - - // Set the event protocol plugin class - this.setEventProtocolPluginClass(Apex2JSONEventConverter.class.getCanonicalName()); - } - - /* (non-Javadoc) - * @see org.onap.policy.common.parameters.ParameterGroup#getName() - */ - @Override - public String getName() { - return this.getLabel(); - } - - /** - * Gets the name alias. - * - * @return the name alias - */ - public String getNameAlias() { - return nameAlias; - } - - /** - * Gets the version alias. - * - * @return the version alias - */ - public String getVersionAlias() { - return versionAlias; - } - - /** - * Gets the name space alias. - * - * @return the name space alias - */ - public String getNameSpaceAlias() { - return nameSpaceAlias; - } - - /** - * Gets the source alias. - * - * @return the source alias - */ - public String getSourceAlias() { - return sourceAlias; - } - - /** - * Gets the target alias. - * - * @return the target alias - */ - public String getTargetAlias() { - return targetAlias; - } - - /** - * Sets the name alias. - * - * @param nameAlias the new name alias - */ - public void setNameAlias(String nameAlias) { - this.nameAlias = nameAlias; - } - - /** - * Sets the version alias. - * - * @param versionAlias the new version alias - */ - public void setVersionAlias(String versionAlias) { - this.versionAlias = versionAlias; - } - - /** - * Sets the name space alias. - * - * @param nameSpaceAlias the new name space alias - */ - public void setNameSpaceAlias(String nameSpaceAlias) { - this.nameSpaceAlias = nameSpaceAlias; - } - - /** - * Sets the source alias. - * - * @param sourceAlias the new source alias - */ - public void setSourceAlias(String sourceAlias) { - this.sourceAlias = sourceAlias; - } - - /** - * Sets the target alias. - * - * @param targetAlias the new target alias - */ - public void setTargetAlias(String targetAlias) { - this.targetAlias = targetAlias; - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JsonEventProtocolParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JsonEventProtocolParameters.java new file mode 100644 index 000000000..8e44ec59b --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JsonEventProtocolParameters.java @@ -0,0 +1,187 @@ +/*- + * ============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.event.impl.jsonprotocolplugin; + +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextCharDelimitedParameters; + +/** + * Event protocol parameters for JSON as an event protocol. + * + *

    The parameters for this plugin are: + *

      + *
    1. nameAlias: The field in a JSON event to use as an alias for the event name. This parameter is + * optional. + *
    2. versionAlias: The field in a JSON event to use as an alias for the event version. This + * parameter is optional. + *
    3. nameSpaceAlias: The field in a JSON event to use as an alias for the event name space. This + * parameter is optional. + *
    4. sourceAlias: The field in a JSON event to use as an alias for the event source. This + * parameter is optional. + *
    5. targetAlias: The field in a JSON event to use as an alias for the event target. This + * parameter is optional. + *
    + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JsonEventProtocolParameters extends EventProtocolTextCharDelimitedParameters { + /** The label of this event protocol. */ + public static final String JSON_EVENT_PROTOCOL_LABEL = "JSON"; + + // Constants for text block delimiters + private static final char JSON_TEXT_BLOCK_START_DELIMITER = '{'; + private static final char JSON_TEXT_BLOCK_END_DELIMITER = '}'; + + // Aliases for Apex event header fields + // @formatter:off + private String nameAlias = null; + private String versionAlias = null; + private String nameSpaceAlias = null; + private String sourceAlias = null; + private String targetAlias = null; + // @formatter:on + + /** + * Constructor to create a JSON event protocol parameter instance and register the instance with + * the parameter service. + */ + public JsonEventProtocolParameters() { + this(JsonEventProtocolParameters.class.getCanonicalName(), JSON_EVENT_PROTOCOL_LABEL); + } + + /** + * Constructor to create an event protocol parameters instance with the name of a sub class of + * this class. + * + * @param parameterClassName the class name of a sub class of this class + * @param eventProtocolLabel the name of the event protocol for this plugin + */ + public JsonEventProtocolParameters(final String parameterClassName, final String eventProtocolLabel) { + super(parameterClassName); + + // Set the event protocol properties for the JSON event protocol + this.setLabel(eventProtocolLabel); + + // Set the starting and ending delimiters for text blocks of JSON events + this.setStartChar(JSON_TEXT_BLOCK_START_DELIMITER); + this.setEndChar(JSON_TEXT_BLOCK_END_DELIMITER); + + // Set the event protocol plugin class + this.setEventProtocolPluginClass(Apex2JsonEventConverter.class.getCanonicalName()); + } + + /* (non-Javadoc) + * @see org.onap.policy.common.parameters.ParameterGroup#getName() + */ + @Override + public String getName() { + return this.getLabel(); + } + + /** + * Gets the name alias. + * + * @return the name alias + */ + public String getNameAlias() { + return nameAlias; + } + + /** + * Gets the version alias. + * + * @return the version alias + */ + public String getVersionAlias() { + return versionAlias; + } + + /** + * Gets the name space alias. + * + * @return the name space alias + */ + public String getNameSpaceAlias() { + return nameSpaceAlias; + } + + /** + * Gets the source alias. + * + * @return the source alias + */ + public String getSourceAlias() { + return sourceAlias; + } + + /** + * Gets the target alias. + * + * @return the target alias + */ + public String getTargetAlias() { + return targetAlias; + } + + /** + * Sets the name alias. + * + * @param nameAlias the new name alias + */ + public void setNameAlias(String nameAlias) { + this.nameAlias = nameAlias; + } + + /** + * Sets the version alias. + * + * @param versionAlias the new version alias + */ + public void setVersionAlias(String versionAlias) { + this.versionAlias = versionAlias; + } + + /** + * Sets the name space alias. + * + * @param nameSpaceAlias the new name space alias + */ + public void setNameSpaceAlias(String nameSpaceAlias) { + this.nameSpaceAlias = nameSpaceAlias; + } + + /** + * Sets the source alias. + * + * @param sourceAlias the new source alias + */ + public void setSourceAlias(String sourceAlias) { + this.sourceAlias = sourceAlias; + } + + /** + * Sets the target alias. + * + * @param targetAlias the new target alias + */ + public void setTargetAlias(String targetAlias) { + this.targetAlias = targetAlias; + } +} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java index d6d278ebf..bdbd82dc2 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java @@ -42,6 +42,8 @@ import org.onap.policy.common.utils.resources.ResourceUtils; * @author Liam Fallon (liam.fallon@ericsson.com) */ public class ApexCommandLineArguments { + // Recurring string constants + private static final String FILE_PREAMBLE = " file \""; private static final int HELP_LINE_LENGTH = 120; // Apache Commons CLI options @@ -181,12 +183,11 @@ public class ApexCommandLineArguments { * @return the help string */ public String help(final String mainClassName) { - final HelpFormatter helpFormatter = new HelpFormatter(); final StringWriter stringWriter = new StringWriter(); - final PrintWriter stringPW = new PrintWriter(stringWriter); + final PrintWriter stringPrintWriter = new PrintWriter(stringWriter); - helpFormatter.printHelp(stringPW, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0, 0, - ""); + new HelpFormatter().printHelp(stringPrintWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", + options, 0, 0, ""); return stringWriter.toString(); } @@ -268,20 +269,20 @@ public class ApexCommandLineArguments { } // The file name can refer to a resource on the local file system or on the class path - final URL fileURL = ResourceUtils.getUrl4Resource(fileName); - if (fileURL == null) { - throw new ApexException(fileTag + " file \"" + fileName + "\" does not exist"); + final URL fileUrl = ResourceUtils.getUrl4Resource(fileName); + if (fileUrl == null) { + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" does not exist"); } - final File theFile = new File(fileURL.getPath()); + final File theFile = new File(fileUrl.getPath()); if (!theFile.exists()) { - throw new ApexException(fileTag + " file \"" + fileName + "\" does not exist"); + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" does not exist"); } if (!theFile.isFile()) { - throw new ApexException(fileTag + " file \"" + fileName + "\" is not a normal file"); + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is not a normal file"); } if (!theFile.canRead()) { - throw new ApexException(fileTag + " file \"" + fileName + "\" is ureadable"); + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is ureadable"); } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java index 9904847aa..532fdb9c7 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java @@ -187,19 +187,19 @@ public class ApexEventMarshaller implements ApexEventListener, Runnable { // Process the next Apex event from the queue final Object event = converter.fromApexEvent(apexEvent); - producer.sendEvent(apexEvent.getExecutionID(), apexEvent.getName(), event); + producer.sendEvent(apexEvent.getExecutionId(), apexEvent.getName(), event); if (LOGGER.isTraceEnabled()) { - LOGGER.trace("event sent : " + apexEvent.toString()); + String message = "event sent : " + apexEvent.toString(); + LOGGER.trace(message); } } catch (final InterruptedException e) { // restore the interrupt status Thread.currentThread().interrupt(); LOGGER.debug("Thread interrupted, Reason {}", e.getMessage()); - break; + stopOrderedFlag = true; } catch (final Exception e) { LOGGER.warn("Error while forwarding events for " + marshallerThread.getName(), e); - continue; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java index 7b4188ea1..1d1b64e37 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java @@ -44,8 +44,8 @@ import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** - * This event unmarshaler handles events coming into Apex, handles threading, event queuing, - * transformation and receiving using the configured receiving technology. + * This event unmarshaler handles events coming into Apex, handles threading, event queuing, transformation and + * receiving using the configured receiving technology. * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -88,7 +88,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { * @param consumerParameters the consumer parameters for this specific unmarshaler */ public ApexEventUnmarshaller(final String name, final EngineServiceParameters engineServiceParameters, - final EventHandlerParameters consumerParameters) { + final EventHandlerParameters consumerParameters) { this.name = name; this.engineServiceParameters = engineServiceParameters; this.consumerParameters = consumerParameters; @@ -97,8 +97,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { /** * Configure the consumer and initialize the thread for event sending. * - * @param incomingEngineServiceHandler the Apex engine service handler for passing events to - * Apex + * @param incomingEngineServiceHandler the Apex engine service handler for passing events to Apex * @throws ApexEventException on errors initializing event handling */ public void init(final ApexEngineServiceHandler incomingEngineServiceHandler) throws ApexEventException { @@ -119,8 +118,8 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { consumer.start(); // Configure and start the event reception thread - final String threadName = - engineServiceParameters.getEngineKey().getName() + ":" + this.getClass().getName() + ":" + name; + final String threadName = engineServiceParameters.getEngineKey().getName() + ":" + this.getClass().getName() + + ":" + name; unmarshallerThread = new ApplicationThreadFactory(threadName).newThread(this); unmarshallerThread.setDaemon(true); unmarshallerThread.start(); @@ -165,7 +164,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // To connect a synchronous unmarshaler and marshaler, we create a synchronous event // cache on the consumer/producer pair new SynchronousEventCache(peeredMode, consumer, peeredMarshaller.getProducer(), - consumerParameters.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); + consumerParameters.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); return; case REQUESTOR: @@ -180,8 +179,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { /* * (non-Javadoc) * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(java.lang.Object) + * @see org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(java.lang.Object) */ @Override public void receiveEvent(final Object event) throws ApexEventException { @@ -191,8 +189,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { /* * (non-Javadoc) * - * @see org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(long, - * java.lang.Object) + * @see org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(long, java.lang.Object) */ @Override public void receiveEvent(final long executionId, final Object event) throws ApexEventException { @@ -204,15 +201,15 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { * * @param executionId the execution id the incoming execution ID * @param event the event in its native format - * @param generateExecutionId if true, let Apex generate the execution ID, if false, use the - * incoming execution ID + * @param generateExecutionId if true, let Apex generate the execution ID, if false, use the incoming execution ID * @throws ApexEventException on unmarshaling errors on events */ private void receiveEvent(final long executionId, final Object event, final boolean generateExecutionId) - throws ApexEventException { + throws ApexEventException { // Push the event onto the queue if (LOGGER.isTraceEnabled()) { - LOGGER.trace("onMessage(): event received: {}", event.toString()); + String eventString = "onMessage(): event received: " + event.toString(); + LOGGER.trace(eventString); } // Convert the incoming events to Apex events @@ -222,10 +219,10 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // Check if we are filtering events on this unmarshaler, if so check the event name // against the filter if (consumerParameters.isSetEventNameFilter() - && !apexEvent.getName().matches(consumerParameters.getEventNameFilter())) { + && !apexEvent.getName().matches(consumerParameters.getEventNameFilter())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("onMessage(): event {} not processed, filtered out by filter", apexEvent, - consumerParameters.getEventNameFilter()); + consumerParameters.getEventNameFilter()); } // Ignore this event @@ -233,7 +230,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { } if (!generateExecutionId) { - apexEvent.setExecutionID(executionId); + apexEvent.setExecutionId(executionId); } // Enqueue the event @@ -241,22 +238,22 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // Cache synchronized events that are sent if (consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) { - final SynchronousEventCache synchronousEventCache = - (SynchronousEventCache) consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS); - synchronousEventCache.cacheSynchronizedEventToApex(apexEvent.getExecutionID(), apexEvent); + final SynchronousEventCache synchronousEventCache = (SynchronousEventCache) consumer + .getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS); + synchronousEventCache.cacheSynchronizedEventToApex(apexEvent.getExecutionId(), apexEvent); } } } catch (final ApexException e) { final String errorMessage = "Error while converting event into an ApexEvent for " + name + ": " - + e.getMessage() + ", Event=" + event; + + e.getMessage() + ", Event=" + event; LOGGER.warn(errorMessage, e); throw new ApexEventException(errorMessage, e); } } /** - * Run a thread that runs forever (well until system termination anyway) and listens for - * incoming events on the queue. + * Run a thread that runs forever (well until system termination anyway) and listens for incoming events on the + * queue. */ @Override public void run() { @@ -270,7 +267,8 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { } if (LOGGER.isTraceEnabled()) { - LOGGER.trace("event received {}", apexEvent.toString()); + String message = apexEvent.toString(); + LOGGER.trace("event received {}", message); } // Pass the event to the activator for forwarding to Apex @@ -279,10 +277,9 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // restore the interrupt status Thread.currentThread().interrupt(); LOGGER.warn("BatchProcessor thread interrupted, Reason {}", e.getMessage()); - break; + stopOrderedFlag = true; } catch (final Exception e) { LOGGER.warn("Error while forwarding events for " + unmarshallerThread.getName(), e); - continue; } } @@ -309,10 +306,9 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { stopOrderedFlag = true; // Order a stop on the synchronous cache if one exists - if (consumerParameters != null && consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) { - if (consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS) != null) { - ((SynchronousEventCache) consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS)).stop(); - } + if (consumerParameters != null && consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS) + && consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS) != null) { + ((SynchronousEventCache) consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS)).stop(); } // Wait for thread shutdown diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java index 436225fc4..2b15b145f 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java @@ -50,7 +50,6 @@ public class ApexMain { * @param args the commaind line arguments */ public ApexMain(final String[] args) { - System.out.println("Starting Apex service with parameters " + Arrays.toString(args) + " . . ."); LOGGER.entry("Starting Apex service with parameters " + Arrays.toString(args) + " . . ."); // Check the arguments @@ -60,16 +59,13 @@ public class ApexMain { final String argumentMessage = arguments.parse(args); if (argumentMessage != null) { LOGGER.info(argumentMessage); - System.out.println(argumentMessage); return; } // Validate that the arguments are sane arguments.validate(); } catch (final ApexException e) { - System.err.println("start of Apex service failed: " + e.getMessage()); LOGGER.error("start of Apex service failed", e); - System.err.println(arguments.help(ApexMain.class.getCanonicalName())); return; } @@ -77,7 +73,6 @@ public class ApexMain { try { parameters = new ApexParameterHandler().getParameters(arguments); } catch (final Exception e) { - System.err.println("start of Apex service failed\n" + e.getMessage()); LOGGER.error("start of Apex service failed", e); return; } @@ -103,8 +98,6 @@ public class ApexMain { try { activator.initialize(); } catch (final ApexActivatorException e) { - System.err.println("start of Apex service failed, used parameters are " + Arrays.toString(args)); - e.printStackTrace(System.err); LOGGER.error("start of Apex service failed, used parameters are " + Arrays.toString(args), e); return; } @@ -112,7 +105,6 @@ public class ApexMain { // Add a shutdown hook to shut everything down in an orderly manner Runtime.getRuntime().addShutdownHook(new ApexMainShutdownHookClass()); LOGGER.exit("Started Apex"); - System.out.println("Started Apex service"); } /** diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java index 1af0c9d1c..ef17a8eab 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java @@ -101,7 +101,7 @@ public interface EngineService { void updateModel(AxArtifactKey engineServiceKey, AxPolicyModel apexModel, boolean forceFlag) throws ApexException; /** - * This method returns the state of an engine service or engine. + * Return the state of an engine service or engine. * * @return The engine service or engine state */ diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java index 04fb8e389..c99987542 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java @@ -63,6 +63,10 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceImpl.class); private static final boolean DEBUG_ENABLED = LOGGER.isDebugEnabled(); + // Recurring string constants + private static final String ENGINE_KEY_PREAMBLE = "engine with key "; + private static final String NOT_FOUND_SUFFIX = " not found in engine service"; + // Constants for timing private static final long MAX_START_WAIT_TIME = 5000; // 5 seconds private static final long MAX_STOP_WAIT_TIME = 5000; // 5 seconds @@ -96,7 +100,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven * @throws ApexException on worker instantiation errors */ private EngineServiceImpl(final AxArtifactKey engineServiceKey, final int incomingThreadCount, - final long periodicEventPeriod) throws ApexException { + final long periodicEventPeriod) { LOGGER.entry(engineServiceKey, incomingThreadCount); this.engineServiceKey = engineServiceKey; @@ -120,26 +124,6 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.exit(); } - /** - * Create an Apex Engine Service instance. This method is deprecated and will be removed in the next version. - * - * @param engineServiceKey the engine service key - * @param threadCount the thread count, the number of engine workers to start - * @return the Engine Service instance - * @throws ApexException on worker instantiation errors - * @deprecated Do not use this version. Use {@link #create(EngineServiceParameters)} - */ - @Deprecated - public static EngineServiceImpl create(final AxArtifactKey engineServiceKey, final int threadCount) - throws ApexException { - // Check if the Apex model specified is sane - if (engineServiceKey == null) { - LOGGER.warn("engine service key is null"); - throw new ApexException("engine service key is null"); - } - return new EngineServiceImpl(engineServiceKey, threadCount, 0); - } - /** * Create an Apex Engine Service instance. This method does not load the policy so * {@link #updateModel(AxArtifactKey, AxPolicyModel, boolean)} or @@ -266,10 +250,10 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven final boolean forceFlag) throws ApexException { // Check if the Apex model specified is sane if (apexModelString == null || apexModelString.trim().length() == 0) { - LOGGER.warn("model for updating on engine service with key " + incomingEngineServiceKey.getId() - + " is empty"); - throw new ApexException("model for updating on engine service with key " + incomingEngineServiceKey.getId() - + " is empty"); + String emptyModelMessage = "model for updating engine service with key " + + incomingEngineServiceKey.getId() + " is empty"; + LOGGER.warn(emptyModelMessage); + throw new ApexException(emptyModelMessage); } // Read the Apex model into memory using the Apex Model Reader @@ -278,15 +262,15 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); apexPolicyModel = modelReader.read(new ByteArrayInputStream(apexModelString.getBytes())); } catch (final ApexModelException e) { - LOGGER.error("failed to unmarshal the apex model on engine service " + incomingEngineServiceKey.getId(), e); - throw new ApexException( - "failed to unmarshal the apex model on engine service " + incomingEngineServiceKey.getId(), - e); + String message = "failed to unmarshal the apex model on engine service " + incomingEngineServiceKey.getId(); + LOGGER.error(message, e); + throw new ApexException(message, e); } if (apexPolicyModel == null) { - LOGGER.error("apex model null on engine service " + incomingEngineServiceKey.getId()); - throw new ApexException("apex model null on engine service " + incomingEngineServiceKey.getId()); + String message = "apex model null on engine service " + incomingEngineServiceKey.getId(); + LOGGER.error(message); + throw new ApexException(message); } // Update the model @@ -327,43 +311,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // The current policy model may or may not be defined final AxPolicyModel currentModel = ModelService.getModel(AxPolicyModel.class); if (!currentModel.getKey().isCompatible(apexModel.getKey())) { - if (forceFlag) { - LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId() - + "\" is not a compatible model update from the existing engine model with key \"" - + currentModel.getKey().getId() + "\""); - } else { - throw new ContextException("apex model update failed, supplied model with key \"" - + apexModel.getKey().getId() - + "\" is not a compatible model update from the existing engine model with key \"" - + currentModel.getKey().getId() + "\""); - } + handleIncompatibility(apexModel, forceFlag, currentModel); } } if (!isStopped()) { - // Stop all engines on this engine service - stop(); - final long stoptime = System.currentTimeMillis(); - while (!isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT_TIME) { - ThreadUtilities.sleep(ENGINE_SERVICE_STOP_START_WAIT_INTERVAL); - } - // Check if all engines are stopped - final StringBuilder notStoppedEngineIdBuilder = new StringBuilder(); - for (final Entry engineWorkerEntry : engineWorkerMap.entrySet()) { - if (engineWorkerEntry.getValue().getState() != AxEngineState.STOPPED) { - notStoppedEngineIdBuilder.append(engineWorkerEntry.getKey().getId()); - notStoppedEngineIdBuilder.append('('); - notStoppedEngineIdBuilder.append(engineWorkerEntry.getValue().getState()); - notStoppedEngineIdBuilder.append(") "); - } - } - if (notStoppedEngineIdBuilder.length() > 0) { - final String errorString = "cannot update model on engine service with key " - + incomingEngineServiceKey.getId() + ", engines not stopped after " + MAX_STOP_WAIT_TIME - + "ms are: " + notStoppedEngineIdBuilder.toString().trim(); - LOGGER.warn(errorString); - throw new ApexException(errorString); - } + stopEngines(incomingEngineServiceKey); } // Update the engines @@ -400,6 +353,58 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.exit(); } + /** + * Stop engines for a model update. + * @param incomingEngineServiceKey the engine service key for the engines that are to be stopped + * @throws ApexException on errors stopping engines + */ + private void stopEngines(final AxArtifactKey incomingEngineServiceKey) throws ApexException { + // Stop all engines on this engine service + stop(); + final long stoptime = System.currentTimeMillis(); + while (!isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT_TIME) { + ThreadUtilities.sleep(ENGINE_SERVICE_STOP_START_WAIT_INTERVAL); + } + // Check if all engines are stopped + final StringBuilder notStoppedEngineIdBuilder = new StringBuilder(); + for (final Entry engineWorkerEntry : engineWorkerMap.entrySet()) { + if (engineWorkerEntry.getValue().getState() != AxEngineState.STOPPED) { + notStoppedEngineIdBuilder.append(engineWorkerEntry.getKey().getId()); + notStoppedEngineIdBuilder.append('('); + notStoppedEngineIdBuilder.append(engineWorkerEntry.getValue().getState()); + notStoppedEngineIdBuilder.append(") "); + } + } + if (notStoppedEngineIdBuilder.length() > 0) { + final String errorString = "cannot update model on engine service with key " + + incomingEngineServiceKey.getId() + ", engines not stopped after " + MAX_STOP_WAIT_TIME + + "ms are: " + notStoppedEngineIdBuilder.toString().trim(); + LOGGER.warn(errorString); + throw new ApexException(errorString); + } + } + + /** + * Issue compatibility warning or error message. + * @param apexModel The model name + * @param forceFlag true if we are forcing the update + * @param currentModel the existing model that is loaded + * @throws ContextException on compatibility errors + */ + private void handleIncompatibility(final AxPolicyModel apexModel, final boolean forceFlag, + final AxPolicyModel currentModel) throws ContextException { + if (forceFlag) { + LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId() + + "\" is not a compatible model update from the existing engine model with key \"" + + currentModel.getKey().getId() + "\""); + } else { + throw new ContextException("apex model update failed, supplied model with key \"" + + apexModel.getKey().getId() + + "\" is not a compatible model update from the existing engine model with key \"" + + currentModel.getKey().getId() + "\""); + } + } + /* * (non-Javadoc) * @@ -446,8 +451,9 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + String message = ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX; + LOGGER.warn(message); + throw new ApexException(message); } // Start the engine @@ -487,8 +493,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Stop the engine @@ -528,8 +534,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Clear the engine @@ -566,7 +572,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public boolean isStarted(final AxArtifactKey engineKey) { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } return engineWorkerMap.get(engineKey).isStarted(); } @@ -597,7 +603,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public boolean isStopped(final AxArtifactKey engineKey) { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } return engineWorkerMap.get(engineKey).isStopped(); } @@ -611,10 +617,10 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public void startPeriodicEvents(final long period) throws ApexException { // Check if periodic events are already started if (periodicEventGenerator != null) { - LOGGER.warn("Peiodic event geneation already running on engine " + engineServiceKey.getId() + ", " - + periodicEventGenerator.toString()); - throw new ApexException("Peiodic event geneation already running on engine " + engineServiceKey.getId() - + ", " + periodicEventGenerator.toString()); + String message = "Peiodic event geneation already running on engine " + engineServiceKey.getId() + ", " + + periodicEventGenerator.toString(); + LOGGER.warn(message); + throw new ApexException(message); } // Set up periodic event execution, its a Java Timer/TimerTask @@ -653,8 +659,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public String getStatus(final AxArtifactKey engineKey) throws ApexException { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Return the information for this worker @@ -671,8 +677,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public String getRuntimeInfo(final AxArtifactKey engineKey) throws ApexException { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Return the information for this worker diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java index b9a405b44..dc5e91979 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java @@ -75,6 +75,13 @@ final class EngineWorker implements EngineService { // Logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineService.class); + // Recurring string constants + private static final String IS_NULL_SUFFIX = " is null"; + private static final String ENGINE_FOR_KEY_PREFIX = "apex engine for engine key "; + private static final String ENGINE_SUFFIX = " of this engine"; + private static final String BAD_KEY_MATCH_TAG = " does not match the key"; + private static final String ENGINE_KEY_PREFIX = "engine key "; + // The ID of this engine private final AxArtifactKey engineWorkerKey; @@ -102,7 +109,7 @@ final class EngineWorker implements EngineService { * @throws ApexException thrown on errors on worker instantiation */ EngineWorker(final AxArtifactKey engineWorkerKey, final BlockingQueue queue, - final ApplicationThreadFactory threadFactory) throws ApexException { + final ApplicationThreadFactory threadFactory) { LOGGER.entry(engineWorkerKey); this.engineWorkerKey = engineWorkerKey; @@ -252,10 +259,10 @@ final class EngineWorker implements EngineService { // Check if the key on the update request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + String message = ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX; + LOGGER.warn(message); + throw new ApexException(message); } // Sanity checks on the Apex model @@ -323,23 +330,24 @@ final class EngineWorker implements EngineService { // Check if the key on the start request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX); + throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + + engineWorkerKey.getId() + ENGINE_SUFFIX); } if (engine == null) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " null"); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() + " null"); + String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is null"; + LOGGER.error(message); + throw new ApexException(message); } // Starts the event processing thread that handles incoming events if (processorThread != null && processorThread.isAlive()) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " is already running with state " - + getState()); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() - + " is already running with state " + getState()); + String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already running with state " + + getState(); + LOGGER.error(message); + throw new ApexException(message); } // Start the engine @@ -373,22 +381,23 @@ final class EngineWorker implements EngineService { public void stop(final AxArtifactKey engineKey) throws ApexException { // Check if the key on the start request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX); + throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + + engineWorkerKey.getId() + ENGINE_SUFFIX); } if (engine == null) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " null"); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() + " null"); + String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is null"; + LOGGER.error(message); + throw new ApexException(message); } // Interrupt the worker to stop its thread if (processorThread == null || !processorThread.isAlive()) { processorThread = null; - LOGGER.warn("apex engine for engine key" + engineWorkerKey.getId() + " is already stopped with state " + LOGGER.warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already stopped with state " + getState()); return; } @@ -424,20 +433,20 @@ final class EngineWorker implements EngineService { public void clear(final AxArtifactKey engineKey) throws ApexException { // Check if the key on the start request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX); + throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + + engineWorkerKey.getId() + ENGINE_SUFFIX); } if (engine == null) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " null"); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() + " null"); + LOGGER.error(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + IS_NULL_SUFFIX); + throw new ApexException(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + IS_NULL_SUFFIX); } // Interrupt the worker to stop its thread if (processorThread != null && !processorThread.isAlive()) { - LOGGER.warn("apex engine for engine key" + engineWorkerKey.getId() + " is not stopped with state " + LOGGER.warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is not stopped with state " + getState()); return; } @@ -653,7 +662,7 @@ final class EngineWorker implements EngineService { final JsonElement jsonElement = jsonParser.parse(runtimeJsonStringBuilder.toString()); final String tidiedRuntimeString = gson.toJson(jsonElement); - LOGGER.debug("runtime information=" + tidiedRuntimeString); + LOGGER.debug("runtime information={}", tidiedRuntimeString); return tidiedRuntimeString; } @@ -691,7 +700,8 @@ final class EngineWorker implements EngineService { // Take events from the event processing queue of the worker and pass them to the engine // for processing - while (!processorThread.isInterrupted()) { + boolean stopFlag = false; + while (!processorThread.isInterrupted() && ! stopFlag) { ApexEvent event = null; try { event = eventProcessingQueue.take(); @@ -714,7 +724,7 @@ final class EngineWorker implements EngineService { LOGGER.warn("Engine {} failed to process event {}", engineWorkerKey, event.toString(), e); } catch (final Exception e) { LOGGER.warn("Engine {} terminated processing event {}", engineWorkerKey, event.toString(), e); - break; + stopFlag = true; } } LOGGER.debug("Engine {} completed processing", engineWorkerKey); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java index 2e8e66ae8..4312793e4 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java @@ -20,18 +20,18 @@ package org.onap.policy.apex.service.parameters; -import java.io.FileReader; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.io.FileReader; + import org.onap.policy.apex.core.engine.EngineParameters; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParametersJSONAdapter; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParametersJSONAdapter; +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParametersJsonAdapter; +import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParametersJsonAdapter; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParametersJSONAdapter; +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParametersJsonAdapter; import org.onap.policy.common.parameters.GroupValidationResult; import org.onap.policy.common.parameters.ParameterException; import org.onap.policy.common.parameters.ParameterService; @@ -56,7 +56,7 @@ public class ApexParameterHandler { public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ParameterException { // Clear all existing parameters ParameterService.clear(); - + ApexParameters parameters = null; // Read the parameters @@ -65,11 +65,11 @@ public class ApexParameterHandler { // @formatter:off final Gson gson = new GsonBuilder() .registerTypeAdapter(EngineParameters .class, - new EngineServiceParametersJSONAdapter()) + new EngineServiceParametersJsonAdapter()) .registerTypeAdapter(CarrierTechnologyParameters.class, - new CarrierTechnologyParametersJSONAdapter()) + new CarrierTechnologyParametersJsonAdapter()) .registerTypeAdapter(EventProtocolParameters .class, - new EventProtocolParametersJSONAdapter()) + new EventProtocolParametersJsonAdapter()) .create(); // @formatter:on parameters = gson.fromJson(new FileReader(arguments.getFullConfigurationFilePath()), ApexParameters.class); @@ -114,12 +114,13 @@ public class ApexParameterHandler { // Register the parameters with the parameter service registerParameters(parameters); - + return parameters; } /** - * Register all the incoming parameters with the parameter service + * Register all the incoming parameters with the parameter service. + * * @param parameters The parameters to register */ private void registerParameters(ApexParameters parameters) { @@ -127,9 +128,13 @@ public class ApexParameterHandler { ParameterService.register(parameters.getEngineServiceParameters()); ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters()); ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()); - ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getSchemaParameters()); - ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getDistributorParameters()); - ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getLockManagerParameters()); - ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getPersistorParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters() + .getSchemaParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters() + .getDistributorParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters() + .getLockManagerParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters() + .getPersistorParameters()); } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java index 87b86a897..907baad40 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java @@ -37,16 +37,11 @@ import org.onap.policy.common.parameters.ValidationStatus; /** * The main container parameter class for an Apex service. * - *

    - * The following parameters are defined: - *

      - *
    1. engineServiceParameters: The parameters for the Apex engine service itself, such as the number of engine threads - * to run and the deployment port number to use. - *
    2. eventOutputParameters: A map of parameters for event outputs that Apex will use to emit events. Apex emits events - * on all outputs + *

      The following parameters are defined:

      1. engineServiceParameters: The parameters for the Apex engine service + * itself, such as the number of engine threads to run and the deployment port number to use.
      2. eventOutputParameters: + * A map of parameters for event outputs that Apex will use to emit events. Apex emits events on all outputs *
      3. eventInputParameters: A map or parameters for event inputs from which Apex will consume events. Apex reads events - * from all its event inputs. - *
      + * from all its event inputs.
    * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -59,13 +54,13 @@ public class ApexParameters implements ParameterGroup { private static final String EVENT_INPUT_PARAMETERS_STRING = "eventInputParameters"; private static final String EVENT_OUTPUT_PARAMETERS_STRING = "eventOutputParameters"; private static final String FOR_PEERED_MODE_STRING = " for peered mode "; - + /** * Constructor to create an apex parameters instance and register the instance with the parameter service. */ public ApexParameters() { super(); - + // Set the name for the parameters this.name = ApexParameterConstants.MAIN_GROUP_NAME; } @@ -235,9 +230,8 @@ public class ApexParameters implements ParameterGroup { } } else { if (peer != null) { - result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, - messagePreamble + " peer is illegal on " + eventHandlerType + " \"" - + parameterEntry.getKey() + "\" "); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, messagePreamble + + " peer is illegal on " + eventHandlerType + " \"" + parameterEntry.getKey() + "\" "); } if (parameterEntry.getValue().getPeerTimeout(peeredMode) != 0) { result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, @@ -315,10 +309,10 @@ public class ApexParameters implements ParameterGroup { final String rightSidePeer = rightModeParameters.getPeer(peeredMode); if (!rightSidePeer.equals(leftModeParameterEntry.getKey())) { result.setResult(handlerMapVariableName, leftModeParameterEntry.getKey(), ValidationStatus.INVALID, - PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + peeredMode - + ", value \"" + rightSidePeer + "\" on peer \"" + leftSidePeer - + "\" does not equal event handler \"" + leftModeParameterEntry.getKey() - + "\""); + PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + + peeredMode + ", value \"" + rightSidePeer + "\" on peer \"" + + leftSidePeer + "\" does not equal event handler \"" + + leftModeParameterEntry.getKey() + "\""); } else { // Check for duplicates if (!leftCheckDuplicateSet.add(leftSidePeer)) { @@ -339,12 +333,12 @@ public class ApexParameters implements ParameterGroup { if (!crossCheckPeeredTimeoutValues(leftModeParameters, rightModeParameters, peeredMode)) { result.setResult(handlerMapVariableName, leftModeParameterEntry.getKey(), ValidationStatus.INVALID, - PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + peeredMode - + " timeout " + leftModeParameters.getPeerTimeout(peeredMode) - + " on event handler \"" + leftModeParameters.getName() - + "\" does not equal timeout " - + rightModeParameters.getPeerTimeout(peeredMode) + " on event handler \"" - + rightModeParameters.getName() + "\""); + PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + + peeredMode + " timeout " + + leftModeParameters.getPeerTimeout(peeredMode) + " on event handler \"" + + leftModeParameters.getName() + "\" does not equal timeout " + + rightModeParameters.getPeerTimeout(peeredMode) + + " on event handler \"" + rightModeParameters.getName() + "\""); } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java index 593c6d86f..bab76b59b 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java @@ -29,14 +29,10 @@ import org.onap.policy.common.parameters.ValidationStatus; * The default carrier technology parameter class that may be specialized by carrier technology plugins that require * plugin specific parameters. * - *

    The following parameters are defined: - *

      - *
    1. label: The label of the carrier technology. + *

      The following parameters are defined:

      1. label: The label of the carrier technology. *
      2. eventProducerPluginClass: The name of the plugin class that will be used by Apex to produce and emit output - * events for this carrier technology - *
      3. eventConsumerPluginClass: The name of the plugin class that will be used by Apex to receive and process input - * events from this carrier technology carrier technology - *
      + * events for this carrier technology
    2. eventConsumerPluginClass: The name of the plugin class that will be used by + * Apex to receive and process input events from this carrier technology carrier technology
    * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -160,7 +156,7 @@ public abstract class CarrierTechnologyParameters implements ParameterGroup { return result; } - + @Override public String getName() { return this.getLabel(); @@ -168,7 +164,8 @@ public abstract class CarrierTechnologyParameters implements ParameterGroup { @Override public void setName(final String name) { - throw new ParameterRuntimeException("the name/label of this carrier technology is always \"" + getLabel() + "\""); + throw new ParameterRuntimeException( + "the name/label of this carrier technology is always \"" + getLabel() + "\""); } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java deleted file mode 100644 index b4e342f17..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java +++ /dev/null @@ -1,177 +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.parameters.carriertechnology; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -import org.onap.policy.apex.service.engine.event.impl.eventrequestor.EventRequestorCarrierTechnologyParameters; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters; -import org.onap.policy.common.parameters.ParameterRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class deserialises various type of carrier technology parameters from JSON. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CarrierTechnologyParametersJSONAdapter - implements JsonSerializer, JsonDeserializer { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(CarrierTechnologyParametersJSONAdapter.class); - - private static final String PARAMETER_CLASS_NAME = "parameterClassName"; - - private static final String CARRIER_TECHNOLOGY_TOKEN = "carrierTechnology"; - private static final String CARRIER_TECHNOLOGY_PARAMETERS = "parameters"; - - // Built in technology parameters - private static final Map BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP = new HashMap<>(); - - static { - BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("FILE", - FILECarrierTechnologyParameters.class.getCanonicalName()); - BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("EVENT_REQUESTOR", - EventRequestorCarrierTechnologyParameters.class.getCanonicalName()); - } - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, - * com.google.gson.JsonSerializationContext) - */ - @Override - public JsonElement serialize(final CarrierTechnologyParameters src, final Type typeOfSrc, - final JsonSerializationContext context) { - final String returnMessage = "serialization of Apex carrier technology parameters to Json is not supported"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, - * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) - */ - @Override - public CarrierTechnologyParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) { - final JsonObject jsonObject = json.getAsJsonObject(); - - // Get the carrier technology label primitive - final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(CARRIER_TECHNOLOGY_TOKEN); - - // Check if we found our carrier technology - if (labelJsonPrimitive == null) { - LOGGER.warn("carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + "\" not found in JSON file"); - return null; - } - - // Get and check the carrier technology label - final String carrierTechnologyLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); - if (carrierTechnologyLabel == null || carrierTechnologyLabel.length() == 0) { - final String errorMessage = "carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + "\" value \"" - + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // We now get the technology carrier parameter class - String carrierTechnologyParameterClassName = null; - - // Get the technology carrier parameter class for the carrier technology plugin class from - // the configuration parameters - final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); - - // If no technology carrier parameter class was specified, we try to use a built in carrier - // technology - if (classNameJsonPrimitive == null) { - carrierTechnologyParameterClassName = - BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.get(carrierTechnologyLabel); - } else { - // We use the specified one - carrierTechnologyParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); - } - - // Check the carrier technology parameter class - if (carrierTechnologyParameterClassName == null || carrierTechnologyParameterClassName.length() == 0) { - final String errorMessage = "carrier technology \"" + carrierTechnologyLabel + "\" parameter \"" - + PARAMETER_CLASS_NAME + "\" value \"" - + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") - + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // Get the class for the carrier technology - Class carrierTechnologyParameterClass = null; - try { - carrierTechnologyParameterClass = Class.forName(carrierTechnologyParameterClassName); - } catch (final ClassNotFoundException e) { - final String errorMessage = - "carrier technology \"" + carrierTechnologyLabel + "\" parameter \"" + PARAMETER_CLASS_NAME - + "\" value \"" + carrierTechnologyParameterClassName + "\", could not find class"; - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - - // Deserialise the class - CarrierTechnologyParameters carrierTechnologyParameters = - context.deserialize(jsonObject.get(CARRIER_TECHNOLOGY_PARAMETERS), carrierTechnologyParameterClass); - if (carrierTechnologyParameters == null) { - // OK no parameters for the carrier technology have been specified, just instantiate the - // default parameters - try { - carrierTechnologyParameters = - (CarrierTechnologyParameters) carrierTechnologyParameterClass.newInstance(); - } catch (final Exception e) { - final String errorMessage = "could not create default parameters for carrier technology \"" - + carrierTechnologyLabel + "\"\n" + e.getMessage(); - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - } - - // Check that the carrier technology label matches the label in the carrier technology - // parameters object - if (!carrierTechnologyParameters.getLabel().equals(carrierTechnologyLabel)) { - final String errorMessage = "carrier technology \"" + carrierTechnologyLabel + "\" does not match plugin \"" - + carrierTechnologyParameters.getLabel() + "\" in \"" + carrierTechnologyParameterClassName - + "\", specify correct carrier technology parameter plugin in parameter \"" + PARAMETER_CLASS_NAME - + "\""; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - return carrierTechnologyParameters; - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJsonAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJsonAdapter.java new file mode 100644 index 000000000..5e320b1bb --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJsonAdapter.java @@ -0,0 +1,184 @@ +/*- + * ============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.parameters.carriertechnology; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import org.onap.policy.apex.service.engine.event.impl.eventrequestor.EventRequestorCarrierTechnologyParameters; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; +import org.onap.policy.common.parameters.ParameterRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class deserialises various type of carrier technology parameters from JSON. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CarrierTechnologyParametersJsonAdapter + implements JsonSerializer, JsonDeserializer { + + private static final XLogger LOGGER = XLoggerFactory.getXLogger(CarrierTechnologyParametersJsonAdapter.class); + + // Recurring string constants + private static final String VALUE_TAG = "\" value \""; + private static final String CARRIER_TECHNOLOGY_PREAMBLE = "carrier technology \""; + + + private static final String PARAMETER_CLASS_NAME = "parameterClassName"; + + private static final String CARRIER_TECHNOLOGY_TOKEN = "carrierTechnology"; + private static final String CARRIER_TECHNOLOGY_PARAMETERS = "parameters"; + + // Built in technology parameters + private static final Map BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP = new HashMap<>(); + + static { + BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("FILE", + FileCarrierTechnologyParameters.class.getCanonicalName()); + BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("EVENT_REQUESTOR", + EventRequestorCarrierTechnologyParameters.class.getCanonicalName()); + } + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, + * com.google.gson.JsonSerializationContext) + */ + @Override + public JsonElement serialize(final CarrierTechnologyParameters src, final Type typeOfSrc, + final JsonSerializationContext context) { + final String returnMessage = "serialization of Apex carrier technology parameters to Json is not supported"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, + * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) + */ + @Override + public CarrierTechnologyParameters deserialize(final JsonElement json, final Type typeOfT, + final JsonDeserializationContext context) { + final JsonObject jsonObject = json.getAsJsonObject(); + + // Get the carrier technology label primitive + final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(CARRIER_TECHNOLOGY_TOKEN); + + // Check if we found our carrier technology + if (labelJsonPrimitive == null) { + LOGGER.warn("carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + "\" not found in JSON file"); + return null; + } + + // Get and check the carrier technology label + final String carrierTechnologyLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); + if (carrierTechnologyLabel == null || carrierTechnologyLabel.length() == 0) { + final String errorMessage = "carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + VALUE_TAG + + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // We now get the technology carrier parameter class + String carrierTechnologyParameterClassName = null; + + // Get the technology carrier parameter class for the carrier technology plugin class from + // the configuration parameters + final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); + + // If no technology carrier parameter class was specified, we try to use a built in carrier + // technology + if (classNameJsonPrimitive == null) { + carrierTechnologyParameterClassName = + BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.get(carrierTechnologyLabel); + } else { + // We use the specified one + carrierTechnologyParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); + } + + // Check the carrier technology parameter class + if (carrierTechnologyParameterClassName == null || carrierTechnologyParameterClassName.length() == 0) { + final String errorMessage = CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel + "\" parameter \"" + + PARAMETER_CLASS_NAME + VALUE_TAG + + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") + + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // Get the class for the carrier technology + Class carrierTechnologyParameterClass = null; + try { + carrierTechnologyParameterClass = Class.forName(carrierTechnologyParameterClassName); + } catch (final ClassNotFoundException e) { + final String errorMessage = + CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + + VALUE_TAG + carrierTechnologyParameterClassName + "\", could not find class"; + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + + // Deserialise the class + CarrierTechnologyParameters carrierTechnologyParameters = + context.deserialize(jsonObject.get(CARRIER_TECHNOLOGY_PARAMETERS), carrierTechnologyParameterClass); + if (carrierTechnologyParameters == null) { + // OK no parameters for the carrier technology have been specified, just instantiate the + // default parameters + try { + carrierTechnologyParameters = + (CarrierTechnologyParameters) carrierTechnologyParameterClass.newInstance(); + } catch (final Exception e) { + final String errorMessage = "could not create default parameters for carrier technology \"" + + carrierTechnologyLabel + "\"\n" + e.getMessage(); + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + } + + // Check that the carrier technology label matches the label in the carrier technology + // parameters object + if (!carrierTechnologyParameters.getLabel().equals(carrierTechnologyLabel)) { + final String errorMessage = CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel + + "\" does not match plugin \"" + + carrierTechnologyParameters.getLabel() + "\" in \"" + carrierTechnologyParameterClassName + + "\", specify correct carrier technology parameter plugin in parameter \"" + PARAMETER_CLASS_NAME + + "\""; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + return carrierTechnologyParameters; + } +} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java index ba065d3ef..faa6d79b3 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java @@ -23,6 +23,7 @@ package org.onap.policy.apex.service.parameters.engineservice; import java.io.File; import java.net.URL; +import org.onap.policy.apex.core.engine.EngineParameters; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.basicmodel.concepts.AxKey; import org.onap.policy.apex.service.parameters.ApexParameterConstants; @@ -31,8 +32,6 @@ import org.onap.policy.common.parameters.ParameterGroup; import org.onap.policy.common.parameters.ValidationStatus; import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.apex.core.engine.EngineParameters; - /** * This class holds the parameters for an Apex Engine Service with multiple engine threads running multiple engines. * @@ -315,7 +314,7 @@ public class EngineServiceParameters implements ParameterGroup { } /** - * Validate the policy model file name parameter + * Validate the policy model file name parameter. * @param result the variable in which to store the result of the validation */ private void validatePolicyModelFileName(final GroupValidationResult result) { @@ -327,11 +326,11 @@ public class EngineServiceParameters implements ParameterGroup { // The file name can refer to a resource on the local file system or on the class // path - final URL fileURL = ResourceUtils.getUrl4Resource(policyModelFileName); - if (fileURL == null) { + final URL fileUrl = ResourceUtils.getUrl4Resource(policyModelFileName); + if (fileUrl == null) { result.setResult(POLICY_MODEL_FILE_NAME, ValidationStatus.INVALID, "not found or is not a plain file"); } else { - final File policyModelFile = new File(fileURL.getPath()); + final File policyModelFile = new File(fileUrl.getPath()); if (!policyModelFile.isFile()) { result.setResult(POLICY_MODEL_FILE_NAME, ValidationStatus.INVALID, "not found or is not a plain file"); } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java deleted file mode 100644 index 50f4925f3..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java +++ /dev/null @@ -1,283 +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.parameters.engineservice; - -import java.lang.reflect.Type; -import java.util.Map.Entry; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -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.DistributorParameters; -import org.onap.policy.apex.context.parameters.LockManagerParameters; -import org.onap.policy.apex.context.parameters.PersistorParameters; -import org.onap.policy.apex.context.parameters.SchemaHelperParameters; -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.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class deserializes engine service parameters from JSON format. The class produces an - * {@link EngineServiceParameters} instance from incoming JSON read from a configuration file in JSON format. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EngineServiceParametersJSONAdapter - implements JsonSerializer, JsonDeserializer { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceParametersJSONAdapter.class); - - private static final String PARAMETER_CLASS_NAME = "parameterClassName"; - - // @formatter:off - private static final String CONTEXT_PARAMETERS = "contextParameters"; - private static final String DISTRIBUTOR_PARAMETERS = "distributorParameters"; - private static final String LOCK_MANAGER_PARAMETERS = "lockManagerParameters"; - private static final String PERSISTOR_PARAMETERS = "persistorParameters"; - private static final String SCHEMA_PARAMETERS = "schemaParameters"; - private static final String EXECUTOR_PARAMETERS = "executorParameters"; - // @formatter:on - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, - * com.google.gson.JsonSerializationContext) - */ - @Override - public JsonElement serialize(final EngineParameters src, final Type typeOfSrc, - final JsonSerializationContext context) { - final String returnMessage = "serialization of Apex parameters to Json is not supported"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, - * com.google.gson.JsonDeserializationContext) - */ - @Override - public EngineParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) { - final JsonObject engineParametersJsonObject = json.getAsJsonObject(); - - final EngineParameters engineParameters = new EngineParameters(); - - // Deserialise context parameters, they may be a subclass of the ContextParameters class - engineParameters.setContextParameters( - (ContextParameters) context.deserialize(engineParametersJsonObject, ContextParameters.class)); - - // Context parameter wrangling - getContextParameters(engineParametersJsonObject, engineParameters, context); - - // Executor parameter wrangling - getExecutorParameters(engineParametersJsonObject, engineParameters, context); - - return engineParameters; - } - - /** - * Get the context parameters for Apex. - * - * @param engineParametersJsonObject The input JSON - * @param engineParameters The output parameters - * @param context the JSON context - */ - private void getContextParameters(final JsonObject engineParametersJsonObject, - final EngineParameters engineParameters, final JsonDeserializationContext context) { - final JsonElement contextParametersElement = engineParametersJsonObject.get(CONTEXT_PARAMETERS); - - // Context parameters are optional so if the element does not exist, just return - if (contextParametersElement == null) { - return; - } - - // We do this because the JSON parameters may be for a subclass of ContextParameters - final ContextParameters contextParameters = (ContextParameters) deserializeParameters(CONTEXT_PARAMETERS, - contextParametersElement, context); - - // We know this will work because if the context parameters was not a Json object, the - // previous deserializeParameters() call would not have worked - final JsonObject contextParametersObject = engineParametersJsonObject.get(CONTEXT_PARAMETERS).getAsJsonObject(); - - // Now get the distributor, lock manager, and persistence parameters - final JsonElement distributorParametersElement = contextParametersObject.get(DISTRIBUTOR_PARAMETERS); - if (distributorParametersElement != null) { - contextParameters.setDistributorParameters((DistributorParameters) deserializeParameters( - DISTRIBUTOR_PARAMETERS, distributorParametersElement, context)); - } - - final JsonElement lockManagerParametersElement = contextParametersObject.get(LOCK_MANAGER_PARAMETERS); - if (lockManagerParametersElement != null) { - contextParameters.setLockManagerParameters((LockManagerParameters) deserializeParameters( - LOCK_MANAGER_PARAMETERS, lockManagerParametersElement, context)); - } - - final JsonElement persistorParametersElement = contextParametersObject.get(PERSISTOR_PARAMETERS); - if (persistorParametersElement != null) { - contextParameters.setPersistorParameters((PersistorParameters) deserializeParameters(PERSISTOR_PARAMETERS, - persistorParametersElement, context)); - } - - // Schema Handler parameter wrangling - getSchemaHandlerParameters(contextParametersObject, contextParameters, context); - - // Get the engine plugin parameters - engineParameters.setContextParameters(contextParameters); - } - - /** - * Get the executor parameters for Apex. - * - * @param engineParametersJsonObject The input JSON - * @param engineParameters The output parameters - * @param context the JSON context - */ - private void getExecutorParameters(final JsonObject engineParametersJsonObject, - final EngineParameters engineParameters, final JsonDeserializationContext context) { - final JsonElement executorParametersElement = engineParametersJsonObject.get(EXECUTOR_PARAMETERS); - - // Executor parameters are mandatory so if the element does not exist throw an exception - if (executorParametersElement == null) { - final String returnMessage = "no \"" + EXECUTOR_PARAMETERS - + "\" entry found in parameters, at least one executor parameter entry must be specified"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Deserialize the executor parameters - final JsonObject executorParametersJsonObject = engineParametersJsonObject.get(EXECUTOR_PARAMETERS) - .getAsJsonObject(); - - for (final Entry executorEntries : executorParametersJsonObject.entrySet()) { - final ExecutorParameters executorParameters = (ExecutorParameters) deserializeParameters( - EXECUTOR_PARAMETERS + ':' + executorEntries.getKey(), executorEntries.getValue(), context); - engineParameters.getExecutorParameterMap().put(executorEntries.getKey(), executorParameters); - } - } - - /** - * Get the schema parameters for Apex. - * - * @param contextParametersJsonObject The input JSON - * @param contextParameters The output parameters - * @param context the JSON context - */ - private void getSchemaHandlerParameters(final JsonObject contextParametersJsonObject, - final ContextParameters contextParameters, final JsonDeserializationContext context) { - final JsonElement schemaParametersElement = contextParametersJsonObject.get(SCHEMA_PARAMETERS); - - // Insert the default Java schema helper - contextParameters.getSchemaParameters().getSchemaHelperParameterMap() - .put(SchemaParameters.DEFAULT_SCHEMA_FLAVOUR, new JavaSchemaHelperParameters()); - - // Context parameters are optional so if the element does not exist, just return - if (schemaParametersElement == null) { - return; - } - - // Deserialize the executor parameters - final JsonObject schemaHelperParametersJsonObject = contextParametersJsonObject.get(SCHEMA_PARAMETERS) - .getAsJsonObject(); - - for (final Entry schemaHelperEntries : schemaHelperParametersJsonObject.entrySet()) { - contextParameters.getSchemaParameters().getSchemaHelperParameterMap().put(schemaHelperEntries.getKey(), - (SchemaHelperParameters) deserializeParameters( - SCHEMA_PARAMETERS + ':' + schemaHelperEntries.getKey(), - schemaHelperEntries.getValue(), context)); - } - } - - /** - * Deserialize a parameter object that's a superclass of the AbstractParameters class. - * - * @param parametersLabel Label to use for error messages - * @param parametersElement The JSON object holding the parameters - * @param context The GSON context - * @return the parameters - * @throws ParameterRuntimeException on errors reading the parameters - */ - private ParameterGroup deserializeParameters(final String parametersLabel, final JsonElement parametersElement, - final JsonDeserializationContext context) { - JsonObject parametersObject = null; - - // Check that the JSON element is a JSON object - if (parametersElement.isJsonObject()) { - parametersObject = parametersElement.getAsJsonObject(); - } else { - final String returnMessage = "value of \"" + parametersLabel + "\" entry is not a parameter JSON object"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Get the parameter class name for instantiation in deserialization - final JsonElement parameterClassNameElement = parametersObject.get(PARAMETER_CLASS_NAME); - if (parameterClassNameElement == null) { - final String returnMessage = "could not find field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel - + "\" entry"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Check the parameter is a JSON primitive - if (!parameterClassNameElement.isJsonPrimitive()) { - final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" of \"" + parametersLabel - + "\" entry is not a plain string"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Check the parameter has a value - final String parameterClassName = parameterClassNameElement.getAsString(); - if (parameterClassName == null || parameterClassName.trim().length() == 0) { - final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel - + "\" entry is not specified or is blank"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Deserialize the parameters using GSON - ParameterGroup parameters = null; - try { - parameters = context.deserialize(parametersObject, Class.forName(parameterClassName)); - } catch (JsonParseException | ClassNotFoundException e) { - final String returnMessage = "failed to deserialize the parameters for \"" + parametersLabel + "\" " - + "to parameter class \"" + parameterClassName + "\"\n" + e.getClass().getCanonicalName() - + ": " + e.getMessage(); - LOGGER.error(returnMessage, e); - throw new ParameterRuntimeException(returnMessage, e); - } - - return parameters; - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJsonAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJsonAdapter.java new file mode 100644 index 000000000..06cbd416f --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJsonAdapter.java @@ -0,0 +1,283 @@ +/*- + * ============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.parameters.engineservice; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.Map.Entry; + +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.DistributorParameters; +import org.onap.policy.apex.context.parameters.LockManagerParameters; +import org.onap.policy.apex.context.parameters.PersistorParameters; +import org.onap.policy.apex.context.parameters.SchemaHelperParameters; +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.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ParameterRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class deserializes engine service parameters from JSON format. The class produces an + * {@link EngineServiceParameters} instance from incoming JSON read from a configuration file in JSON format. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EngineServiceParametersJsonAdapter + implements JsonSerializer, JsonDeserializer { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceParametersJsonAdapter.class); + + private static final String PARAMETER_CLASS_NAME = "parameterClassName"; + + // @formatter:off + private static final String CONTEXT_PARAMETERS = "contextParameters"; + private static final String DISTRIBUTOR_PARAMETERS = "distributorParameters"; + private static final String LOCK_MANAGER_PARAMETERS = "lockManagerParameters"; + private static final String PERSISTOR_PARAMETERS = "persistorParameters"; + private static final String SCHEMA_PARAMETERS = "schemaParameters"; + private static final String EXECUTOR_PARAMETERS = "executorParameters"; + // @formatter:on + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, + * com.google.gson.JsonSerializationContext) + */ + @Override + public JsonElement serialize(final EngineParameters src, final Type typeOfSrc, + final JsonSerializationContext context) { + final String returnMessage = "serialization of Apex parameters to Json is not supported"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, + * com.google.gson.JsonDeserializationContext) + */ + @Override + public EngineParameters deserialize(final JsonElement json, final Type typeOfT, + final JsonDeserializationContext context) { + final JsonObject engineParametersJsonObject = json.getAsJsonObject(); + + final EngineParameters engineParameters = new EngineParameters(); + + // Deserialise context parameters, they may be a subclass of the ContextParameters class + engineParameters.setContextParameters( + (ContextParameters) context.deserialize(engineParametersJsonObject, ContextParameters.class)); + + // Context parameter wrangling + getContextParameters(engineParametersJsonObject, engineParameters, context); + + // Executor parameter wrangling + getExecutorParameters(engineParametersJsonObject, engineParameters, context); + + return engineParameters; + } + + /** + * Get the context parameters for Apex. + * + * @param engineParametersJsonObject The input JSON + * @param engineParameters The output parameters + * @param context the JSON context + */ + private void getContextParameters(final JsonObject engineParametersJsonObject, + final EngineParameters engineParameters, final JsonDeserializationContext context) { + final JsonElement contextParametersElement = engineParametersJsonObject.get(CONTEXT_PARAMETERS); + + // Context parameters are optional so if the element does not exist, just return + if (contextParametersElement == null) { + return; + } + + // We do this because the JSON parameters may be for a subclass of ContextParameters + final ContextParameters contextParameters = (ContextParameters) deserializeParameters(CONTEXT_PARAMETERS, + contextParametersElement, context); + + // We know this will work because if the context parameters was not a Json object, the + // previous deserializeParameters() call would not have worked + final JsonObject contextParametersObject = engineParametersJsonObject.get(CONTEXT_PARAMETERS).getAsJsonObject(); + + // Now get the distributor, lock manager, and persistence parameters + final JsonElement distributorParametersElement = contextParametersObject.get(DISTRIBUTOR_PARAMETERS); + if (distributorParametersElement != null) { + contextParameters.setDistributorParameters((DistributorParameters) deserializeParameters( + DISTRIBUTOR_PARAMETERS, distributorParametersElement, context)); + } + + final JsonElement lockManagerParametersElement = contextParametersObject.get(LOCK_MANAGER_PARAMETERS); + if (lockManagerParametersElement != null) { + contextParameters.setLockManagerParameters((LockManagerParameters) deserializeParameters( + LOCK_MANAGER_PARAMETERS, lockManagerParametersElement, context)); + } + + final JsonElement persistorParametersElement = contextParametersObject.get(PERSISTOR_PARAMETERS); + if (persistorParametersElement != null) { + contextParameters.setPersistorParameters((PersistorParameters) deserializeParameters(PERSISTOR_PARAMETERS, + persistorParametersElement, context)); + } + + // Schema Handler parameter wrangling + getSchemaHandlerParameters(contextParametersObject, contextParameters, context); + + // Get the engine plugin parameters + engineParameters.setContextParameters(contextParameters); + } + + /** + * Get the executor parameters for Apex. + * + * @param engineParametersJsonObject The input JSON + * @param engineParameters The output parameters + * @param context the JSON context + */ + private void getExecutorParameters(final JsonObject engineParametersJsonObject, + final EngineParameters engineParameters, final JsonDeserializationContext context) { + final JsonElement executorParametersElement = engineParametersJsonObject.get(EXECUTOR_PARAMETERS); + + // Executor parameters are mandatory so if the element does not exist throw an exception + if (executorParametersElement == null) { + final String returnMessage = "no \"" + EXECUTOR_PARAMETERS + + "\" entry found in parameters, at least one executor parameter entry must be specified"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Deserialize the executor parameters + final JsonObject executorParametersJsonObject = engineParametersJsonObject.get(EXECUTOR_PARAMETERS) + .getAsJsonObject(); + + for (final Entry executorEntries : executorParametersJsonObject.entrySet()) { + final ExecutorParameters executorParameters = (ExecutorParameters) deserializeParameters( + EXECUTOR_PARAMETERS + ':' + executorEntries.getKey(), executorEntries.getValue(), context); + engineParameters.getExecutorParameterMap().put(executorEntries.getKey(), executorParameters); + } + } + + /** + * Get the schema parameters for Apex. + * + * @param contextParametersJsonObject The input JSON + * @param contextParameters The output parameters + * @param context the JSON context + */ + private void getSchemaHandlerParameters(final JsonObject contextParametersJsonObject, + final ContextParameters contextParameters, final JsonDeserializationContext context) { + final JsonElement schemaParametersElement = contextParametersJsonObject.get(SCHEMA_PARAMETERS); + + // Insert the default Java schema helper + contextParameters.getSchemaParameters().getSchemaHelperParameterMap() + .put(SchemaParameters.DEFAULT_SCHEMA_FLAVOUR, new JavaSchemaHelperParameters()); + + // Context parameters are optional so if the element does not exist, just return + if (schemaParametersElement == null) { + return; + } + + // Deserialize the executor parameters + final JsonObject schemaHelperParametersJsonObject = contextParametersJsonObject.get(SCHEMA_PARAMETERS) + .getAsJsonObject(); + + for (final Entry schemaHelperEntries : schemaHelperParametersJsonObject.entrySet()) { + contextParameters.getSchemaParameters().getSchemaHelperParameterMap().put(schemaHelperEntries.getKey(), + (SchemaHelperParameters) deserializeParameters( + SCHEMA_PARAMETERS + ':' + schemaHelperEntries.getKey(), + schemaHelperEntries.getValue(), context)); + } + } + + /** + * Deserialize a parameter object that's a superclass of the AbstractParameters class. + * + * @param parametersLabel Label to use for error messages + * @param parametersElement The JSON object holding the parameters + * @param context The GSON context + * @return the parameters + * @throws ParameterRuntimeException on errors reading the parameters + */ + private ParameterGroup deserializeParameters(final String parametersLabel, final JsonElement parametersElement, + final JsonDeserializationContext context) { + JsonObject parametersObject = null; + + // Check that the JSON element is a JSON object + if (parametersElement.isJsonObject()) { + parametersObject = parametersElement.getAsJsonObject(); + } else { + final String returnMessage = "value of \"" + parametersLabel + "\" entry is not a parameter JSON object"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Get the parameter class name for instantiation in deserialization + final JsonElement parameterClassNameElement = parametersObject.get(PARAMETER_CLASS_NAME); + if (parameterClassNameElement == null) { + final String returnMessage = "could not find field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel + + "\" entry"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Check the parameter is a JSON primitive + if (!parameterClassNameElement.isJsonPrimitive()) { + final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" of \"" + parametersLabel + + "\" entry is not a plain string"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Check the parameter has a value + final String parameterClassName = parameterClassNameElement.getAsString(); + if (parameterClassName == null || parameterClassName.trim().length() == 0) { + final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel + + "\" entry is not specified or is blank"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Deserialize the parameters using GSON + ParameterGroup parameters = null; + try { + parameters = context.deserialize(parametersObject, Class.forName(parameterClassName)); + } catch (JsonParseException | ClassNotFoundException e) { + final String returnMessage = "failed to deserialize the parameters for \"" + parametersLabel + "\" " + + "to parameter class \"" + parameterClassName + "\"\n" + e.getClass().getCanonicalName() + + ": " + e.getMessage(); + LOGGER.error(returnMessage, e); + throw new ParameterRuntimeException(returnMessage, e); + } + + return parameters; + } +} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java index 996899052..afd877fd2 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java @@ -33,26 +33,20 @@ import org.onap.policy.common.parameters.ValidationStatus; /** * The parameters for a single event producer, event consumer or synchronous event handler. * - *

    Event producers, consumers, and synchronous event handlers all use a carrier technology and an event protocol so the - * actual parameters for each one are the same. Therefore, we use the same class for the parameters of each one. + *

    Event producers, consumers, and synchronous event handlers all use a carrier technology and an event protocol so + * the actual parameters for each one are the same. Therefore, we use the same class for the parameters of each one. * - *

    The following parameters are defined: - *

      - *
    1. carrierTechnologyParameters: The carrier technology is the type of messaging infrastructure used to carry events. - * Examples are File, Kafka or REST. - *
    2. eventProtocolParameters: The format that the events are in when being carried. Examples are JSON, XML, or Java - * Beans. carrier technology - *
    3. synchronousMode: true if the event handler is working in synchronous mode, defaults to false - *
    4. synchronousPeer: the peer event handler (consumer for producer or producer for consumer) of this event handler in - * synchronous mode + *

      The following parameters are defined:

      1. carrierTechnologyParameters: The carrier technology is the type of + * messaging infrastructure used to carry events. Examples are File, Kafka or REST.
      2. eventProtocolParameters: The + * format that the events are in when being carried. Examples are JSON, XML, or Java Beans. carrier technology + *
      3. synchronousMode: true if the event handler is working in synchronous mode, defaults to false
      4. synchronousPeer: + * the peer event handler (consumer for producer or producer for consumer) of this event handler in synchronous mode *
      5. synchronousTimeout: the amount of time to wait for the reply to synchronous events before they are timed out - *
      6. requestorMode: true if the event handler is working in requestor mode, defaults to false - *
      7. requestorPeer: the peer event handler (consumer for producer or producer for consumer) of this event handler in - * requestor mode + *
      8. requestorMode: true if the event handler is working in requestor mode, defaults to false
      9. requestorPeer: the + * peer event handler (consumer for producer or producer for consumer) of this event handler in requestor mode *
      10. requestorTimeout: the amount of time to wait for the reply to synchronous events before they are timed out *
      11. eventNameFilter: a regular expression to apply to events on this event handler. If specified, events not matching - * the given regular expression are ignored. If it is null, all events are handledDefaults to null. - *
      + * the given regular expression are ignored. If it is null, all events are handledDefaults to null.
    * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -340,7 +334,7 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * Check if we're using synchronous mode + * Check if we're using synchronous mode. * * @return true if if we're using synchronous mode */ @@ -349,7 +343,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * The synchronous peer for this event handler + * The synchronous peer for this event handler. + * * @return the synchronous peer for this event handler */ public String getSynchronousPeer() { @@ -357,7 +352,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * Get the timeout for synchronous operations + * Get the timeout for synchronous operations. + * * @return the timeout for synchronous operations */ public long getSynchronousTimeout() { @@ -365,7 +361,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * Check if this event handler will use requestor mode + * Check if this event handler will use requestor mode. + * * @return true if this event handler will use requestor mode */ public boolean isRequestorMode() { @@ -373,7 +370,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * The requestor peer for this event handler + * The requestor peer for this event handler. + * * @return the requestor peer for this event handler */ public String getRequestorPeer() { @@ -381,7 +379,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * @return the requestorTimeout + * Get the requestor timeout. + * @return the requestorTimeout. */ public long getRequestorTimeout() { return requestorTimeout; diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java deleted file mode 100644 index 645368509..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java +++ /dev/null @@ -1,173 +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.parameters.eventprotocol; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -import org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin.ApexEventProtocolParameters; -import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters; -import org.onap.policy.common.parameters.ParameterRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class serialises and deserialises various type of event protocol parameters to and from - * JSON. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EventProtocolParametersJSONAdapter - implements JsonSerializer, JsonDeserializer { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProtocolParametersJSONAdapter.class); - - private static final String PARAMETER_CLASS_NAME = "parameterClassName"; - - private static final String EVENT_PROTOCOL_TOKEN = "eventProtocol"; - private static final String EVENT_PROTOCOL_PARAMETERS = "parameters"; - - // Built in event protocol parameters - private static final Map BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP = new HashMap<>(); - - static { - BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("JSON", JSONEventProtocolParameters.class.getCanonicalName()); - BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName()); - } - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, - * com.google.gson.JsonSerializationContext) - */ - @Override - public JsonElement serialize(final EventProtocolParameters src, final Type typeOfSrc, - final JsonSerializationContext context) { - final String returnMessage = "serialization of Apex event protocol parameters to Json is not supported"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, - * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) - */ - @Override - public EventProtocolParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) { - final JsonObject jsonObject = json.getAsJsonObject(); - - // Get the event protocol label primitive - final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(EVENT_PROTOCOL_TOKEN); - - // Check if we found our event protocol - if (labelJsonPrimitive == null) { - LOGGER.warn("event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" not found in JSON file"); - return null; - } - - // Get and check the event protocol label - final String eventProtocolLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); - if (eventProtocolLabel == null || eventProtocolLabel.length() == 0) { - final String errorMessage = "event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" value \"" - + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // We now get the event protocol parameter class - String eventProtocolParameterClassName = null; - - // Get the event protocol parameter class for the event protocol plugin class from the - // configuration parameters - final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); - - // If no event protocol parameter class was specified, we use the default - if (classNameJsonPrimitive == null) { - eventProtocolParameterClassName = BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel); - } else { - // We use the specified one - eventProtocolParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); - } - - // Check the event protocol parameter class - if (eventProtocolParameterClassName == null || eventProtocolParameterClassName.length() == 0) { - final String errorMessage = - "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \"" - + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") - + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // Get the class for the event protocol - Class eventProtocolParameterClass = null; - try { - eventProtocolParameterClass = Class.forName(eventProtocolParameterClassName); - } catch (final ClassNotFoundException e) { - final String errorMessage = - "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \"" - + eventProtocolParameterClassName + "\", could not find class"; - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - - // Deserialise the class - EventProtocolParameters eventProtocolParameters = - context.deserialize(jsonObject.get(EVENT_PROTOCOL_PARAMETERS), eventProtocolParameterClass); - if (eventProtocolParameters == null) { - // OK no parameters for the event protocol have been specified, just instantiate the - // default parameters - try { - eventProtocolParameters = (EventProtocolParameters) eventProtocolParameterClass.newInstance(); - } catch (final Exception e) { - final String errorMessage = "could not create default parameters for event protocol \"" - + eventProtocolLabel + "\"\n" + e.getMessage(); - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - } - - // Check that the event protocol label matches the label in the event protocol parameters - // object - if (!eventProtocolParameters.getLabel().equals(eventProtocolLabel)) { - final String errorMessage = "event protocol \"" + eventProtocolLabel + "\" does not match plugin \"" - + eventProtocolParameters.getLabel() + "\" in \"" + eventProtocolParameterClassName - + "\", specify correct event protocol parameter plugin in parameter \"" + PARAMETER_CLASS_NAME - + "\""; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - return eventProtocolParameters; - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJsonAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJsonAdapter.java new file mode 100644 index 000000000..ba37fe80c --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJsonAdapter.java @@ -0,0 +1,177 @@ +/*- + * ============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.parameters.eventprotocol; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin.ApexEventProtocolParameters; +import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; +import org.onap.policy.common.parameters.ParameterRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class serialises and deserialises various type of event protocol parameters to and from + * JSON. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EventProtocolParametersJsonAdapter + implements JsonSerializer, JsonDeserializer { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProtocolParametersJsonAdapter.class); + + // Recurring string constants + private static final String EVENT_PROTOCOL_PREFIX = "event protocol \""; + private static final String VALUE_TAG = "\" value \""; + + private static final String PARAMETER_CLASS_NAME = "parameterClassName"; + + private static final String EVENT_PROTOCOL_TOKEN = "eventProtocol"; + private static final String EVENT_PROTOCOL_PARAMETERS = "parameters"; + + // Built in event protocol parameters + private static final Map BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP = new HashMap<>(); + + static { + BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("JSON", JsonEventProtocolParameters.class.getCanonicalName()); + BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName()); + } + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, + * com.google.gson.JsonSerializationContext) + */ + @Override + public JsonElement serialize(final EventProtocolParameters src, final Type typeOfSrc, + final JsonSerializationContext context) { + final String returnMessage = "serialization of Apex event protocol parameters to Json is not supported"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, + * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) + */ + @Override + public EventProtocolParameters deserialize(final JsonElement json, final Type typeOfT, + final JsonDeserializationContext context) { + final JsonObject jsonObject = json.getAsJsonObject(); + + // Get the event protocol label primitive + final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(EVENT_PROTOCOL_TOKEN); + + // Check if we found our event protocol + if (labelJsonPrimitive == null) { + LOGGER.warn("event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" not found in JSON file"); + return null; + } + + // Get and check the event protocol label + final String eventProtocolLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); + if (eventProtocolLabel == null || eventProtocolLabel.length() == 0) { + final String errorMessage = "event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + VALUE_TAG + + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // We now get the event protocol parameter class + String eventProtocolParameterClassName = null; + + // Get the event protocol parameter class for the event protocol plugin class from the + // configuration parameters + final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); + + // If no event protocol parameter class was specified, we use the default + if (classNameJsonPrimitive == null) { + eventProtocolParameterClassName = BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel); + } else { + // We use the specified one + eventProtocolParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); + } + + // Check the event protocol parameter class + if (eventProtocolParameterClassName == null || eventProtocolParameterClassName.length() == 0) { + final String errorMessage = + EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + VALUE_TAG + + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") + + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // Get the class for the event protocol + Class eventProtocolParameterClass = null; + try { + eventProtocolParameterClass = Class.forName(eventProtocolParameterClassName); + } catch (final ClassNotFoundException e) { + final String errorMessage = + EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + VALUE_TAG + + eventProtocolParameterClassName + "\", could not find class"; + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + + // Deserialise the class + EventProtocolParameters eventProtocolParameters = + context.deserialize(jsonObject.get(EVENT_PROTOCOL_PARAMETERS), eventProtocolParameterClass); + if (eventProtocolParameters == null) { + // OK no parameters for the event protocol have been specified, just instantiate the + // default parameters + try { + eventProtocolParameters = (EventProtocolParameters) eventProtocolParameterClass.newInstance(); + } catch (final Exception e) { + final String errorMessage = "could not create default parameters for event protocol \"" + + eventProtocolLabel + "\"\n" + e.getMessage(); + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + } + + // Check that the event protocol label matches the label in the event protocol parameters + // object + if (!eventProtocolParameters.getLabel().equals(eventProtocolLabel)) { + final String errorMessage = EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" does not match plugin \"" + + eventProtocolParameters.getLabel() + "\" in \"" + eventProtocolParameterClassName + + "\", specify correct event protocol parameter plugin in parameter \"" + PARAMETER_CLASS_NAME + + "\""; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + return eventProtocolParameters; + } +} diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JSONEventGenerator.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JSONEventGenerator.java deleted file mode 100644 index 94210e473..000000000 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JSONEventGenerator.java +++ /dev/null @@ -1,444 +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.event; - -import java.util.Random; - -/** - * This class generates JSON event used for the test cases. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JSONEventGenerator { - private static int nextEventNo = 0; - - 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 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 != 1) { - System.err.println("usage EventGenerator #events"); - return; - } - - int eventCount = 0; - try { - eventCount = Integer.parseInt(args[0]); - } catch (final Exception e) { - System.err.println("usage EventGenerator #events"); - e.printStackTrace(); - return; - } - - System.out.println(jsonEvents(eventCount)); - } - - public static int getNextEventNo() { - return nextEventNo; - } -} diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventGenerator.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventGenerator.java new file mode 100644 index 000000000..1ba901090 --- /dev/null +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventGenerator.java @@ -0,0 +1,540 @@ +/*- + * ============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.event; + +import java.util.Random; + +/** + * This class generates JSON event used for the test cases. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JsonEventGenerator { + private static int nextEventNo = 0; + + /** + * 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(); + } + + /** + * 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 != 1) { + System.err.println("usage EventGenerator #events"); + return; + } + + int eventCount = 0; + try { + eventCount = Integer.parseInt(args[0]); + } catch (final Exception e) { + System.err.println("usage EventGenerator #events"); + e.printStackTrace(); + return; + } + + System.out.println(jsonEvents(eventCount)); + } + + /** + * Gets the next event no. + * + * @return the next event no + */ + public static int getNextEventNo() { + return nextEventNo; + } +} diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONEventHandler.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONEventHandler.java deleted file mode 100644 index 4f1089229..000000000 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONEventHandler.java +++ /dev/null @@ -1,328 +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.event; - -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.ByteArrayInputStream; -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.policy.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JSONEventConverter; -import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * Test JSON Event Handler. - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestJSONEventHandler { - private static final XLogger logger = XLoggerFactory.getXLogger(TestJSONEventHandler.class); - - @BeforeClass - public static void setupEventModel() throws IOException, ApexModelException { - final String policyModelString = - TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SamplePolicyModelMVEL.json"); - final ApexModelReader modelReader = new ApexModelReader(AxPolicyModel.class); - final AxPolicyModel apexPolicyModel = modelReader.read(new ByteArrayInputStream(policyModelString.getBytes())); - - // Set up the models in the model service - apexPolicyModel.register(); - } - - @BeforeClass - public static void initializeDefaultSchemaParameters() { - ParameterService.clear(); - final SchemaParameters schemaParameters = new SchemaParameters(); - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - ParameterService.register(schemaParameters); - } - - @AfterClass - public static void teardownDefaultSchemaParameters() { - ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); - } - - @Test - public void testJSONtoApexEvent() throws ApexException { - try { - final Apex2JSONEventConverter jsonEventConverter = new Apex2JSONEventConverter(); - assertNotNull(jsonEventConverter); - jsonEventConverter.init(new JSONEventProtocolParameters()); - - final String apexEventJSONStringIn = JSONEventGenerator.jsonEvent(); - - logger.debug("input event\n" + apexEventJSONStringIn); - - final List apexEventList = jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - for (final ApexEvent apexEvent : apexEventList) { - assertNotNull(apexEvent); - - logger.debug(apexEvent.toString()); - - assertTrue(apexEvent.getName().equals("Event0000") || apexEvent.getName().equals("Event0100")); - assertTrue(apexEvent.getVersion().equals("0.0.1")); - assertTrue(apexEvent.getNameSpace().equals("org.onap.policy.apex.sample.events")); - assertTrue(apexEvent.getSource().equals("test")); - assertTrue(apexEvent.getTarget().equals("apex")); - assertTrue(apexEvent.get("TestSlogan").toString().startsWith("Test slogan for External Event")); - - final Object testMatchCaseSelected = apexEvent.get("TestMatchCaseSelected"); - assertTrue(testMatchCaseSelected == null); - } - } catch (final Exception e) { - e.printStackTrace(); - throw new ApexException("Exception reading Apex event JSON file", e); - } - } - - @Test - public void testJSONtoApexBadEvent() throws ApexException { - try { - final Apex2JSONEventConverter jsonEventConverter = new Apex2JSONEventConverter(); - assertNotNull(jsonEventConverter); - jsonEventConverter.init(new JSONEventProtocolParameters()); - - String apexEventJSONStringIn = null; - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoName(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertEquals("Failed to unmarshal JSON event: event received without mandatory parameter \"name\" ", - e.getMessage().substring(0, 82)); - } - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventBadName(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage() - .startsWith("Failed to unmarshal JSON event: field \"name\" with value \"%%%%\" is invalid")); - } - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoExName(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertEquals("Failed to unmarshal JSON event: an event definition for an event named \"I_DONT_EXI", - e.getMessage().substring(0, 82)); - } - - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoVersion(); - ApexEvent event = jsonEventConverter.toApexEvent(null, apexEventJSONStringIn).get(0); - assertEquals("0.0.1", event.getVersion()); - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventBadVersion(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage().startsWith( - "Failed to unmarshal JSON event: field \"version\" with value \"#####\" is invalid")); - } - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoExVersion(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage().startsWith( - "Failed to unmarshal JSON event: an event definition for an event named " - + "\"Event0000\" with version \"1.2.3\" not found in Apex model")); - } - - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoNamespace(); - event = jsonEventConverter.toApexEvent(null, apexEventJSONStringIn).get(0); - assertEquals("org.onap.policy.apex.sample.events", event.getNameSpace()); - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventBadNamespace(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage().startsWith( - "Failed to unmarshal JSON event: field \"nameSpace\" with value \"hello.&&&&\" is invalid")); - } - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoExNamespace(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage().startsWith( - "Failed to unmarshal JSON event: namespace \"pie.in.the.sky\" on event \"Event0000\" does not" - + " match namespace \"org.onap.policy.apex.sample.events\" for that event in the Apex model")); - } - - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoSource(); - event = jsonEventConverter.toApexEvent(null, apexEventJSONStringIn).get(0); - assertEquals("Outside", event.getSource()); - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventBadSource(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage().startsWith( - "Failed to unmarshal JSON event: field \"source\" with value \"%!@**@!\" is invalid")); - } - - apexEventJSONStringIn = JSONEventGenerator.jsonEventNoTarget(); - event = jsonEventConverter.toApexEvent(null, apexEventJSONStringIn).get(0); - assertEquals("Match", event.getTarget()); - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventBadTarget(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage().startsWith( - "Failed to unmarshal JSON event: field \"target\" with value \"KNIO(*S)A(S)D\" is invalid")); - } - - try { - apexEventJSONStringIn = JSONEventGenerator.jsonEventMissingFields(); - jsonEventConverter.toApexEvent(null, apexEventJSONStringIn); - fail("Test should throw an exception here"); - } catch (final ApexEventException e) { - assertTrue(e.getMessage().startsWith("Failed to unmarshal JSON event: error parsing Event0000:0.0.1 " - + "event from Json. Field \"TestMatchCase\" is missing, but is mandatory.")); - } - - apexEventJSONStringIn = JSONEventGenerator.jsonEventNullFields(); - event = jsonEventConverter.toApexEvent(null, apexEventJSONStringIn).get(0); - assertEquals(event.get("TestSlogan"), null); - assertEquals(event.get("TestMatchCase"), (byte) -1); - assertEquals(event.get("TestTimestamp"), (long) -1); - assertEquals(event.get("TestTemperature"), -1.0); - - // Set the missing fields as optional in the model - final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get("Event0000"); - eventDefinition.getParameterMap().get("TestSlogan").setOptional(true); - eventDefinition.getParameterMap().get("TestMatchCase").setOptional(true); - eventDefinition.getParameterMap().get("TestTimestamp").setOptional(true); - eventDefinition.getParameterMap().get("TestTemperature").setOptional(true); - - apexEventJSONStringIn = JSONEventGenerator.jsonEventMissingFields(); - event = jsonEventConverter.toApexEvent(null, apexEventJSONStringIn).get(0); - assertEquals(null, event.get("TestSlogan")); - assertEquals(null, event.get("TestMatchCase")); - assertEquals(null, event.get("TestTimestamp")); - assertEquals(null, event.get("TestTemperature")); - } catch (final Exception e) { - e.printStackTrace(); - throw new ApexException("Exception reading Apex event JSON file", e); - } - } - - @Test - public void testApexEventToJSON() throws ApexException { - try { - final Apex2JSONEventConverter jsonEventConverter = new Apex2JSONEventConverter(); - assertNotNull(jsonEventConverter); - - final Date event0000StartTime = new Date(); - final Map event0000DataMap = new HashMap(); - event0000DataMap.put("TestSlogan", "This is a test slogan"); - event0000DataMap.put("TestMatchCase", 12345); - event0000DataMap.put("TestTimestamp", event0000StartTime.getTime()); - event0000DataMap.put("TestTemperature", 34.5445667); - - final ApexEvent apexEvent0000 = - new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.sample.events", "test", "apex"); - apexEvent0000.putAll(event0000DataMap); - - final String apexEvent0000JSONString = (String) jsonEventConverter.fromApexEvent(apexEvent0000); - - logger.debug(apexEvent0000JSONString); - - assertTrue(apexEvent0000JSONString.contains("\"name\": \"Event0000\"")); - assertTrue(apexEvent0000JSONString.contains("\"version\": \"0.0.1\"")); - assertTrue(apexEvent0000JSONString.contains("\"nameSpace\": \"org.onap.policy.apex.sample.events\"")); - assertTrue(apexEvent0000JSONString.contains("\"source\": \"test\"")); - assertTrue(apexEvent0000JSONString.contains("\"target\": \"apex\"")); - assertTrue(apexEvent0000JSONString.contains("\"TestSlogan\": \"This is a test slogan\"")); - assertTrue(apexEvent0000JSONString.contains("\"TestMatchCase\": 12345")); - assertTrue(apexEvent0000JSONString.contains("\"TestTimestamp\": " + event0000StartTime.getTime())); - assertTrue(apexEvent0000JSONString.contains("\"TestTemperature\": 34.5445667")); - - final Date event0004StartTime = new Date(1434363272000L); - final Map event0004DataMap = new HashMap(); - event0004DataMap.put("TestSlogan", "Test slogan for External Event"); - event0004DataMap.put("TestMatchCase", new Integer(2)); - event0004DataMap.put("TestTimestamp", new Long(event0004StartTime.getTime())); - event0004DataMap.put("TestTemperature", new Double(1064.43)); - event0004DataMap.put("TestMatchCaseSelected", new Integer(2)); - event0004DataMap.put("TestMatchStateTime", new Long(1434370506078L)); - event0004DataMap.put("TestEstablishCaseSelected", new Integer(0)); - event0004DataMap.put("TestEstablishStateTime", new Long(1434370506085L)); - event0004DataMap.put("TestDecideCaseSelected", new Integer(3)); - event0004DataMap.put("TestDecideStateTime", new Long(1434370506092L)); - event0004DataMap.put("TestActCaseSelected", new Integer(2)); - event0004DataMap.put("TestActStateTime", new Long(1434370506095L)); - - final ApexEvent apexEvent0004 = - new ApexEvent("Event0004", "0.0.1", "org.onap.policy.apex.sample.events", "test", "apex"); - apexEvent0004.putAll(event0004DataMap); - - final String apexEvent0004JSONString = (String) jsonEventConverter.fromApexEvent(apexEvent0004); - - logger.debug(apexEvent0004JSONString); - - assertTrue(apexEvent0004JSONString.contains("\"name\": \"Event0004\"")); - assertTrue(apexEvent0004JSONString.contains("\"version\": \"0.0.1\"")); - assertTrue(apexEvent0004JSONString.contains("\"nameSpace\": \"org.onap.policy.apex.sample.events\"")); - assertTrue(apexEvent0004JSONString.contains("\"source\": \"test\"")); - assertTrue(apexEvent0004JSONString.contains("\"target\": \"apex\"")); - assertTrue(apexEvent0004JSONString.contains("\"TestSlogan\": \"Test slogan for External Event\"")); - assertTrue(apexEvent0004JSONString.contains("1434370506078")); - assertTrue(apexEvent0004JSONString.contains("1064.43")); - } catch (final Exception e) { - e.printStackTrace(); - throw new ApexException("Exception reading Apex event JSON file", e); - } - } -} diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONTaggedEventConsumer.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONTaggedEventConsumer.java deleted file mode 100644 index 49e6f3bdf..000000000 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJSONTaggedEventConsumer.java +++ /dev/null @@ -1,131 +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.event; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.CharacterDelimitedTextBlockReader; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.TextBlock; - -/** - * Test JSON Tagged Event Consumer. - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestJSONTaggedEventConsumer { - - @Test - public void testGarbageText() throws IOException { - final InputStream jsonInputStream = new ByteArrayInputStream("hello there".getBytes()); - - final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); - taggedReader.init(jsonInputStream); - - final TextBlock textBlock = taggedReader.readTextBlock(); - assertNull(textBlock.getText()); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testPartialEvent() throws IOException { - final InputStream jsonInputStream = new ByteArrayInputStream("\"TestTimestamp\": 1469781869268}".getBytes()); - - final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); - taggedReader.init(jsonInputStream); - - final TextBlock textBlock = taggedReader.readTextBlock(); - assertNull(textBlock.getText()); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEvent() throws IOException { - final InputStream jsonInputStream = new ByteArrayInputStream("{TestTimestamp\": 1469781869268}".getBytes()); - - final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); - taggedReader.init(jsonInputStream); - - TextBlock textBlock = taggedReader.readTextBlock(); - assertEquals(textBlock.getText(), "{TestTimestamp\": 1469781869268}"); - - textBlock = taggedReader.readTextBlock(); - assertNull(textBlock.getText()); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventGarbageBefore() throws IOException { - final InputStream jsonInputStream = - new ByteArrayInputStream("Garbage{TestTimestamp\": 1469781869268}".getBytes()); - - final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); - taggedReader.init(jsonInputStream); - - TextBlock textBlock = taggedReader.readTextBlock(); - assertEquals(textBlock.getText(), "{TestTimestamp\": 1469781869268}"); - assertFalse(textBlock.isEndOfText()); - - textBlock = taggedReader.readTextBlock(); - assertNull(textBlock.getText()); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventGarbageBeforeAfter() throws IOException { - final InputStream jsonInputStream = - new ByteArrayInputStream("Garbage{TestTimestamp\": 1469781869268}Rubbish".getBytes()); - - final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); - taggedReader.init(jsonInputStream); - - TextBlock textBlock = taggedReader.readTextBlock(); - assertEquals(textBlock.getText(), "{TestTimestamp\": 1469781869268}"); - assertFalse(textBlock.isEndOfText()); - - textBlock = taggedReader.readTextBlock(); - assertNull(textBlock.getText()); - assertTrue(textBlock.isEndOfText()); - } - - @Test - public void testFullEventGarbageAfter() throws IOException { - final InputStream jsonInputStream = - new ByteArrayInputStream("{TestTimestamp\": 1469781869268}Rubbish".getBytes()); - - final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); - taggedReader.init(jsonInputStream); - - TextBlock textBlock = taggedReader.readTextBlock(); - assertEquals(textBlock.getText(), "{TestTimestamp\": 1469781869268}"); - assertFalse(textBlock.isEndOfText()); - - textBlock = taggedReader.readTextBlock(); - assertNull(textBlock.getText()); - assertTrue(textBlock.isEndOfText()); - } -} diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java new file mode 100644 index 000000000..cfe2921b8 --- /dev/null +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java @@ -0,0 +1,358 @@ +/*- + * ============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.event; + +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.ByteArrayInputStream; +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JsonEventConverter; +import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * Test JSON Event Handler. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestJsonEventHandler { + private static final XLogger logger = XLoggerFactory.getXLogger(TestJsonEventHandler.class); + + /** + * Setup event model. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException the apex model exception + */ + @BeforeClass + public static void setupEventModel() throws IOException, ApexModelException { + final String policyModelString = TextFileUtils + .getTextFileAsString("src/test/resources/policymodels/SamplePolicyModelMVEL.json"); + final ApexModelReader modelReader = new ApexModelReader(AxPolicyModel.class); + final AxPolicyModel apexPolicyModel = modelReader.read(new ByteArrayInputStream(policyModelString.getBytes())); + + // Set up the models in the model service + apexPolicyModel.register(); + } + + /** + * Initialize default schema parameters. + */ + @BeforeClass + public static void initializeDefaultSchemaParameters() { + ParameterService.clear(); + final SchemaParameters schemaParameters = new SchemaParameters(); + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + ParameterService.register(schemaParameters); + } + + /** + * Teardown default schema parameters. + */ + @AfterClass + public static void teardownDefaultSchemaParameters() { + ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); + } + + /** + * Test JSO nto apex event. + * + * @throws ApexException the apex exception + */ + @Test + public void testJsontoApexEvent() throws ApexException { + try { + final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); + assertNotNull(jsonEventConverter); + jsonEventConverter.init(new JsonEventProtocolParameters()); + + final String apexEventJsonStringIn = JsonEventGenerator.jsonEvent(); + + logger.debug("input event\n" + apexEventJsonStringIn); + + final List apexEventList = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + for (final ApexEvent apexEvent : apexEventList) { + assertNotNull(apexEvent); + + logger.debug(apexEvent.toString()); + + assertTrue(apexEvent.getName().equals("Event0000") || apexEvent.getName().equals("Event0100")); + assertTrue(apexEvent.getVersion().equals("0.0.1")); + assertTrue(apexEvent.getNameSpace().equals("org.onap.policy.apex.sample.events")); + assertTrue(apexEvent.getSource().equals("test")); + assertTrue(apexEvent.getTarget().equals("apex")); + assertTrue(apexEvent.get("TestSlogan").toString().startsWith("Test slogan for External Event")); + + final Object testMatchCaseSelected = apexEvent.get("TestMatchCaseSelected"); + assertTrue(testMatchCaseSelected == null); + } + } catch (final Exception e) { + e.printStackTrace(); + throw new ApexException("Exception reading Apex event JSON file", e); + } + } + + /** + * Test JSO nto apex bad event. + * + * @throws ApexException the apex exception + */ + @Test + public void testJsontoApexBadEvent() throws ApexException { + try { + final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); + assertNotNull(jsonEventConverter); + jsonEventConverter.init(new JsonEventProtocolParameters()); + + String apexEventJsonStringIn = null; + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoName(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertEquals("Failed to unmarshal JSON event: event received without mandatory parameter \"name\" ", + e.getMessage().substring(0, 82)); + } + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventBadName(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage().startsWith( + "Failed to unmarshal JSON event: field \"name\" with value \"%%%%\" is invalid")); + } + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoExName(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertEquals("Failed to unmarshal JSON event: an event definition for an event named \"I_DONT_EXI", + e.getMessage().substring(0, 82)); + } + + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoVersion(); + ApexEvent event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0); + assertEquals("0.0.1", event.getVersion()); + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventBadVersion(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage().startsWith( + "Failed to unmarshal JSON event: field \"version\" with value \"#####\" is invalid")); + } + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoExVersion(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage() + .startsWith("Failed to unmarshal JSON event: an event definition for an event named " + + "\"Event0000\" with version \"1.2.3\" not found in Apex model")); + } + + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoNamespace(); + event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0); + assertEquals("org.onap.policy.apex.sample.events", event.getNameSpace()); + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventBadNamespace(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage().startsWith("Failed to unmarshal JSON event: field \"nameSpace\" " + + "with value \"hello.&&&&\" is invalid")); + } + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoExNamespace(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage() + .startsWith("Failed to unmarshal JSON event: namespace \"pie.in.the.sky\" " + + "on event \"Event0000\" does not" + + " match namespace \"org.onap.policy.apex.sample.events\" " + + "for that event in the Apex model")); + } + + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoSource(); + event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0); + assertEquals("Outside", event.getSource()); + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventBadSource(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage().startsWith( + "Failed to unmarshal JSON event: field \"source\" with value \"%!@**@!\" is invalid")); + } + + apexEventJsonStringIn = JsonEventGenerator.jsonEventNoTarget(); + event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0); + assertEquals("Match", event.getTarget()); + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventBadTarget(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage().startsWith("Failed to unmarshal JSON event: field \"target\" " + + "with value \"KNIO(*S)A(S)D\" is invalid")); + } + + try { + apexEventJsonStringIn = JsonEventGenerator.jsonEventMissingFields(); + jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); + fail("Test should throw an exception here"); + } catch (final ApexEventException e) { + assertTrue(e.getMessage().startsWith("Failed to unmarshal JSON event: error parsing Event0000:0.0.1 " + + "event from Json. Field \"TestMatchCase\" is missing, but is mandatory.")); + } + + apexEventJsonStringIn = JsonEventGenerator.jsonEventNullFields(); + event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0); + assertEquals(null, event.get("TestSlogan")); + assertEquals((byte) -1, event.get("TestMatchCase")); + assertEquals((long) -1, event.get("TestTimestamp")); + assertEquals(-1.0, event.get("TestTemperature")); + + // Set the missing fields as optional in the model + final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get("Event0000"); + eventDefinition.getParameterMap().get("TestSlogan").setOptional(true); + eventDefinition.getParameterMap().get("TestMatchCase").setOptional(true); + eventDefinition.getParameterMap().get("TestTimestamp").setOptional(true); + eventDefinition.getParameterMap().get("TestTemperature").setOptional(true); + + apexEventJsonStringIn = JsonEventGenerator.jsonEventMissingFields(); + event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0); + assertEquals(null, event.get("TestSlogan")); + assertEquals(null, event.get("TestMatchCase")); + assertEquals(null, event.get("TestTimestamp")); + assertEquals(null, event.get("TestTemperature")); + } catch (final Exception e) { + e.printStackTrace(); + throw new ApexException("Exception reading Apex event JSON file", e); + } + } + + /** + * Test apex event to JSON. + * + * @throws ApexException the apex exception + */ + @Test + public void testApexEventToJson() throws ApexException { + try { + final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); + assertNotNull(jsonEventConverter); + + final Date event0000StartTime = new Date(); + final Map event0000DataMap = new HashMap(); + event0000DataMap.put("TestSlogan", "This is a test slogan"); + event0000DataMap.put("TestMatchCase", 12345); + event0000DataMap.put("TestTimestamp", event0000StartTime.getTime()); + event0000DataMap.put("TestTemperature", 34.5445667); + + final ApexEvent apexEvent0000 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.sample.events", + "test", "apex"); + apexEvent0000.putAll(event0000DataMap); + + final String apexEvent0000JsonString = (String) jsonEventConverter.fromApexEvent(apexEvent0000); + + logger.debug(apexEvent0000JsonString); + + assertTrue(apexEvent0000JsonString.contains("\"name\": \"Event0000\"")); + assertTrue(apexEvent0000JsonString.contains("\"version\": \"0.0.1\"")); + assertTrue(apexEvent0000JsonString.contains("\"nameSpace\": \"org.onap.policy.apex.sample.events\"")); + assertTrue(apexEvent0000JsonString.contains("\"source\": \"test\"")); + assertTrue(apexEvent0000JsonString.contains("\"target\": \"apex\"")); + assertTrue(apexEvent0000JsonString.contains("\"TestSlogan\": \"This is a test slogan\"")); + assertTrue(apexEvent0000JsonString.contains("\"TestMatchCase\": 12345")); + assertTrue(apexEvent0000JsonString.contains("\"TestTimestamp\": " + event0000StartTime.getTime())); + assertTrue(apexEvent0000JsonString.contains("\"TestTemperature\": 34.5445667")); + + final Date event0004StartTime = new Date(1434363272000L); + final Map event0004DataMap = new HashMap(); + event0004DataMap.put("TestSlogan", "Test slogan for External Event"); + event0004DataMap.put("TestMatchCase", new Integer(2)); + event0004DataMap.put("TestTimestamp", new Long(event0004StartTime.getTime())); + event0004DataMap.put("TestTemperature", new Double(1064.43)); + event0004DataMap.put("TestMatchCaseSelected", new Integer(2)); + event0004DataMap.put("TestMatchStateTime", new Long(1434370506078L)); + event0004DataMap.put("TestEstablishCaseSelected", new Integer(0)); + event0004DataMap.put("TestEstablishStateTime", new Long(1434370506085L)); + event0004DataMap.put("TestDecideCaseSelected", new Integer(3)); + event0004DataMap.put("TestDecideStateTime", new Long(1434370506092L)); + event0004DataMap.put("TestActCaseSelected", new Integer(2)); + event0004DataMap.put("TestActStateTime", new Long(1434370506095L)); + + final ApexEvent apexEvent0004 = new ApexEvent("Event0004", "0.0.1", "org.onap.policy.apex.sample.events", + "test", "apex"); + apexEvent0004.putAll(event0004DataMap); + + final String apexEvent0004JsonString = (String) jsonEventConverter.fromApexEvent(apexEvent0004); + + logger.debug(apexEvent0004JsonString); + + assertTrue(apexEvent0004JsonString.contains("\"name\": \"Event0004\"")); + assertTrue(apexEvent0004JsonString.contains("\"version\": \"0.0.1\"")); + assertTrue(apexEvent0004JsonString.contains("\"nameSpace\": \"org.onap.policy.apex.sample.events\"")); + assertTrue(apexEvent0004JsonString.contains("\"source\": \"test\"")); + assertTrue(apexEvent0004JsonString.contains("\"target\": \"apex\"")); + assertTrue(apexEvent0004JsonString.contains("\"TestSlogan\": \"Test slogan for External Event\"")); + assertTrue(apexEvent0004JsonString.contains("1434370506078")); + assertTrue(apexEvent0004JsonString.contains("1064.43")); + } catch (final Exception e) { + e.printStackTrace(); + throw new ApexException("Exception reading Apex event JSON file", e); + } + } +} diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonTaggedEventConsumer.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonTaggedEventConsumer.java new file mode 100644 index 000000000..e948ba67a --- /dev/null +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonTaggedEventConsumer.java @@ -0,0 +1,131 @@ +/*- + * ============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.event; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.CharacterDelimitedTextBlockReader; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.TextBlock; + +/** + * Test JSON Tagged Event Consumer. + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestJsonTaggedEventConsumer { + + @Test + public void testGarbageText() throws IOException { + final InputStream jsonInputStream = new ByteArrayInputStream("hello there".getBytes()); + + final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); + taggedReader.init(jsonInputStream); + + final TextBlock textBlock = taggedReader.readTextBlock(); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + @Test + public void testPartialEvent() throws IOException { + final InputStream jsonInputStream = new ByteArrayInputStream("\"TestTimestamp\": 1469781869268}".getBytes()); + + final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); + taggedReader.init(jsonInputStream); + + final TextBlock textBlock = taggedReader.readTextBlock(); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + @Test + public void testFullEvent() throws IOException { + final InputStream jsonInputStream = new ByteArrayInputStream("{TestTimestamp\": 1469781869268}".getBytes()); + + final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); + taggedReader.init(jsonInputStream); + + TextBlock textBlock = taggedReader.readTextBlock(); + assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText()); + + textBlock = taggedReader.readTextBlock(); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + @Test + public void testFullEventGarbageBefore() throws IOException { + final InputStream jsonInputStream = + new ByteArrayInputStream("Garbage{TestTimestamp\": 1469781869268}".getBytes()); + + final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); + taggedReader.init(jsonInputStream); + + TextBlock textBlock = taggedReader.readTextBlock(); + assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText()); + assertFalse(textBlock.isEndOfText()); + + textBlock = taggedReader.readTextBlock(); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + @Test + public void testFullEventGarbageBeforeAfter() throws IOException { + final InputStream jsonInputStream = + new ByteArrayInputStream("Garbage{TestTimestamp\": 1469781869268}Rubbish".getBytes()); + + final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); + taggedReader.init(jsonInputStream); + + TextBlock textBlock = taggedReader.readTextBlock(); + assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText()); + assertFalse(textBlock.isEndOfText()); + + textBlock = taggedReader.readTextBlock(); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } + + @Test + public void testFullEventGarbageAfter() throws IOException { + final InputStream jsonInputStream = + new ByteArrayInputStream("{TestTimestamp\": 1469781869268}Rubbish".getBytes()); + + final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); + taggedReader.init(jsonInputStream); + + TextBlock textBlock = taggedReader.readTextBlock(); + assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText()); + assertFalse(textBlock.isEndOfText()); + + textBlock = taggedReader.readTextBlock(); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); + } +} diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java index bfda220a5..56e716dd6 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java @@ -65,8 +65,8 @@ public class ContextParameterTests { } catch (final ParameterException e) { assertEquals("error reading parameters from \"src/test/resources/parameters/serviceContextBadParams.json\"" + "\n(ParameterRuntimeException):failed to deserialize the parameters for " - + "\"contextParameters\" to parameter class \"hello\"\njava.lang.ClassNotFoundException: hello", - e.getMessage()); + + "\"contextParameters\" to parameter class " + + "\"hello\"\njava.lang.ClassNotFoundException: hello", e.getMessage()); } } @@ -97,8 +97,10 @@ public class ContextParameterTests { new ApexParameterHandler().getParameters(arguments); fail("This test should throw an exception"); } catch (final ParameterException e) { - assertEquals("error reading parameters from \"src/test/resources/parameters/serviceContextBadClassParams.json\"" - + "\n(ParameterRuntimeException):failed to deserialize the parameters for \"contextParameters\"" + assertEquals("error reading parameters from " + + "\"src/test/resources/parameters/serviceContextBadClassParams.json\"" + + "\n(ParameterRuntimeException):failed to deserialize " + + "the parameters for \"contextParameters\"" + " to parameter class \"java.lang.Integer\"\ncom.google.gson.JsonSyntaxException: " + "java.lang.IllegalStateException: Expected NUMBER but was BEGIN_OBJECT at path $", e.getMessage()); @@ -253,7 +255,8 @@ public class ContextParameterTests { } catch (final ParameterException e) { assertEquals("error reading parameters from " + "\"src/test/resources/parameters/serviceContextBadClassDistParams.json\"\n" - + "(ClassCastException):org.onap.policy.apex.context.parameters.ContextParameters cannot be cast to" + + "(ClassCastException):" + + "org.onap.policy.apex.context.parameters.ContextParameters cannot be cast to" + " org.onap.policy.apex.context.parameters.DistributorParameters", e.getMessage()); } } @@ -270,7 +273,8 @@ public class ContextParameterTests { } catch (final ParameterException e) { assertEquals("error reading parameters from " + "\"src/test/resources/parameters/serviceContextBadClassLockParams.json\"\n" - + "(ClassCastException):org.onap.policy.apex.context.parameters.ContextParameters cannot be cast to" + + "(ClassCastException):" + + "org.onap.policy.apex.context.parameters.ContextParameters cannot be cast to" + " org.onap.policy.apex.context.parameters.LockManagerParameters", e.getMessage()); } } @@ -287,7 +291,8 @@ public class ContextParameterTests { } catch (final ParameterException e) { assertEquals("error reading parameters from " + "\"src/test/resources/parameters/serviceContextBadClassPersistParams.json\"\n" - + "(ClassCastException):org.onap.policy.apex.context.parameters.ContextParameters cannot be cast to" + + "(ClassCastException):" + + "org.onap.policy.apex.context.parameters.ContextParameters cannot be cast to" + " org.onap.policy.apex.context.parameters.PersistorParameters", e.getMessage()); } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java index 97724becc..7b71253b0 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java @@ -156,7 +156,7 @@ public class ParameterTests { + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID" + ", parameter group has status INVALID\n" + " parameter group \"FILE\" type " + "\"org.onap.policy.apex.service.engine.event.impl." - + "filecarrierplugin.FILECarrierTechnologyParameters\" INVALID, " + + "filecarrierplugin.FileCarrierTechnologyParameters\" INVALID, " + "parameter group has status INVALID\n" + " field \"fileName\" type \"java.lang.String\" value \"null\" INVALID, " + "fileName not specified or is blank or null, " @@ -166,7 +166,7 @@ public class ParameterTests { + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID" + ", parameter group has status INVALID\n" + " parameter group \"FILE\" type " + "\"org.onap.policy.apex.service.engine.event.impl." - + "filecarrierplugin.FILECarrierTechnologyParameters\" INVALID, " + + "filecarrierplugin.FileCarrierTechnologyParameters\" INVALID, " + "parameter group has status INVALID\n" + " field \"fileName\" type \"java.lang.String\" value \"null\" INVALID, " + "fileName not specified or is blank or null, " @@ -241,23 +241,24 @@ public class ParameterTests { assertEquals(345, parameters.getEngineServiceParameters().getInstanceCount()); assertEquals(65522, parameters.getEngineServiceParameters().getDeploymentPort()); - final CarrierTechnologyParameters prodCT = parameters.getEventOutputParameters().get("FirstProducer") - .getCarrierTechnologyParameters(); - final EventProtocolParameters prodEP = parameters.getEventOutputParameters().get("FirstProducer") + final CarrierTechnologyParameters prodCarrierTech = parameters.getEventOutputParameters() + .get("FirstProducer").getCarrierTechnologyParameters(); + final EventProtocolParameters prodEventProt = parameters.getEventOutputParameters().get("FirstProducer") .getEventProtocolParameters(); - final CarrierTechnologyParameters consCT = parameters.getEventInputParameters() + final CarrierTechnologyParameters consCarrierTech = parameters.getEventInputParameters() .get("MySuperDooperConsumer1").getCarrierTechnologyParameters(); - final EventProtocolParameters consEP = parameters.getEventInputParameters().get("MySuperDooperConsumer1") - .getEventProtocolParameters(); + final EventProtocolParameters consEventProt = parameters.getEventInputParameters() + .get("MySuperDooperConsumer1").getEventProtocolParameters(); - assertEquals("SUPER_DOOPER", prodCT.getLabel()); - assertEquals("SUPER_TOK_DEL", prodEP.getLabel()); - assertEquals("SUPER_DOOPER", consCT.getLabel()); - assertEquals("JSON", consEP.getLabel()); + assertEquals("SUPER_DOOPER", prodCarrierTech.getLabel()); + assertEquals("SUPER_TOK_DEL", prodEventProt.getLabel()); + assertEquals("SUPER_DOOPER", consCarrierTech.getLabel()); + assertEquals("JSON", consEventProt.getLabel()); - assertTrue(prodCT instanceof SuperDooperCarrierTechnologyParameters); + assertTrue(prodCarrierTech instanceof SuperDooperCarrierTechnologyParameters); - final SuperDooperCarrierTechnologyParameters superDooperParameters = (SuperDooperCarrierTechnologyParameters) prodCT; + final SuperDooperCarrierTechnologyParameters superDooperParameters = + (SuperDooperCarrierTechnologyParameters) prodCarrierTech; assertEquals("somehost:12345", superDooperParameters.getBootstrapServers()); assertEquals("0", superDooperParameters.getAcks()); assertEquals(25, superDooperParameters.getRetries()); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java index 26cf09c38..374a2df14 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.parameters.ApexParameterHandler; import org.onap.policy.apex.service.parameters.ApexParameters; @@ -117,7 +117,7 @@ public class ProducerConsumerTests { + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID" + ", parameter group has status INVALID\n" + " parameter group \"FILE\" type " + "\"org.onap.policy.apex.service.engine.event.impl." - + "filecarrierplugin.FILECarrierTechnologyParameters\" INVALID, " + + "filecarrierplugin.FileCarrierTechnologyParameters\" INVALID, " + "parameter group has status INVALID\n" + " field \"fileName\" type \"java.lang.String\" value \"null\" INVALID, " + "fileName not specified or is blank or null, " @@ -156,8 +156,8 @@ public class ProducerConsumerTests { + "(ParameterRuntimeException):carrier technology \"SUPER_LOOPER\" " + "does not match plugin \"SUPER_DOOPER\" in \"" + "org.onap.policy.apex.service.engine." + "parameters.dummyclasses.SuperDooperCarrierTechnologyParameters" - + "\", specify correct carrier technology parameter plugin in parameter \"parameterClassName\"", - e.getMessage()); + + "\", specify correct carrier technology parameter plugin " + + "in parameter \"parameterClassName\"", e.getMessage()); } } @@ -189,11 +189,11 @@ public class ProducerConsumerTests { try { final ApexParameters parameters = new ApexParameterHandler().getParameters(arguments); - final FILECarrierTechnologyParameters fileParams = (FILECarrierTechnologyParameters) parameters + final FileCarrierTechnologyParameters fileParams = (FileCarrierTechnologyParameters) parameters .getEventOutputParameters().get("aProducer").getCarrierTechnologyParameters(); assertEquals("/tmp/aaa.json", fileParams.getFileName()); assertEquals(false, fileParams.isStandardError()); - assertEquals(false, fileParams.isStandardIO()); + assertEquals(false, fileParams.isStandardIo()); assertEquals(false, fileParams.isStreamingMode()); } catch (final ParameterException e) { fail("This test should not throw an exception"); @@ -210,18 +210,20 @@ public class ProducerConsumerTests { new ApexParameterHandler().getParameters(arguments); fail("This test should throw an exception"); } catch (final ParameterException e) { - assertEquals("validation error(s) on parameters from \"src/test/resources/parameters/prodConsBadFileName.json\"\n" + assertEquals("validation error(s) on parameters from " + + "\"src/test/resources/parameters/prodConsBadFileName.json\"\n" + "parameter group \"APEX_PARAMETERS\" type " + "\"org.onap.policy.apex.service.parameters.ApexParameters\" INVALID, " + "parameter group has status INVALID\n" - + " parameter group map \"eventOutputParameters\" INVALID, parameter group has status INVALID\n" - + " parameter group \"aProducer\" type " - + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID, " - + "parameter group has status INVALID\n" + " parameter group \"FILE\" type " + + " parameter group map \"eventOutputParameters\" INVALID, " + + "parameter group has status INVALID\n" + " parameter group \"aProducer\" type " + + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" " + + "INVALID, parameter group has status INVALID\n" + " parameter group \"FILE\" type " + "\"org.onap.policy.apex.service.engine.event.impl." - + "filecarrierplugin.FILECarrierTechnologyParameters\" INVALID, " + + "filecarrierplugin.FileCarrierTechnologyParameters\" INVALID, " + "parameter group has status INVALID\n" + " field \"fileName\" type " - + "\"java.lang.String\" value \"null\" INVALID, fileName not specified or is blank or null, " + + "\"java.lang.String\" value \"null\" INVALID, " + + "fileName not specified or is blank or null, " + "it must be specified as a valid file location\n", e.getMessage()); } } @@ -237,8 +239,9 @@ public class ProducerConsumerTests { fail("This test should throw an exception"); } catch (final ParameterException e) { assertEquals("error reading parameters from \"src/test/resources/parameters/prodConsBadEPParClass.json\"\n" - + "(ParameterRuntimeException):event protocol \"SUPER_TOK_DEL\" does not match plugin \"JSON\" in " - + "\"org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters" + + "(ParameterRuntimeException):event protocol \"SUPER_TOK_DEL\" " + + "does not match plugin \"JSON\" in \"org.onap.policy.apex.service.engine.event.impl" + + ".jsonprotocolplugin.JsonEventProtocolParameters" + "\", specify correct event protocol parameter plugin in parameter \"parameterClassName\"", e.getMessage()); } @@ -270,7 +273,8 @@ public class ProducerConsumerTests { new ApexParameterHandler().getParameters(arguments); fail("This test should throw an exception"); } catch (final ParameterException e) { - assertEquals("error reading parameters from \"src/test/resources/parameters/prodConsMismatchEPParClass.json\"\n" + assertEquals("error reading parameters from " + + "\"src/test/resources/parameters/prodConsMismatchEPParClass.json\"\n" + "(ParameterRuntimeException):event protocol \"SUPER_TOK_BEL\" " + "does not match plugin \"SUPER_TOK_DEL\" in " + "\"org.onap.policy.apex.service.engine.parameters.dummyclasses." diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java index 7913af84c..8ad0654b1 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java @@ -151,8 +151,8 @@ public class SyncParameterTests { + "specify a non-negative timeout value in milliseconds\n" + " parameter group map \"eventInputParameters\" INVALID, " + "parameter group has status INVALID\n" + " parameter group \"SyncConsumer0\" type " - + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID, " - + "specified peered mode \"SYNCHRONOUS\" timeout value \"-1\" is illegal, " + + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" " + + "INVALID, specified peered mode \"SYNCHRONOUS\" timeout value \"-1\" is illegal, " + "specify a non-negative timeout value in milliseconds\n" + " parameter group \"SyncConsumer1\" type " + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID," @@ -371,8 +371,8 @@ public class SyncParameterTests { + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID" + ", peer \"SyncConsumer0 for peered mode SYNCHRONOUS, value \"SyncProducer1\" on peer " + "\"SyncConsumer0\" does not equal event handler \"SyncProducer0\"\n" - + " parameter group map \"eventInputParameters\" INVALID, parameter group has status INVALID\n" - + " parameter group \"SyncConsumer0\" type " + + " parameter group map \"eventInputParameters\" INVALID, parameter group has status " + + "INVALID\n parameter group \"SyncConsumer0\" type " + "\"org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters\" INVALID" + ", peer \"SyncProducer1 for peered mode SYNCHRONOUS, value \"SyncConsumer1\" on peer " + "\"SyncProducer1\" does not equal event handler \"SyncConsumer0\"\n", e.getMessage()); @@ -454,7 +454,8 @@ public class SyncParameterTests { assertTrue(consCT1 instanceof SuperDooperCarrierTechnologyParameters); assertTrue(consEP1 instanceof SuperTokenDelimitedEventProtocolParameters); - final SuperDooperCarrierTechnologyParameters superDooperParameters = (SuperDooperCarrierTechnologyParameters) consCT1; + final SuperDooperCarrierTechnologyParameters superDooperParameters = + (SuperDooperCarrierTechnologyParameters) consCT1; assertEquals("localhost:9092", superDooperParameters.getBootstrapServers()); assertEquals("all", superDooperParameters.getAcks()); assertEquals(0, superDooperParameters.getRetries()); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperCarrierTechnologyParameters.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperCarrierTechnologyParameters.java index 7eaf4c8e1..ccde5199a 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperCarrierTechnologyParameters.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperCarrierTechnologyParameters.java @@ -47,11 +47,12 @@ public class SuperDooperCarrierTechnologyParameters extends CarrierTechnologyPar private static final int DEFAULT_SESSION_TIMEOUT = 30000; private static final String DEFAULT_PRODUCER_TOPIC = "apex-out"; private static final int DEFAULT_CONSUMER_POLL_TIME = 100; - private static final String[] DEFAULT_CONSUMER_TOPIC_LIST = { "apex-in" }; - private static final String DEFAULT_KEY_SERIALIZER = "org.apache.superDooper.common.serialization.StringSerializer"; - private static final String DEFAULT_VALUE_SERIALIZER = "org.apache.superDooper.common.serialization.StringSerializer"; - private static final String DEFAULT_KEY_DESERIALIZER = "org.apache.superDooper.common.serialization.StringDeserializer"; - private static final String DEFAULT_VALUE_DESERIALIZER = "org.apache.superDooper.common.serialization.StringDeserializer"; + private static final String[] DEFAULT_CONSUMER_TOPIC_LIST = + { "apex-in" }; + private static final String DEFAULT_KEYSERZER = "org.apache.superDooper.common.serialization.StringSerializer"; + private static final String DEFAULT_VALSERZER = "org.apache.superDooper.common.serialization.StringSerializer"; + private static final String DEFAULT_KEYDESZER = "org.apache.superDooper.common.serialization.StringDeserializer"; + private static final String DEFAULT_VALDESZER = "org.apache.superDooper.common.serialization.StringDeserializer"; // Parameter property map tokens private static final String PROPERTY_BOOTSTRAP_SERVERS = "bootstrap.servers"; @@ -83,10 +84,10 @@ public class SuperDooperCarrierTechnologyParameters extends CarrierTechnologyPar private String producerTopic = DEFAULT_PRODUCER_TOPIC; private int consumerPollTime = DEFAULT_CONSUMER_POLL_TIME; private String[] consumerTopicList = DEFAULT_CONSUMER_TOPIC_LIST; - private String keySerializer = DEFAULT_KEY_SERIALIZER; - private String valueSerializer = DEFAULT_VALUE_SERIALIZER; - private String keyDeserializer = DEFAULT_KEY_DESERIALIZER; - private String valueDeserializer = DEFAULT_VALUE_DESERIALIZER; + private String keySerializer = DEFAULT_KEYSERZER; + private String valueSerializer = DEFAULT_VALSERZER; + private String keyDeserializer = DEFAULT_KEYDESZER; + private String valueDeserializer = DEFAULT_VALDESZER; /** * Constructor to create a file carrier technology parameters instance and register the instance with the parameter @@ -478,19 +479,23 @@ public class SuperDooperCarrierTechnologyParameters extends CarrierTechnologyPar } if (retries < 0) { - result.setResult("retries", ValidationStatus.INVALID, "[" + retries + "] invalid, must be specified as retries >= 0"); + result.setResult("retries", ValidationStatus.INVALID, + "[" + retries + "] invalid, must be specified as retries >= 0"); } if (batchSize < 0) { - result.setResult("batchSize", ValidationStatus.INVALID, "[" + batchSize + "] invalid, must be specified as batchSize >= 0"); + result.setResult("batchSize", ValidationStatus.INVALID, + "[" + batchSize + "] invalid, must be specified as batchSize >= 0"); } if (lingerTime < 0) { - result.setResult("lingerTime", ValidationStatus.INVALID, "[" + lingerTime + "] invalid, must be specified as lingerTime >= 0"); + result.setResult("lingerTime", ValidationStatus.INVALID, + "[" + lingerTime + "] invalid, must be specified as lingerTime >= 0"); } if (bufferMemory < 0) { - result.setResult("bufferMemory", ValidationStatus.INVALID, "[" + bufferMemory + "] invalid, must be specified as bufferMemory >= 0"); + result.setResult("bufferMemory", ValidationStatus.INVALID, + "[" + bufferMemory + "] invalid, must be specified as bufferMemory >= 0"); } if (groupId == null || groupId.trim().length() == 0) { @@ -498,8 +503,8 @@ public class SuperDooperCarrierTechnologyParameters extends CarrierTechnologyPar } if (autoCommitTime < 0) { - result.setResult("autoCommitTime", ValidationStatus.INVALID, "[" + autoCommitTime - + "] invalid, must be specified as autoCommitTime >= 0"); + result.setResult("autoCommitTime", ValidationStatus.INVALID, + "[" + autoCommitTime + "] invalid, must be specified as autoCommitTime >= 0"); } if (sessionTimeout < 0) { @@ -508,16 +513,18 @@ public class SuperDooperCarrierTechnologyParameters extends CarrierTechnologyPar } if (producerTopic == null || producerTopic.trim().length() == 0) { - result.setResult("producerTopic", ValidationStatus.INVALID, "producerTopic not specified, must be specified as a string"); + result.setResult("producerTopic", ValidationStatus.INVALID, + "producerTopic not specified, must be specified as a string"); } if (consumerPollTime < 0) { - result.setResult("consumerPollTime", ValidationStatus.INVALID, "[" + consumerPollTime - + "] invalid, must be specified as consumerPollTime >= 0"); + result.setResult("consumerPollTime", ValidationStatus.INVALID, + "[" + consumerPollTime + "] invalid, must be specified as consumerPollTime >= 0"); } if (consumerTopicList == null || consumerTopicList.length == 0) { - result.setResult("consumerTopicList", ValidationStatus.INVALID, "not specified, must be specified as a list of strings"); + result.setResult("consumerTopicList", ValidationStatus.INVALID, + "not specified, must be specified as a list of strings"); } StringBuilder consumerTopicMessageBuilder = new StringBuilder(); @@ -527,7 +534,7 @@ public class SuperDooperCarrierTechnologyParameters extends CarrierTechnologyPar + "\" specified on consumerTopicList, consumer topics must be specified as strings"); } } - + if (consumerTopicMessageBuilder.length() > 0) { result.setResult("consumerTopicList", ValidationStatus.INVALID, consumerTopicMessageBuilder.toString()); } @@ -537,11 +544,13 @@ public class SuperDooperCarrierTechnologyParameters extends CarrierTechnologyPar } if (valueSerializer == null || valueSerializer.trim().length() == 0) { - result.setResult("valueSerializer", ValidationStatus.INVALID, "not specified, must be specified as a string"); + result.setResult("valueSerializer", ValidationStatus.INVALID, + "not specified, must be specified as a string"); } if (keyDeserializer == null || keyDeserializer.trim().length() == 0) { - result.setResult("keyDeserializer", ValidationStatus.INVALID, "not specified, must be specified as a string"); + result.setResult("keyDeserializer", ValidationStatus.INVALID, + "not specified, must be specified as a string"); } if (valueDeserializer == null || valueDeserializer.trim().length() == 0) { diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperDistributorParameters.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperDistributorParameters.java index a8d099654..0d021c919 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperDistributorParameters.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperDooperDistributorParameters.java @@ -74,8 +74,8 @@ public class SuperDooperDistributorParameters extends DistributorParameters { return jgroupsBindAddress; } - public void setjGroupsBindAddress(final String jGroupsBindAddress) { - this.jgroupsBindAddress = jGroupsBindAddress; + public void setjGroupsBindAddress(final String jgroupsBindAddress) { + this.jgroupsBindAddress = jgroupsBindAddress; } @Override diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperTokenDelimitedEventProtocolParameters.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperTokenDelimitedEventProtocolParameters.java index ec4f97d78..7ae403726 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperTokenDelimitedEventProtocolParameters.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/dummyclasses/SuperTokenDelimitedEventProtocolParameters.java @@ -20,7 +20,7 @@ package org.onap.policy.apex.service.engine.parameters.dummyclasses; -import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters; +import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextTokenDelimitedParameters; /** @@ -38,7 +38,7 @@ public class SuperTokenDelimitedEventProtocolParameters extends EventProtocolTex * the parameter service. */ public SuperTokenDelimitedEventProtocolParameters() { - super(JSONEventProtocolParameters.class.getCanonicalName()); + super(JsonEventProtocolParameters.class.getCanonicalName()); // Set the event protocol properties for the JSON carrier technology this.setLabel(SUPER_TOKEN_EVENT_PROTOCOL_LABEL); diff --git a/services/services-engine/src/test/resources/parameters/prodConsBadCTParClass.json b/services/services-engine/src/test/resources/parameters/prodConsBadCTParClass.json index 217946956..bb431279e 100644 --- a/services/services-engine/src/test/resources/parameters/prodConsBadCTParClass.json +++ b/services/services-engine/src/test/resources/parameters/prodConsBadCTParClass.json @@ -31,7 +31,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "SUPER_DOOPER", - "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "SUPER_TOK_DEL", diff --git a/services/services-engine/src/test/resources/parameters/prodConsBadEPParClass.json b/services/services-engine/src/test/resources/parameters/prodConsBadEPParClass.json index 0900d5bee..7b1f1c099 100644 --- a/services/services-engine/src/test/resources/parameters/prodConsBadEPParClass.json +++ b/services/services-engine/src/test/resources/parameters/prodConsBadEPParClass.json @@ -35,7 +35,7 @@ }, "eventProtocolParameters": { "eventProtocol": "SUPER_TOK_DEL", - "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters" } } } diff --git a/services/services-engine/src/test/resources/parameters/prodConsNoCT.json b/services/services-engine/src/test/resources/parameters/prodConsNoCT.json index 7bf3024ba..cbd9957c8 100644 --- a/services/services-engine/src/test/resources/parameters/prodConsNoCT.json +++ b/services/services-engine/src/test/resources/parameters/prodConsNoCT.json @@ -31,7 +31,7 @@ "aConsumer": { "carrierParameters": { "carrierTechnology": "SUPER_DOOPER", - "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "SUPER_TOK_DEL", diff --git a/services/services-engine/src/test/resources/parameters/prodConsNoEP.json b/services/services-engine/src/test/resources/parameters/prodConsNoEP.json index 122680dbe..92c089225 100644 --- a/services/services-engine/src/test/resources/parameters/prodConsNoEP.json +++ b/services/services-engine/src/test/resources/parameters/prodConsNoEP.json @@ -31,7 +31,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "FILE", - "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "SUPER_TOK_DEL", 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 e500c9d3b..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/engine/TestApexEngineMvel.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMvel.java new file mode 100644 index 000000000..4aab859ca --- /dev/null +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/plugins/executor/test/script/engine/TestApexEngineMvel.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.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 index 07a374926..b1542def0 100644 --- 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 @@ -45,7 +45,7 @@ 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.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; @@ -86,7 +86,7 @@ public class TestEventInstantiation { ParameterService.register(contextParameters.getPersistorParameters()); engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); ParameterService.register(engineParameters); } 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 index 83e69c98f..20159a3bf 100644 --- 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 @@ -41,7 +41,7 @@ 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.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; @@ -83,7 +83,7 @@ public class TestContextUpdateDifferentModels { ParameterService.register(contextParameters.getPersistorParameters()); engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); ParameterService.register(engineParameters); } 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 index 7aaa1e585..d5605ea4c 100644 --- 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 @@ -44,7 +44,7 @@ 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.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; @@ -86,7 +86,7 @@ public class TestContextUpdateModel { ParameterService.register(contextParameters.getPersistorParameters()); engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); ParameterService.register(engineParameters); } 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 index b17457516..c95498a05 100644 --- 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 @@ -28,7 +28,6 @@ import java.util.Properties; import kafka.admin.AdminUtils; import kafka.admin.RackAwareMode; -import kafka.server.BrokerState; import kafka.server.KafkaConfig; import kafka.server.KafkaServer; import kafka.utils.TestUtils; @@ -48,6 +47,9 @@ 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 @@ -66,6 +68,11 @@ public class TestKafka2Kafka { 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 @@ -95,6 +102,11 @@ public class TestKafka2Kafka { } + /** + * Shutdown dummy kafka server. + * + * @throws IOException Signals that an I/O exception has occurred. + */ @AfterClass public static void shutdownDummyKafkaServer() throws IOException { if (kafkaServer != null) { @@ -108,18 +120,39 @@ public class TestKafka2Kafka { } } + /** + * 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 { + 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 = 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 index bda312c42..fd78ba5c0 100644 --- 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 @@ -26,6 +26,9 @@ import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStri 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; @@ -36,6 +39,16 @@ public class WebSocketEventProducerClient implements WsStringMessageListener { 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; @@ -51,6 +64,9 @@ public class WebSocketEventProducerClient implements WsStringMessageListener { + ", 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); @@ -74,10 +90,18 @@ public class WebSocketEventProducerClient implements WsStringMessageListener { 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"); @@ -96,6 +120,12 @@ public class WebSocketEventProducerClient implements WsStringMessageListener { + ", 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"); 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 index a36c4d61e..53aa0cab4 100644 --- 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 @@ -26,6 +26,9 @@ import org.onap.policy.apex.core.infrastructure.messaging.stringmessaging.WsStri 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; @@ -35,6 +38,15 @@ public class WebSocketEventProducerServer implements WsStringMessageListener { 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; @@ -49,6 +61,9 @@ public class WebSocketEventProducerServer implements WsStringMessageListener { + eventCount + ", xmlEvents " + xmlEvents); } + /** + * Send events. + */ public void sendEvents() { System.out.println(WebSocketEventProducerServer.class.getCanonicalName() + ": sending events on port " + port + ", event count " + eventCount + ", xmlEvents " + xmlEvents); @@ -73,10 +88,18 @@ public class WebSocketEventProducerServer implements WsStringMessageListener { 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"); @@ -95,6 +118,12 @@ public class WebSocketEventProducerServer implements WsStringMessageListener { + ", 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"); 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 index 48ca9c884..27a34a92e 100644 --- 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 @@ -24,12 +24,22 @@ 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; @@ -51,15 +61,29 @@ public class WebSocketEventSubscriberClient implements WsStringMessageListener { 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"); 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 index 83e324b9c..854a0e410 100644 --- 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 @@ -24,12 +24,21 @@ 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; @@ -54,15 +63,29 @@ public class WebSocketEventSubscriberServer implements WsStringMessageListener { 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"); 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 index aa7b56189..8f9aa6cee 100644 --- 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 @@ -29,13 +29,11 @@ import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain; +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.basicmodel.service.ModelService; import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.apex.service.engine.main.ApexMain; -import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.common.utils.resources.ResourceUtils; public class EventAlbumContextTest { @@ -86,7 +84,7 @@ public class EventAlbumContextTest { final String[] cliArgs = new String[] { "-c", tempCommandFile.getCanonicalPath(), "-l", tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath() }; - new ApexCLIEditorMain(cliArgs); + new ApexCommandLineEditorMain(cliArgs); final String[] args = new String[] { "-m", tempModelFile.getAbsolutePath(), "-c", configFile }; final ApexMain apexMain = new ApexMain(args); 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 index 451b4c76a..187a2a316 100644 --- 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 @@ -42,7 +42,7 @@ 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.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; @@ -94,7 +94,7 @@ public class EngDepMessagingTest { engineServiceParameters.setDeploymentPort(58820); engineServiceParameters.setInstanceCount(3); engineServiceParameters.setId(100); - engineServiceParameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + engineServiceParameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); ParameterService.register(engineServiceParameters); ParameterService.register(engineServiceParameters.getEngineParameters()); diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInJsonEvent.json index 507ae7d6f..209e94fea 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json index 43e187a87..10544c45e 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredInOutJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json index e5cd23b03..99b7c6684 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileFilteredOutJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileJsonEvent.json index a7a321039..fb42942d7 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileXmlEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileXmlEvent.json index 5cca6d604..4b3adfaae 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileXmlEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2FileXmlEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -24,7 +24,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } }, @@ -38,7 +38,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json index b7540f943..9ce0bb348 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadHTTPMethod.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestFile2Rest/apex/event/PutEvent", "httpMethod": "DELETE" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadURL.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadURL.json index 99856932e..639b7c677 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadURL.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventBadURL.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestFile2Rest/apex/event/Bad" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventNoURL.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventNoURL.json index 8c00885e5..2dcedf7fd 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventNoURL.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventNoURL.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPost.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPost.json index 1a1a189a4..1fa52d055 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPost.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPost.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestFile2Rest/apex/event/PostEvent" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json index fda83d7a6..e196d8999 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPostBadResponse.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestFile2Rest/apex/event/PostEventBadResponse" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPut.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPut.json index 990e08f17..641c0c97e 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPut.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/File2RESTJsonEventPut.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestFile2Rest/apex/event/PutEvent", "httpMethod": "PUT" 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 6e9405576..0d55d8a7d 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 @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "JMS", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JMSCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", @@ -31,7 +31,7 @@ }, "eventProtocolParameters": { "eventProtocol": "JMSTEXT", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JMSTextEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JmsTextEventProtocolParameters" } } }, @@ -39,7 +39,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "JMS", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JMSCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", @@ -51,7 +51,7 @@ }, "eventProtocolParameters": { "eventProtocol": "JMSTEXT", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JMSTextEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JmsTextEventProtocolParameters" } } } 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 9a8aed39b..228f8ec60 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 @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "JMS", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JMSCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", @@ -30,7 +30,7 @@ }, "eventProtocolParameters": { "eventProtocol": "JMSOBJECT", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JMSObjectEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JmsObjectEventProtocolParameters" } } }, @@ -38,7 +38,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "JMS", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JMSCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.jms.JmsCarrierTechnologyParameters", "parameters": { "initialContextFactory": "org.onap.policy.apex.apps.uservice.test.adapt.jms.TestInitialContextFactory", "connectionFactory": "ConnectionFactory", @@ -50,7 +50,7 @@ }, "eventProtocolParameters": { "eventProtocol": "JMSOBJECT", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JMSObjectEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.jms.JmsObjectEventProtocolParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaJsonEvent.json index 974e22b51..cd758b18d 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "KAFKA", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KafkaCarrierTechnologyParameters", "parameters": { "bootstrapServers": "localhost:39902", "acks": "all", @@ -40,7 +40,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "KAFKA", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KafkaCarrierTechnologyParameters", "parameters": { "bootstrapServers": "localhost:39902", "groupId": "apex-group-id", diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaXmlEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaXmlEvent.json index 916b7caf7..d4468a57e 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaXmlEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Kafka2KafkaXmlEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "KAFKA", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KafkaCarrierTechnologyParameters", "parameters": { "bootstrapServers": "localhost:39902", "acks": "all", @@ -33,7 +33,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } }, @@ -41,7 +41,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "KAFKA", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KafkaCarrierTechnologyParameters", "parameters": { "bootstrapServers": "localhost:39902", "groupId": "apex-group-id", @@ -58,7 +58,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/LBPolicy_ExecModel_file2kafka.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/LBPolicy_ExecModel_file2kafka.json index f98a853f6..7b4127d53 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/LBPolicy_ExecModel_file2kafka.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/LBPolicy_ExecModel_file2kafka.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "KAFKA", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KafkaCarrierTechnologyParameters", "parameters": { "bootstrapServers": "localhost:9092", "acks": "all", diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEmptyEvents.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEmptyEvents.json index 8e77e7d25..804b91e9f 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEmptyEvents.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEmptyEvents.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEvent.json index 849a83eca..6424e52e1 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRest2File/apex/event/GetEvent" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json index 86f14b024..227c20a0e 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRest2File/apex/event/GetEvent", "httpMethod": "POST" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadResponse.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadResponse.json index 95c3fd5c3..f365a9631 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadResponse.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadResponse.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadURL.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadURL.json index f58e55bc4..852e69194 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadURL.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventBadURL.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", "parameters": { "url": "http://localhost:32801/TestRest2File/apex/event/Bad" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventNoURL.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventNoURL.json index ff35e17be..877ca47ba 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventNoURL.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/REST2FileJsonEventNoURL.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEvent.json index 180530ac7..f482bc9b2 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -37,7 +37,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json index 7cd558a51..0b325a08d 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerNotSync.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -34,7 +34,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json index 72c94fd58..40943e794 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoHost.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true } @@ -35,7 +35,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json index 0ee99e2c9..85e33ef54 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventConsumerStandaloneNoPort.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost" @@ -36,7 +36,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextAvro.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextAvro.json index 7aabe00e7..2cd373810 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextAvro.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextAvro.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } }, "contextParameters": { @@ -26,7 +26,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -45,7 +45,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextJava.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextJava.json index 30b32da82..193c259b5 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextJava.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventContextJava.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } }, "contextParameters": { @@ -26,7 +26,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -45,7 +45,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json index 1a5db11e8..d4b6d19b5 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventDivideByZero.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -37,7 +37,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventMultiIn.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventMultiIn.json index 9975a443f..b34a85d32 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventMultiIn.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventMultiIn.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -35,7 +35,7 @@ "SecondConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -54,7 +54,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" @@ -66,7 +66,7 @@ "SecondProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerHost.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerHost.json index c33570808..2c73fc3de 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerHost.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerHost.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -37,7 +37,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "host": "localhost" } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json index 1c0d005f6..8c55d158d 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerNotSync.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -34,7 +34,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters" }, "eventProtocolParameters": { "eventProtocol": "JSON" diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerPort.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerPort.json index 4366c651a..da08cf569 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerPort.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerPort.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -37,7 +37,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "port": 12345 } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json index d0cf4eb11..a2626dcf1 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/RESTServerJsonEventProducerStandalone.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "FirstConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true, "host": "localhost", @@ -37,7 +37,7 @@ "FirstProducer": { "carrierTechnologyParameters": { "carrierTechnology": "RESTSERVER", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restserver.RestServerCarrierTechnologyParameters", "parameters": { "standalone": true } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientJsonEvent.json index 651a63b59..7caa8b264 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "host": "localhost", "port": 42453 @@ -33,7 +33,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "host": "localhost", "port": 42451 diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientXMLEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientXMLEvent.json index c14bc0645..8883d2fa7 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientXMLEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsClientXMLEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "host": "localhost", "port": 42453 @@ -26,7 +26,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } }, @@ -34,7 +34,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "host": "localhost", "port": 42451 @@ -42,7 +42,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } } diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerJsonEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerJsonEvent.json index c1fa11c30..e7b1943c1 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerJsonEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerJsonEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 42452 @@ -33,7 +33,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 42450 diff --git a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerXMLEvent.json b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerXMLEvent.json index 878d7108a..5cd7945c2 100644 --- a/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerXMLEvent.json +++ b/testsuites/integration/integration-uservice-test/src/test/resources/prodcons/Ws2WsServerXMLEvent.json @@ -9,7 +9,7 @@ "engineParameters": { "executorParameters": { "MVEL": { - "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters" + "parameterClassName": "org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters" } } } @@ -18,7 +18,7 @@ "aProducer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 42452 @@ -26,7 +26,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } }, @@ -34,7 +34,7 @@ "aConsumer": { "carrierTechnologyParameters": { "carrierTechnology": "WEBSOCKET", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.websocket.WebSocketCarrierTechnologyParameters", "parameters": { "wsClient": false, "port": 42450 @@ -42,7 +42,7 @@ }, "eventProtocolParameters": { "eventProtocol": "XML", - "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters" + "parameterClassName": "org.onap.policy.apex.plugins.event.protocol.xml.XmlEventProtocolParameters" } } } 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 index 363811978..43211bc73 100644 --- 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 @@ -36,7 +36,7 @@ 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.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; @@ -74,7 +74,7 @@ public class ApexBaseBenchMarkTest { final EngineParameters engineParameters = parameters.getEngineParameters(); final Map executorParameterMap = engineParameters.getExecutorParameterMap(); - executorParameterMap.put("MVEL", new MVELExecutorParameters()); + executorParameterMap.put("MVEL", new MvelExecutorParameters()); executorParameterMap.put("JAVASCRIPT", new JavascriptExecutorParameters()); executorParameterMap.put("JYTHON", new JythonExecutorParameters()); executorParameterMap.put("JAVA", new JavaExecutorParameters()); 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 index d26580611..aa95e73b3 100644 --- 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 @@ -38,7 +38,7 @@ 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.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; @@ -80,7 +80,7 @@ public class ApexServiceModelUpdateTest { parameters.setName(engineServiceKey.getName()); parameters.setVersion(engineServiceKey.getVersion()); parameters.setId(100); - parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); service = EngineServiceImpl.create(parameters); LOGGER.debug("Running TestApexEngine. . ."); 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 index c5617e1e4..c178cd9aa 100644 --- 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 @@ -36,7 +36,7 @@ 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.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; @@ -58,8 +58,8 @@ public class ApexServiceTest { private static final long MAX_START_WAIT = 5000; // 5 sec private static final long MAX_RECV_WAIT = 5000; // 5 sec - private final static AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0"); - private final static EngineServiceParameters parameters = new EngineServiceParameters(); + 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; @@ -81,7 +81,7 @@ public class ApexServiceTest { parameters.setName(engineServiceKey.getName()); parameters.setVersion(engineServiceKey.getVersion()); parameters.setId(100); - parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); service = EngineServiceImpl.create(parameters); @@ -130,13 +130,13 @@ public class ApexServiceTest { final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event.setExecutionID(System.nanoTime()); + 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.setExecutionId(System.nanoTime()); event2.putAll(eventDataMap); engineServiceEventInterface.sendEvent(event2); @@ -193,13 +193,13 @@ public class ApexServiceTest { 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()); + 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()); + assertEquals(event1.getExecutionId(), responseEvent.getExecutionId()); waitFlag = false; } }; @@ -214,14 +214,14 @@ public class ApexServiceTest { final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event2.setExecutionID(System.nanoTime()); + 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(event2.getExecutionId(), responseEvent.getExecutionId()); assertEquals(2, actionEventsReceived); waitFlag = false; } @@ -283,13 +283,13 @@ public class ApexServiceTest { final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex"); - event.setExecutionID(System.nanoTime()); + 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.setExecutionId(System.nanoTime()); event2.putAll(eventDataMap); engineServiceEventInterface.sendEvent(event2); @@ -350,7 +350,7 @@ public class ApexServiceTest { @Override public void onApexEvent(final ApexEvent responseEvent) { assertNotNull("Synchronous sendEventWait failed", responseEvent); - assertEquals(event1.getExecutionID(), responseEvent.getExecutionID()); + assertEquals(event1.getExecutionId(), responseEvent.getExecutionId()); waitFlag = false; } }; @@ -371,7 +371,7 @@ public class ApexServiceTest { @Override public void onApexEvent(final ApexEvent responseEvent) { assertNotNull("Synchronous sendEventWait failed", responseEvent); - assertEquals(event2.getExecutionID(), responseEvent.getExecutionID()); + assertEquals(event2.getExecutionId(), responseEvent.getExecutionId()); waitFlag = false; } }; @@ -429,7 +429,7 @@ public class ApexServiceTest { * * @see TestEvent */ - private final static class TestListener implements ApexEventListener { + private static final class TestListener implements ApexEventListener { /* * (non-Javadoc) 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 cc9ed5cae..88ada24f6 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 @@ -31,7 +31,7 @@ import java.util.Map.Entry; import java.util.Properties; import org.apache.commons.lang3.Validate; -import org.onap.policy.apex.auth.clicodegen.CGCliEditor; +import org.onap.policy.apex.auth.clicodegen.CodeGeneratorCliEditor; 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.concepts.AxReferenceKey; @@ -104,7 +104,7 @@ public class Model2Cli { * @throws ApexException if any problem occurred in the model */ public int runApp() throws ApexException { - final CGCliEditor codeGen = new CGCliEditor(); + final CodeGeneratorCliEditor codeGen = new CodeGeneratorCliEditor(); final ApexModelFactory factory = new ApexModelFactory(); final ApexModel model = factory.createApexModel(new Properties(), true); @@ -208,7 +208,7 @@ public class Model2Cli { * @param event the event * @return the parameters for event */ - private List getParametersForEvent(final CGCliEditor cg, final AxEvent event) { + private List getParametersForEvent(final CodeGeneratorCliEditor cg, final AxEvent event) { final Collection fields = event.getFields(); final List ret = new ArrayList<>(fields.size()); for (final AxField f : fields) { @@ -229,7 +229,7 @@ public class Model2Cli { * @param task the task * @return the context references for task */ - private List getCtxtRefsForTask(final CGCliEditor cg, final AxTask task) { + private List getCtxtRefsForTask(final CodeGeneratorCliEditor cg, final AxTask task) { final Collection ctxs = task.getContextAlbumReferences(); final List ret = new ArrayList<>(ctxs.size()); final AxArtifactKey tkey = task.getKey(); @@ -250,7 +250,7 @@ public class Model2Cli { * @param task the task * @return the parameters for task */ - private List getParametersForTask(final CGCliEditor cg, final AxTask task) { + private List getParametersForTask(final CodeGeneratorCliEditor cg, final AxTask task) { final Collection pars = task.getTaskParameters().values(); final List ret = new ArrayList<>(pars.size()); for (final AxTaskParameter p : pars) { @@ -271,7 +271,7 @@ public class Model2Cli { * @param task the task * @return the logic for task */ - private ST getLogicForTask(final CGCliEditor cg, final AxTask task) { + private ST getLogicForTask(final CodeGeneratorCliEditor cg, final AxTask task) { final AxArtifactKey tkey = task.getKey(); final AxTaskLogic tl = task.getTaskLogic(); @@ -288,7 +288,7 @@ public class Model2Cli { * @param task the task * @return the output fields for task */ - private List getOutfieldsForTask(final CGCliEditor cg, final AxTask task) { + private List getOutfieldsForTask(final CodeGeneratorCliEditor cg, final AxTask task) { final Collection fields = task.getOutputFields().values(); final List ret = new ArrayList<>(fields.size()); for (final AxField f : fields) { @@ -309,7 +309,7 @@ public class Model2Cli { * @param task the task * @return the input fields for task */ - private List getInfieldsForTask(final CGCliEditor cg, final AxTask task) { + private List getInfieldsForTask(final CodeGeneratorCliEditor cg, final AxTask task) { final Collection fields = task.getInputFields().values(); final List ret = new ArrayList<>(fields.size()); for (final AxField f : fields) { @@ -330,7 +330,7 @@ public class Model2Cli { * @param pol the policy * @return the states for policy */ - private List getStatesForPolicy(final CGCliEditor cg, final AxPolicy pol) { + private List getStatesForPolicy(final CodeGeneratorCliEditor cg, final AxPolicy pol) { final Collection states = pol.getStateMap().values(); final List ret = new ArrayList<>(states.size()); for (final AxState st : states) { @@ -357,7 +357,7 @@ public class Model2Cli { * @param st the state * @return the finalizers for state */ - private List getFinalizersForState(final CGCliEditor cg, final AxState st) { + private List getFinalizersForState(final CodeGeneratorCliEditor cg, final AxState st) { final Collection fins = st.getStateFinalizerLogicMap().values(); final List ret = new ArrayList<>(fins.size()); final AxReferenceKey skey = st.getKey(); @@ -379,7 +379,7 @@ public class Model2Cli { * @param st the state * @return the context references for state */ - private List getCtxtRefsForState(final CGCliEditor cg, final AxState st) { + private List getCtxtRefsForState(final CodeGeneratorCliEditor cg, final AxState st) { final Collection ctxs = st.getContextAlbumReferences(); final List ret = new ArrayList<>(ctxs.size()); final AxReferenceKey skey = st.getKey(); @@ -400,7 +400,7 @@ public class Model2Cli { * @param st the state * @return the TSL for state (if any) in a list */ - private List getTSLForState(final CGCliEditor 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(); @@ -419,7 +419,7 @@ public class Model2Cli { * @param st the state * @return the task references for state */ - private List getTaskRefsForState(final CGCliEditor cg, final AxState st) { + private List getTaskRefsForState(final CodeGeneratorCliEditor cg, final AxState st) { final Map taskrefs = st.getTaskReferences(); final List ret = new ArrayList<>(taskrefs.size()); final AxReferenceKey skey = st.getKey(); @@ -444,7 +444,7 @@ public class Model2Cli { * @param st the state * @return the state outputs for state */ - private List getStateOutputsForState(final CGCliEditor cg, final AxState st) { + private List getStateOutputsForState(final CodeGeneratorCliEditor cg, final AxState st) { final Collection outs = st.getStateOutputs().values(); final List ret = new ArrayList<>(outs.size()); final AxReferenceKey skey = st.getKey(); -- cgit 1.2.3-korg