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 --- .../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 +- 106 files changed, 4864 insertions(+), 4106 deletions(-) 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 (limited to 'plugins') 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."); -- cgit 1.2.3-korg