From 0cb18b0baa2cf750e557262d821bbf2a03326bbe Mon Sep 17 00:00:00 2001 From: sunil unnava Date: Tue, 23 Oct 2018 10:31:46 -0400 Subject: update the package name Issue-ID: DMAAP-858 Change-Id: Ia69621ea6ad2ec2ec525800af2a7d3f73aef82ed Signed-off-by: sunil unnava --- pom.xml | 2 +- .../java/com/att/nsa/mr/client/HostSelector.java | 198 ----- .../com/att/nsa/mr/client/MRBatchingPublisher.java | 55 -- src/main/java/com/att/nsa/mr/client/MRClient.java | 66 -- .../com/att/nsa/mr/client/MRClientBuilders.java | 449 ---------- .../com/att/nsa/mr/client/MRClientFactory.java | 691 --------------- .../java/com/att/nsa/mr/client/MRConsumer.java | 54 -- .../com/att/nsa/mr/client/MRIdentityManager.java | 100 --- .../java/com/att/nsa/mr/client/MRPublisher.java | 93 --- .../java/com/att/nsa/mr/client/MRTopicManager.java | 183 ---- .../java/com/att/nsa/mr/client/impl/Clock.java | 63 -- .../att/nsa/mr/client/impl/DmaapClientUtil.java | 85 -- .../com/att/nsa/mr/client/impl/MRBaseClient.java | 395 --------- .../att/nsa/mr/client/impl/MRBatchPublisher.java | 487 ----------- .../nsa/mr/client/impl/MRClientVersionInfo.java | 59 -- .../com/att/nsa/mr/client/impl/MRConstants.java | 179 ---- .../com/att/nsa/mr/client/impl/MRConsumerImpl.java | 675 --------------- .../java/com/att/nsa/mr/client/impl/MRFormat.java | 52 -- .../com/att/nsa/mr/client/impl/MRMetaClient.java | 266 ------ .../mr/client/impl/MRSimplerBatchPublisher.java | 927 --------------------- .../nsa/mr/client/response/MRConsumerResponse.java | 60 -- .../mr/client/response/MRPublisherResponse.java | 67 -- .../client/DefaultLoggingFailoverFaultHandler.java | 52 -- .../att/nsa/mr/dme/client/HeaderReplyHandler.java | 63 -- .../mr/dme/client/PreferredRouteReplyHandler.java | 72 -- .../dme/client/PreferredRouteRequestHandler.java | 54 -- .../nsa/mr/dme/client/SimpleExampleConsumer.java | 88 -- .../nsa/mr/dme/client/SimpleExamplePublisher.java | 135 --- .../java/com/att/nsa/mr/logging/MRAppender.java | 165 ---- .../att/nsa/mr/test/clients/ConsolePublisher.java | 95 --- .../nsa/mr/test/clients/ProtocolTypeConstants.java | 44 - .../att/nsa/mr/test/clients/SampleConsumer.java | 87 -- .../att/nsa/mr/test/clients/SamplePublisher.java | 86 -- .../nsa/mr/test/clients/SimpleExampleConsumer.java | 84 -- .../SimpleExampleConsumerWithReturnResponse.java | 95 --- .../mr/test/clients/SimpleExamplePublisher.java | 98 --- .../SimpleExamplePublisherWithResponse.java | 84 -- .../mr/test/support/MRBatchingPublisherMock.java | 184 ---- .../att/nsa/mr/test/support/MRConsumerMock.java | 169 ---- .../java/com/att/nsa/mr/tools/ApiKeyCommand.java | 141 ---- .../java/com/att/nsa/mr/tools/AuthCommand.java | 69 -- .../java/com/att/nsa/mr/tools/ClusterCommand.java | 80 -- .../com/att/nsa/mr/tools/MRCommandContext.java | 100 --- src/main/java/com/att/nsa/mr/tools/MRTool.java | 49 -- .../java/com/att/nsa/mr/tools/MessageCommand.java | 131 --- src/main/java/com/att/nsa/mr/tools/ToolsUtil.java | 40 - .../java/com/att/nsa/mr/tools/TopicCommand.java | 221 ----- .../java/com/att/nsa/mr/tools/TraceCommand.java | 118 --- .../java/com/att/nsa/mr/tools/ValidatorUtil.java | 174 ---- .../org/onap/dmaap/mr/client/HostSelector.java | 198 +++++ .../onap/dmaap/mr/client/MRBatchingPublisher.java | 55 ++ .../java/org/onap/dmaap/mr/client/MRClient.java | 66 ++ .../org/onap/dmaap/mr/client/MRClientBuilders.java | 449 ++++++++++ .../org/onap/dmaap/mr/client/MRClientFactory.java | 691 +++++++++++++++ .../java/org/onap/dmaap/mr/client/MRConsumer.java | 54 ++ .../onap/dmaap/mr/client/MRIdentityManager.java | 100 +++ .../java/org/onap/dmaap/mr/client/MRPublisher.java | 93 +++ .../org/onap/dmaap/mr/client/MRTopicManager.java | 183 ++++ .../java/org/onap/dmaap/mr/client/impl/Clock.java | 63 ++ .../onap/dmaap/mr/client/impl/DmaapClientUtil.java | 85 ++ .../onap/dmaap/mr/client/impl/MRBaseClient.java | 395 +++++++++ .../dmaap/mr/client/impl/MRBatchPublisher.java | 487 +++++++++++ .../dmaap/mr/client/impl/MRClientVersionInfo.java | 59 ++ .../org/onap/dmaap/mr/client/impl/MRConstants.java | 179 ++++ .../onap/dmaap/mr/client/impl/MRConsumerImpl.java | 675 +++++++++++++++ .../org/onap/dmaap/mr/client/impl/MRFormat.java | 52 ++ .../onap/dmaap/mr/client/impl/MRMetaClient.java | 266 ++++++ .../mr/client/impl/MRSimplerBatchPublisher.java | 927 +++++++++++++++++++++ .../mr/client/response/MRConsumerResponse.java | 60 ++ .../mr/client/response/MRPublisherResponse.java | 67 ++ .../client/DefaultLoggingFailoverFaultHandler.java | 52 ++ .../dmaap/mr/dme/client/HeaderReplyHandler.java | 63 ++ .../mr/dme/client/PreferredRouteReplyHandler.java | 72 ++ .../dme/client/PreferredRouteRequestHandler.java | 54 ++ .../dmaap/mr/dme/client/SimpleExampleConsumer.java | 88 ++ .../mr/dme/client/SimpleExamplePublisher.java | 135 +++ .../java/org/onap/dmaap/mr/logging/MRAppender.java | 165 ++++ .../dmaap/mr/test/clients/ConsolePublisher.java | 95 +++ .../mr/test/clients/ProtocolTypeConstants.java | 44 + .../onap/dmaap/mr/test/clients/SampleConsumer.java | 87 ++ .../dmaap/mr/test/clients/SamplePublisher.java | 86 ++ .../mr/test/clients/SimpleExampleConsumer.java | 84 ++ .../SimpleExampleConsumerWithReturnResponse.java | 95 +++ .../mr/test/clients/SimpleExamplePublisher.java | 98 +++ .../SimpleExamplePublisherWithResponse.java | 84 ++ .../mr/test/support/MRBatchingPublisherMock.java | 184 ++++ .../onap/dmaap/mr/test/support/MRConsumerMock.java | 169 ++++ .../org/onap/dmaap/mr/tools/ApiKeyCommand.java | 141 ++++ .../java/org/onap/dmaap/mr/tools/AuthCommand.java | 69 ++ .../org/onap/dmaap/mr/tools/ClusterCommand.java | 80 ++ .../org/onap/dmaap/mr/tools/MRCommandContext.java | 100 +++ src/main/java/org/onap/dmaap/mr/tools/MRTool.java | 49 ++ .../org/onap/dmaap/mr/tools/MessageCommand.java | 131 +++ .../java/org/onap/dmaap/mr/tools/ToolsUtil.java | 40 + .../java/org/onap/dmaap/mr/tools/TopicCommand.java | 221 +++++ .../java/org/onap/dmaap/mr/tools/TraceCommand.java | 118 +++ .../org/onap/dmaap/mr/tools/ValidatorUtil.java | 174 ++++ .../com/att/nsa/mr/client/HostSelectorTest.java | 68 -- .../java/com/att/nsa/mr/client/JUnitTestSuite.java | 43 - .../att/nsa/mr/client/MRClientBuildersTest.java | 248 ------ .../com/att/nsa/mr/client/MRClientFactoryTest.java | 252 ------ .../java/com/att/nsa/mr/client/TestRunner.java | 41 - .../nsa/mr/client/impl/DMaapClientUtilTest.java | 85 -- .../att/nsa/mr/client/impl/MRBaseClientTest.java | 471 ----------- .../nsa/mr/client/impl/MRBatchPublisherTest.java | 54 -- .../att/nsa/mr/client/impl/MRConstantsTest.java | 143 ---- .../att/nsa/mr/client/impl/MRConsumerImplTest.java | 112 --- .../att/nsa/mr/client/impl/MRMetaClientTest.java | 129 --- .../mr/client/impl/MRSimplerBatchConsumerTest.java | 76 -- .../client/impl/MRSimplerBatchPublisherTest.java | 96 --- .../att/nsa/mr/client/response/JUnitTestSuite.java | 43 - .../mr/client/response/MRConsumerResponseTest.java | 94 --- .../client/response/MRPublisherResponseTest.java | 104 --- .../com/att/nsa/mr/client/response/TestRunner.java | 41 - .../DefaultLoggingFailoverFaultHandlerTest.java | 69 -- .../nsa/mr/dme/client/HeaderReplyHandlerTest.java | 79 -- .../com/att/nsa/mr/dme/client/JUnitTestSuite.java | 44 - .../dme/client/PreferredRouteReplyHandlerTest.java | 88 -- .../client/PreferredRouteRequestHandlerTest.java | 74 -- .../mr/dme/client/SimpleExamplePublisherTest.java | 68 -- .../java/com/att/nsa/mr/dme/client/TestRunner.java | 41 - .../com/att/nsa/mr/logging/JUnitTestSuite.java | 43 - .../com/att/nsa/mr/logging/MRAppenderTest.java | 184 ---- .../java/com/att/nsa/mr/logging/TestRunner.java | 41 - .../nsa/mr/test/clients/ConsolePublisherTest.java | 55 -- .../att/nsa/mr/test/clients/JUnitTestSuite.java | 45 - .../mr/test/clients/ProtocolTypeConstantsTest.java | 61 -- .../nsa/mr/test/clients/SampleConsumerTest.java | 54 -- .../nsa/mr/test/clients/SamplePublisherTest.java | 55 -- .../mr/test/clients/SimpleExampleConsumerTest.java | 55 -- ...impleExampleConsumerWithReturnResponseTest.java | 54 -- .../test/clients/SimpleExamplePublisherTest.java | 80 -- .../SimpleExamplePublisherWithResponseTest.java | 68 -- .../com/att/nsa/mr/test/clients/TestRunner.java | 41 - .../att/nsa/mr/test/support/JUnitTestSuite.java | 43 - .../test/support/MRBatchingPublisherMockTest.java | 191 ----- .../nsa/mr/test/support/MRConsumerMockTest.java | 174 ---- .../com/att/nsa/mr/test/support/TestRunner.java | 41 - .../com/att/nsa/mr/tools/ApiKeyCommandTest.java | 217 ----- .../java/com/att/nsa/mr/tools/AuthCommandTest.java | 113 --- .../com/att/nsa/mr/tools/ClusterCommandTest.java | 106 --- .../java/com/att/nsa/mr/tools/JUnitTestSuite.java | 44 - .../com/att/nsa/mr/tools/MRCommandContextTest.java | 165 ---- .../com/att/nsa/mr/tools/MessageCommandTest.java | 214 ----- src/test/java/com/att/nsa/mr/tools/TestRunner.java | 41 - .../java/com/att/nsa/mr/tools/ToolsUtilTest.java | 51 -- .../com/att/nsa/mr/tools/TopicCommandTest.java | 224 ----- .../com/att/nsa/mr/tools/TraceCommandTest.java | 102 --- .../com/att/nsa/mr/tools/ValidatorUtilTest.java | 315 ------- .../org/onap/dmaap/mr/client/HostSelectorTest.java | 68 ++ .../org/onap/dmaap/mr/client/JUnitTestSuite.java | 43 + .../onap/dmaap/mr/client/MRClientBuildersTest.java | 248 ++++++ .../onap/dmaap/mr/client/MRClientFactoryTest.java | 252 ++++++ .../java/org/onap/dmaap/mr/client/TestRunner.java | 41 + .../dmaap/mr/client/impl/DMaapClientUtilTest.java | 85 ++ .../dmaap/mr/client/impl/MRBaseClientTest.java | 471 +++++++++++ .../dmaap/mr/client/impl/MRBatchPublisherTest.java | 54 ++ .../onap/dmaap/mr/client/impl/MRConstantsTest.java | 143 ++++ .../dmaap/mr/client/impl/MRConsumerImplTest.java | 112 +++ .../dmaap/mr/client/impl/MRMetaClientTest.java | 129 +++ .../mr/client/impl/MRSimplerBatchConsumerTest.java | 76 ++ .../client/impl/MRSimplerBatchPublisherTest.java | 96 +++ .../dmaap/mr/client/response/JUnitTestSuite.java | 43 + .../mr/client/response/MRConsumerResponseTest.java | 94 +++ .../client/response/MRPublisherResponseTest.java | 104 +++ .../onap/dmaap/mr/client/response/TestRunner.java | 41 + .../DefaultLoggingFailoverFaultHandlerTest.java | 69 ++ .../mr/dme/client/HeaderReplyHandlerTest.java | 79 ++ .../onap/dmaap/mr/dme/client/JUnitTestSuite.java | 44 + .../dme/client/PreferredRouteReplyHandlerTest.java | 88 ++ .../client/PreferredRouteRequestHandlerTest.java | 74 ++ .../mr/dme/client/SimpleExamplePublisherTest.java | 68 ++ .../org/onap/dmaap/mr/dme/client/TestRunner.java | 41 + .../org/onap/dmaap/mr/logging/JUnitTestSuite.java | 43 + .../org/onap/dmaap/mr/logging/MRAppenderTest.java | 184 ++++ .../java/org/onap/dmaap/mr/logging/TestRunner.java | 41 + .../mr/test/clients/ConsolePublisherTest.java | 55 ++ .../onap/dmaap/mr/test/clients/JUnitTestSuite.java | 45 + .../mr/test/clients/ProtocolTypeConstantsTest.java | 61 ++ .../dmaap/mr/test/clients/SampleConsumerTest.java | 54 ++ .../dmaap/mr/test/clients/SamplePublisherTest.java | 55 ++ .../mr/test/clients/SimpleExampleConsumerTest.java | 55 ++ ...impleExampleConsumerWithReturnResponseTest.java | 54 ++ .../test/clients/SimpleExamplePublisherTest.java | 80 ++ .../SimpleExamplePublisherWithResponseTest.java | 68 ++ .../org/onap/dmaap/mr/test/clients/TestRunner.java | 41 + .../onap/dmaap/mr/test/support/JUnitTestSuite.java | 43 + .../test/support/MRBatchingPublisherMockTest.java | 191 +++++ .../dmaap/mr/test/support/MRConsumerMockTest.java | 174 ++++ .../org/onap/dmaap/mr/test/support/TestRunner.java | 41 + .../org/onap/dmaap/mr/tools/ApiKeyCommandTest.java | 217 +++++ .../org/onap/dmaap/mr/tools/AuthCommandTest.java | 113 +++ .../onap/dmaap/mr/tools/ClusterCommandTest.java | 106 +++ .../org/onap/dmaap/mr/tools/JUnitTestSuite.java | 44 + .../onap/dmaap/mr/tools/MRCommandContextTest.java | 165 ++++ .../onap/dmaap/mr/tools/MessageCommandTest.java | 214 +++++ .../java/org/onap/dmaap/mr/tools/TestRunner.java | 41 + .../org/onap/dmaap/mr/tools/ToolsUtilTest.java | 51 ++ .../org/onap/dmaap/mr/tools/TopicCommandTest.java | 224 +++++ .../org/onap/dmaap/mr/tools/TraceCommandTest.java | 102 +++ .../org/onap/dmaap/mr/tools/ValidatorUtilTest.java | 315 +++++++ version.properties | 2 +- 202 files changed, 13424 insertions(+), 13424 deletions(-) delete mode 100644 src/main/java/com/att/nsa/mr/client/HostSelector.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRBatchingPublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRClient.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRClientBuilders.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRClientFactory.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRConsumer.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRIdentityManager.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRPublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/client/MRTopicManager.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/Clock.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/DmaapClientUtil.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRBaseClient.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRBatchPublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRClientVersionInfo.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRConstants.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRConsumerImpl.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRFormat.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRMetaClient.java delete mode 100644 src/main/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/client/response/MRConsumerResponse.java delete mode 100644 src/main/java/com/att/nsa/mr/client/response/MRPublisherResponse.java delete mode 100644 src/main/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandler.java delete mode 100644 src/main/java/com/att/nsa/mr/dme/client/HeaderReplyHandler.java delete mode 100644 src/main/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandler.java delete mode 100644 src/main/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandler.java delete mode 100644 src/main/java/com/att/nsa/mr/dme/client/SimpleExampleConsumer.java delete mode 100644 src/main/java/com/att/nsa/mr/dme/client/SimpleExamplePublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/logging/MRAppender.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/ConsolePublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/ProtocolTypeConstants.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/SampleConsumer.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/SamplePublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumer.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisher.java delete mode 100644 src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponse.java delete mode 100644 src/main/java/com/att/nsa/mr/test/support/MRBatchingPublisherMock.java delete mode 100644 src/main/java/com/att/nsa/mr/test/support/MRConsumerMock.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/ApiKeyCommand.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/AuthCommand.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/ClusterCommand.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/MRCommandContext.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/MRTool.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/MessageCommand.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/ToolsUtil.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/TopicCommand.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/TraceCommand.java delete mode 100644 src/main/java/com/att/nsa/mr/tools/ValidatorUtil.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/HostSelector.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRClient.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRConsumer.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRPublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/Clock.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRBatchPublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java create mode 100644 src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java create mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java create mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java create mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java create mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java create mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java create mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/logging/MRAppender.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java create mode 100644 src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/MRTool.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java create mode 100644 src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java delete mode 100644 src/test/java/com/att/nsa/mr/client/HostSelectorTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/mr/client/MRClientBuildersTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/MRClientFactoryTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/DMaapClientUtilTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/MRBaseClientTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/MRBatchPublisherTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/MRConstantsTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/MRConsumerImplTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/MRMetaClientTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchConsumerTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisherTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/response/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/mr/client/response/MRConsumerResponseTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/response/MRPublisherResponseTest.java delete mode 100644 src/test/java/com/att/nsa/mr/client/response/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java delete mode 100644 src/test/java/com/att/nsa/mr/dme/client/HeaderReplyHandlerTest.java delete mode 100644 src/test/java/com/att/nsa/mr/dme/client/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandlerTest.java delete mode 100644 src/test/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandlerTest.java delete mode 100644 src/test/java/com/att/nsa/mr/dme/client/SimpleExamplePublisherTest.java delete mode 100644 src/test/java/com/att/nsa/mr/dme/client/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/mr/logging/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/mr/logging/MRAppenderTest.java delete mode 100644 src/test/java/com/att/nsa/mr/logging/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/ConsolePublisherTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/ProtocolTypeConstantsTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/SampleConsumerTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/SamplePublisherTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponseTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/clients/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/mr/test/support/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/mr/test/support/MRBatchingPublisherMockTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/support/MRConsumerMockTest.java delete mode 100644 src/test/java/com/att/nsa/mr/test/support/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/ApiKeyCommandTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/AuthCommandTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/ClusterCommandTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/MRCommandContextTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/MessageCommandTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/ToolsUtilTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/TopicCommandTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/TraceCommandTest.java delete mode 100644 src/test/java/com/att/nsa/mr/tools/ValidatorUtilTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mr/logging/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mr/logging/MRAppenderTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/logging/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java diff --git a/pom.xml b/pom.xml index 1da2616..42400c5 100644 --- a/pom.xml +++ b/pom.xml @@ -15,7 +15,7 @@ org.onap.dmaap.messagerouter.dmaapclient dmaapClient jar - 1.1.8-SNAPSHOT + 1.1.9-SNAPSHOT dmaap-messagerouter-dmaapclient Client library for MR event routing API https://github.com/att/dmaap-framework diff --git a/src/main/java/com/att/nsa/mr/client/HostSelector.java b/src/main/java/com/att/nsa/mr/client/HostSelector.java deleted file mode 100644 index 63ef404..0000000 --- a/src/main/java/com/att/nsa/mr/client/HostSelector.java +++ /dev/null @@ -1,198 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Random; -import java.util.Set; -import java.util.TreeSet; -import java.util.Vector; -import java.util.concurrent.DelayQueue; -import java.util.concurrent.Delayed; -import java.util.concurrent.TimeUnit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HostSelector -{ - private final TreeSet fBaseHosts; - private final DelayQueue fBlacklist; - private String fIdealHost; - private String fCurrentHost; - private static final Logger log = LoggerFactory.getLogger(HostSelector.class); - - public HostSelector(String hostPart) - { - this(makeSet(hostPart), null); - } - - public HostSelector(Collection baseHosts) - { - this(baseHosts, null); - } - - public HostSelector(Collection baseHosts, String signature) - { - if (baseHosts.isEmpty()) - { - throw new IllegalArgumentException("At least one host must be provided."); - } - - this.fBaseHosts = new TreeSet(baseHosts); - this.fBlacklist = new DelayQueue(); - this.fIdealHost = null; - - if (signature == null) { - return; - } - int index = 0 ; - int value = signature.hashCode(); - if(value!=0) { - index = Math.abs(value) % baseHosts.size(); - } - Iterator it = this.fBaseHosts.iterator(); - while (index-- > 0) - { - it.next(); - } - this.fIdealHost = ((String)it.next()); - } - - public String selectBaseHost() - { - if (this.fCurrentHost == null) - { - makeSelection(); - } - return this.fCurrentHost; - } - - public void reportReachabilityProblem(long blacklistUnit, TimeUnit blacklistTimeUnit) - { - if (this.fCurrentHost == null) - { - log.warn("Reporting reachability problem, but no host is currently selected."); - } - - if (blacklistUnit > 0L) - { - for (BlacklistEntry be : this.fBlacklist) - { - if (be.getHost().equals(this.fCurrentHost)) - { - be.expireNow(); - } - } - - LinkedList devNull = new LinkedList(); - this.fBlacklist.drainTo(devNull); - - if (this.fCurrentHost != null) - { - this.fBlacklist.add(new BlacklistEntry(this.fCurrentHost, TimeUnit.MILLISECONDS.convert(blacklistUnit, blacklistTimeUnit))); - } - } - this.fCurrentHost = null; - } - - private String makeSelection() - { - TreeSet workingSet = new TreeSet(this.fBaseHosts); - - LinkedList devNull = new LinkedList(); - this.fBlacklist.drainTo(devNull); - for (BlacklistEntry be : this.fBlacklist) - { - workingSet.remove(be.getHost()); - } - - if (workingSet.isEmpty()) - { - log.warn("All hosts were blacklisted; reverting to full set of hosts."); - workingSet.addAll(this.fBaseHosts); - this.fCurrentHost = null; - } - - String selection = null; - if ((this.fCurrentHost != null) && (workingSet.contains(this.fCurrentHost))) - { - selection = this.fCurrentHost; - } - else if ((this.fIdealHost != null) && (workingSet.contains(this.fIdealHost))) - { - selection = this.fIdealHost; - } - else - { - int index = 0; - int value = new Random().nextInt(); - Vector v = new Vector(workingSet); - if(value!=0) { - index = Math.abs(value) % workingSet.size(); - } - selection = (String)v.elementAt(index); - } - - this.fCurrentHost = selection; - return this.fCurrentHost; - } - - private static Set makeSet(String s) - { - TreeSet set = new TreeSet(); - set.add(s); - return set; } - - private static class BlacklistEntry implements Delayed { - private final String fHost; - private long fExpireAtMs; - - public BlacklistEntry(String host, long delayMs) { - this.fHost = host; - this.fExpireAtMs = (System.currentTimeMillis() + delayMs); - } - - public void expireNow() - { - this.fExpireAtMs = 0L; - } - - public String getHost() - { - return this.fHost; - } - - public int compareTo(Delayed o) - { - Long thisDelay = Long.valueOf(getDelay(TimeUnit.MILLISECONDS)); - return thisDelay.compareTo(Long.valueOf(o.getDelay(TimeUnit.MILLISECONDS))); - } - - public long getDelay(TimeUnit unit) - { - long remainingMs = this.fExpireAtMs - System.currentTimeMillis(); - return unit.convert(remainingMs, TimeUnit.MILLISECONDS); - } - } -} diff --git a/src/main/java/com/att/nsa/mr/client/MRBatchingPublisher.java b/src/main/java/com/att/nsa/mr/client/MRBatchingPublisher.java deleted file mode 100644 index 875b5a3..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRBatchingPublisher.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; -import com.att.nsa.mr.client.response.MRPublisherResponse; - -/** - * A MR batching publisher is a publisher with additional functionality - * for managing delayed sends. - * - * @author author - * - */ -public interface MRBatchingPublisher extends MRPublisher -{ - /** - * Get the number of messages that have not yet been sent. - * @return the number of pending messages - */ - int getPendingMessageCount (); - - /** - * Close this publisher, sending any remaining messages. - * @param timeout an amount of time to wait for unsent messages to be sent - * @param timeoutUnits the time unit for the timeout arg - * @return a list of any unsent messages after the timeout - * @throws IOException exception - * @throws InterruptedException exception - */ - List close ( long timeout, TimeUnit timeoutUnits ) throws IOException, InterruptedException; - - MRPublisherResponse sendBatchWithResponse (); -} diff --git a/src/main/java/com/att/nsa/mr/client/MRClient.java b/src/main/java/com/att/nsa/mr/client/MRClient.java deleted file mode 100644 index f3a8f43..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRClient.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import org.slf4j.Logger; - - -public interface MRClient -{ - /** - * An exception at the MR layer. This is used when the HTTP transport - * layer returns a success code but the transaction is not completed as expected. - */ - public class MRApiException extends Exception - { - private static final long serialVersionUID = 1L; - public MRApiException ( String msg ) { super ( msg ); } - public MRApiException ( String msg, Throwable t ) { super ( msg, t ); } - } - - /** - * Optionally set the Logger to use - * @param log log - */ - void logTo ( Logger log ); - - /** - * Set the API credentials for this client connection. Subsequent calls will - * include authentication headers.who i - */ - /** - * @param apiKey apikey - * @param apiSecret apisec - */ - void setApiCredentials ( String apiKey, String apiSecret ); - - /** - * Remove API credentials, if any, on this connection. Subsequent calls will not include - * authentication headers. - */ - void clearApiCredentials (); - - /** - * Close this connection. Some client interfaces have additional close capability. - */ - void close (); -} diff --git a/src/main/java/com/att/nsa/mr/client/MRClientBuilders.java b/src/main/java/com/att/nsa/mr/client/MRClientBuilders.java deleted file mode 100644 index 73ef5c4..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRClientBuilders.java +++ /dev/null @@ -1,449 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.net.MalformedURLException; -import java.util.Collection; -import java.util.TreeSet; -import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.mr.client.impl.MRConsumerImpl; -import com.att.nsa.mr.client.impl.MRMetaClient; -import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher; - -/** - * A collection of builders for various types of MR API clients - * - * @author author - */ -public class MRClientBuilders -{ - - /** - * Instantiates MRClientBuilders. - */ - private MRClientBuilders() { - // prevent instantiation - } - - /** - * A builder for a topic Consumer - * @author author - */ - public static class ConsumerBuilder - { - /** - * Construct a consumer builder. - */ - public ConsumerBuilder () {} - - /** - * Set the host list - * @param hostList a comma-separated list of hosts to use to connect to MR - * @return this builder - */ - public ConsumerBuilder usingHosts ( String hostList ) { - return usingHosts ( MRConsumerImpl.stringToList(hostList) ); - } - - /** - * Set the host list - * @param hostSet a set of hosts to use to connect to MR - * @return this builder - */ - public ConsumerBuilder usingHosts ( Collection hostSet ) { - fHosts = hostSet; return this; - } - - /** - * Set the topic - * @param topic the name of the topic to consume - * @return this builder - */ - public ConsumerBuilder onTopic ( String topic ) { - fTopic=topic; - return this; - } - - /** - * Set the consumer's group and ID - * @param consumerGroup The name of the consumer group this consumer is part of - * @param consumerId The unique id of this consumer in its group - * @return this builder - */ - public ConsumerBuilder knownAs ( String consumerGroup, String consumerId ) { - fGroup = consumerGroup; - fId = consumerId; - return this; - } - - /** - * Set the API key and secret for this client. - * @param apiKey - * @param apiSecret - * @return this builder - */ - public ConsumerBuilder authenticatedBy ( String apiKey, String apiSecret ) { - fApiKey = apiKey; - fApiSecret = apiSecret; - return this; - } - - /** - * Set the server side timeout - * @param timeoutMs The amount of time in milliseconds that the server should keep the connection open while waiting for message traffic. - * @return this builder - */ - public ConsumerBuilder waitAtServer ( int timeoutMs ) { - fTimeoutMs = timeoutMs; - return this; - }; - - /** - * Set the maximum number of messages to receive per transaction - * @param limit The maximum number of messages to receive from the server in one transaction. - * @return this builder - */ - public ConsumerBuilder receivingAtMost ( int limit ) { - fLimit = limit; - return this; - }; - - /** - * Set a filter to use on the server - * @param filter a Highland Park standard library filter encoded in JSON - * @return this builder - */ - public ConsumerBuilder withServerSideFilter ( String filter ) { - fFilter = filter; - return this; - } - - /** - * Build the consumer - * @return a consumer - */ - public MRConsumer build () - { - if ( fHosts == null || fHosts.size() == 0 || fTopic == null ) - { - throw new IllegalArgumentException ( "You must provide at least one host and a topic name." ); - } - - if ( fGroup == null ) - { - fGroup = UUID.randomUUID ().toString (); - fId = "0"; - log.info ( "Creating non-restartable client with group " + fGroup + " and ID " + fId + "." ); - } - - if ( sfConsumerMock != null ) return sfConsumerMock; - try { - return new MRConsumerImpl ( fHosts, fTopic, fGroup, fId, fTimeoutMs, fLimit, fFilter, fApiKey, fApiSecret ); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } - - private Collection fHosts = null; - private String fTopic = null; - private String fGroup = null; - private String fId = null; - private String fApiKey = null; - private String fApiSecret = null; - private int fTimeoutMs = -1; - private int fLimit = -1; - private String fFilter = null; - } - - /*************************************************************************/ - /*************************************************************************/ - /*************************************************************************/ - - /** - * A publisher builder - * @author author - */ - public static class PublisherBuilder - { - public PublisherBuilder () {} - - /** - * Set the MR/UEB host(s) to use - * @param hostlist The host(s) used in the URL to MR. Can be "host:port", can be multiple comma-separated entries. - * @return this builder - */ - public PublisherBuilder usingHosts ( String hostlist ) { - return usingHosts ( MRConsumerImpl.stringToList(hostlist) ); - } - - /** - * Set the MR/UEB host(s) to use - * @param hostSet The host(s) used in the URL to MR. Can be "host:port" - * @return this builder - */ - public PublisherBuilder usingHosts ( String[] hostSet ) - { - final TreeSet hosts = new TreeSet (); - for ( String hp : hostSet ) - { - hosts.add ( hp ); - } - return usingHosts ( hosts ); - } - - /** - * Set the MR/UEB host(s) to use - * @param hostlist The host(s) used in the URL to MR. Can be "host:port". - * @return this builder - */ - public PublisherBuilder usingHosts ( Collection hostlist ) { - fHosts=hostlist; - return this; - } - - /** - * Set the topic to publish on - * @param topic The topic on which to publish messages. - * @return this builder - */ - public PublisherBuilder onTopic ( String topic ) { - fTopic = topic; - return this; - } - - /** - * Batch message sends with the given limits. - * @param messageCount The largest set of messages to batch. - * @param ageInMs The maximum age of a message waiting in a batch. - * @return this builder - */ - public PublisherBuilder limitBatch ( int messageCount, int ageInMs ) { - fMaxBatchSize = messageCount; - fMaxBatchAgeMs = ageInMs; - return this; - } - - /** - * Compress transactions - * @return this builder - */ - public PublisherBuilder withCompresion () { - return enableCompresion(true); - } - - /** - * Do not compress transactions - * @return this builder - */ - public PublisherBuilder withoutCompresion () { - return enableCompresion(false); - } - - /** - * Set the compression option - * @param compress true to gzip compress transactions - * @return this builder - */ - public PublisherBuilder enableCompresion ( boolean compress ) { - fCompress = compress; - return this; - } - - /** - * Set the API key and secret for this client. - * @param apiKey - * @param apiSecret - * @return this builder - */ - public PublisherBuilder authenticatedBy ( String apiKey, String apiSecret ) { - fApiKey = apiKey; - fApiSecret = apiSecret; - return this; - } - - /** - * Build the publisher - * @return a batching publisher - */ - public MRBatchingPublisher build () - { - if ( fHosts == null || fHosts.isEmpty() || fTopic == null ) - { - throw new IllegalArgumentException ( "You must provide at least one host and a topic name." ); - } - - if ( sfPublisherMock != null ) return sfPublisherMock; - - final MRSimplerBatchPublisher pub = new MRSimplerBatchPublisher.Builder (). - againstUrls ( fHosts ). - onTopic ( fTopic ). - batchTo ( fMaxBatchSize, fMaxBatchAgeMs ). - compress ( fCompress ). - build (); - if ( fApiKey != null ) - { - pub.setApiCredentials ( fApiKey, fApiSecret ); - } - return pub; - } - - private Collection fHosts = null; - private String fTopic = null; - private int fMaxBatchSize = 1; - private int fMaxBatchAgeMs = 1; - private boolean fCompress = false; - private String fApiKey = null; - private String fApiSecret = null; - } - - /** - * A builder for an identity manager - * @author author - */ - public static class IdentityManagerBuilder extends AbstractAuthenticatedManagerBuilder - { - /** - * Construct an identity manager builder. - */ - public IdentityManagerBuilder () {} - - @Override - protected MRIdentityManager constructClient ( Collection hosts ) { try { - return new MRMetaClient ( hosts ); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } } - } - - /** - * A builder for a topic manager - * @author author - */ - public static class TopicManagerBuilder extends AbstractAuthenticatedManagerBuilder - { - /** - * Construct an topic manager builder. - */ - public TopicManagerBuilder () {} - - @Override - protected MRTopicManager constructClient ( Collection hosts ) { try { - return new MRMetaClient ( hosts ); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } } - } - - /** - * Inject a consumer. Used to support unit tests. - * @param cc - */ - public static void $testInject ( MRConsumer cc ) - { - sfConsumerMock = cc; - } - - /** - * Inject a publisher. Used to support unit tests. - * @param pub - */ - public static void $testInject ( MRBatchingPublisher pub ) - { - sfPublisherMock = pub; - } - - static MRConsumer sfConsumerMock = null; - static MRBatchingPublisher sfPublisherMock = null; - - /** - * A builder for an identity manager - * @author author - */ - public static abstract class AbstractAuthenticatedManagerBuilder - { - /** - * Construct an identity manager builder. - */ - public AbstractAuthenticatedManagerBuilder () {} - - /** - * Set the host list - * @param hostList a comma-separated list of hosts to use to connect to MR - * @return this builder - */ - public AbstractAuthenticatedManagerBuilder usingHosts ( String hostList ) { - return usingHosts ( MRConsumerImpl.stringToList(hostList) ); - } - - /** - * Set the host list - * @param hostSet a set of hosts to use to connect to MR - * @return this builder - */ - public AbstractAuthenticatedManagerBuilder usingHosts ( Collection hostSet ) { - fHosts = hostSet; - return this; - } - - /** - * Set the API key and secret for this client. - * @param apiKey - * @param apiSecret - * @return this builder - */ - public AbstractAuthenticatedManagerBuilder authenticatedBy ( String apiKey, String apiSecret ) { - fApiKey = apiKey; - fApiSecret = apiSecret; - return this; - } - - /** - * Build the consumer - * @return a consumer - */ - public T build () - { - if ( fHosts.isEmpty() ) - { - throw new IllegalArgumentException ( "You must provide at least one host and a topic name." ); - } - - final T mgr = constructClient ( fHosts ); - mgr.setApiCredentials ( fApiKey, fApiSecret ); - return mgr; - } - - protected abstract T constructClient ( Collection hosts ); - - private Collection fHosts = null; - private String fApiKey = null; - private String fApiSecret = null; - } - - private static final Logger log = LoggerFactory.getLogger ( MRClientBuilders.class ); -} diff --git a/src/main/java/com/att/nsa/mr/client/MRClientFactory.java b/src/main/java/com/att/nsa/mr/client/MRClientFactory.java deleted file mode 100644 index 689190e..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRClientFactory.java +++ /dev/null @@ -1,691 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.TreeSet; -import java.util.UUID; - -import javax.ws.rs.core.MultivaluedMap; - -import com.att.nsa.mr.client.impl.MRConsumerImpl; -import com.att.nsa.mr.client.impl.MRMetaClient; -import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher; -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; -import com.att.nsa.mr.tools.ValidatorUtil; - -/** - * A factory for MR clients.
- *
- * Use caution selecting a consumer creator factory. If the call doesn't accept - * a consumer group name, then it creates a consumer that is not restartable. - * That is, if you stop your process and start it again, your client will NOT - * receive any missed messages on the topic. If you need to ensure receipt of - * missed messages, then you must use a consumer that's created with a group - * name and ID. (If you create multiple consumer processes using the same group, - * load is split across them. Be sure to use a different ID for each - * instance.)
- *
- * Publishers - * - * @author author - */ -public class MRClientFactory { - private static final String AUTH_KEY = "authKey"; - private static final String AUTH_DATE = "authDate"; - private static final String PASSWORD = "password"; - private static final String USERNAME = "username"; - private static final String DME2PREFERRED_ROUTER_FILE_PATH = "DME2preferredRouterFilePath"; - private static final String TOPIC = "topic"; - private static final String TRANSPORT_TYPE = "TransportType"; - public static MultivaluedMap HTTPHeadersMap; - public static Map DME2HeadersMap; - public static String routeFilePath; - - public static FileReader routeReader; - - public static FileWriter routeWriter = null; - public static Properties prop = null; - - /** - * Instantiates MRClientFactory. - */ - private MRClientFactory() { - //prevents instantiation. - } - - /** - * Create a consumer instance with the default timeout and no limit on - * messages returned. This consumer operates as an independent consumer - * (i.e., not in a group) and is NOT re-startable across sessions. - * - * @param hostList - * A comma separated list of hosts to use to connect to MR. You - * can include port numbers (3904 is the default). For example, - * "hostname:8080," - * - * @param topic - * The topic to consume - * - * @return a consumer - */ - public static MRConsumer createConsumer(String hostList, String topic) { - return createConsumer(MRConsumerImpl.stringToList(hostList), topic); - } - - /** - * Create a consumer instance with the default timeout and no limit on - * messages returned. This consumer operates as an independent consumer - * (i.e., not in a group) and is NOT re-startable across sessions. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * - * @return a consumer - */ - public static MRConsumer createConsumer(Collection hostSet, String topic) { - return createConsumer(hostSet, topic, null); - } - - /** - * Create a consumer instance with server-side filtering, the default - * timeout, and no limit on messages returned. This consumer operates as an - * independent consumer (i.e., not in a group) and is NOT re-startable - * across sessions. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param filter - * a filter to use on the server side - * - * @return a consumer - */ - public static MRConsumer createConsumer(Collection hostSet, String topic, String filter) { - return createConsumer(hostSet, topic, UUID.randomUUID().toString(), "0", -1, -1, filter, null, null); - } - - /** - * Create a consumer instance with the default timeout, and no limit on - * messages returned. This consumer can operate in a logical group and is - * re-startable across sessions when you use the same group and ID on - * restart. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * - * @return a consumer - */ - public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, - final String consumerId) { - return createConsumer(hostSet, topic, consumerGroup, consumerId, -1, -1); - } - - /** - * Create a consumer instance with the default timeout, and no limit on - * messages returned. This consumer can operate in a logical group and is - * re-startable across sessions when you use the same group and ID on - * restart. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * @param timeoutMs - * The amount of time in milliseconds that the server should keep - * the connection open while waiting for message traffic. Use -1 - * for default timeout. - * @param limit - * A limit on the number of messages returned in a single call. - * Use -1 for no limit. - * - * @return a consumer - */ - public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit) { - return createConsumer(hostSet, topic, consumerGroup, consumerId, timeoutMs, limit, null, null, null); - } - - /** - * Create a consumer instance with the default timeout, and no limit on - * messages returned. This consumer can operate in a logical group and is - * re-startable across sessions when you use the same group and ID on - * restart. This consumer also uses server-side filtering. - * - * @param hostList - * A comma separated list of hosts to use to connect to MR. You - * can include port numbers (3904 is the default). For example, - * "ueb01hydc.it.att.com:8080,ueb02hydc.it.att.com" - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * @param timeoutMs - * The amount of time in milliseconds that the server should keep - * the connection open while waiting for message traffic. Use -1 - * for default timeout. - * @param limit - * A limit on the number of messages returned in a single call. - * Use -1 for no limit. - * @param filter - * A Highland Park filter expression using only built-in filter - * components. Use null for "no filter". - * - * @return a consumer - */ - public static MRConsumer createConsumer(String hostList, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { - return createConsumer(MRConsumerImpl.stringToList(hostList), topic, consumerGroup, consumerId, timeoutMs, limit, - filter, apiKey, apiSecret); - } - - /** - * Create a consumer instance with the default timeout, and no limit on - * messages returned. This consumer can operate in a logical group and is - * re-startable across sessions when you use the same group and ID on - * restart. This consumer also uses server-side filtering. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * @param timeoutMs - * The amount of time in milliseconds that the server should keep - * the connection open while waiting for message traffic. Use -1 - * for default timeout. - * @param limit - * A limit on the number of messages returned in a single call. - * Use -1 for no limit. - * @param filter - * A Highland Park filter expression using only built-in filter - * components. Use null for "no filter". - * - * @return a consumer - */ - public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { - if (MRClientBuilders.sfConsumerMock != null) - return MRClientBuilders.sfConsumerMock; - try { - return new MRConsumerImpl(hostSet, topic, consumerGroup, consumerId, timeoutMs, limit, filter, apiKey, - apiSecret); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } - - /*************************************************************************/ - /*************************************************************************/ - /*************************************************************************/ - - /** - * Create a publisher that sends each message (or group of messages) - * immediately. Most applications should favor higher latency for much - * higher message throughput and the "simple publisher" is not a good - * choice. - * - * @param hostlist - * The host used in the URL to MR. Can be "host:port", can be - * multiple comma-separated entries. - * @param topic - * The topic on which to publish messages. - * @return a publisher - */ - public static MRBatchingPublisher createSimplePublisher(String hostlist, String topic) { - return createBatchingPublisher(hostlist, topic, 1, 1); - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown. Message payloads are - * not compressed. - * - * @param hostlist - * The host used in the URL to MR. Can be "host:port", can be - * multiple comma-separated entries. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * - * @return a publisher - */ - public static MRBatchingPublisher createBatchingPublisher(String hostlist, String topic, int maxBatchSize, - long maxAgeMs) { - return createBatchingPublisher(hostlist, topic, maxBatchSize, maxAgeMs, false); - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown. - * - * @param hostlist - * The host used in the URL to MR. Can be "host:port", can be - * multiple comma-separated entries. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * - * @return a publisher - */ - public static MRBatchingPublisher createBatchingPublisher(String hostlist, String topic, int maxBatchSize, - long maxAgeMs, boolean compress) { - return createBatchingPublisher(MRConsumerImpl.stringToList(hostlist), topic, maxBatchSize, maxAgeMs, compress); - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * - * @return a publisher - */ - public static MRBatchingPublisher createBatchingPublisher(String[] hostSet, String topic, int maxBatchSize, - long maxAgeMs, boolean compress) { - final TreeSet hosts = new TreeSet(); - for (String hp : hostSet) { - hosts.add(hp); - } - return createBatchingPublisher(hosts, topic, maxBatchSize, maxAgeMs, compress); - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * - * @return a publisher - */ - public static MRBatchingPublisher createBatchingPublisher(Collection hostSet, String topic, - int maxBatchSize, long maxAgeMs, boolean compress) { - return new MRSimplerBatchPublisher.Builder().againstUrls(hostSet).onTopic(topic).batchTo(maxBatchSize, maxAgeMs) - .compress(compress).build(); - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown. - * - * @param host - * A host to be used in the URL to MR. Can be "host:port". Use - * multiple entries to enable failover. - * @param topic - * The topic on which to publish messages. - * @param username - * username - * @param password - * password - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * @param protocolFlag - * http auth or ueb auth or dme2 method - * @param producerFilePath - * all properties for publisher - * @return MRBatchingPublisher obj - */ - public static MRBatchingPublisher createBatchingPublisher(String host, String topic, final String username, - final String password, int maxBatchSize, long maxAgeMs, boolean compress, String protocolFlag) { - MRSimplerBatchPublisher pub = new MRSimplerBatchPublisher.Builder() - .againstUrls(MRConsumerImpl.stringToList(host)).onTopic(topic).batchTo(maxBatchSize, maxAgeMs) - .compress(compress).build(); - - pub.setHost(host); - pub.setUsername(username); - pub.setPassword(password); - pub.setProtocolFlag(protocolFlag); - return pub; - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown - * - * @param Properties - * props set all properties for publishing message - * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex - */ - public static MRBatchingPublisher createBatchingPublisher(Properties props, boolean withResponse) - throws FileNotFoundException, IOException { - return createInternalBatchingPublisher(props, withResponse); - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown - * - * @param Properties - * props set all properties for publishing message - * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex - */ - public static MRBatchingPublisher createBatchingPublisher(Properties props) - throws FileNotFoundException, IOException { - return createInternalBatchingPublisher(props, false); - } - - /** - * Create a publisher that batches messages. Be sure to close the publisher - * to send the last batch and ensure a clean shutdown - * - * @param producerFilePath - * set all properties for publishing message - * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex - */ - public static MRBatchingPublisher createBatchingPublisher(final String producerFilePath) - throws FileNotFoundException, IOException { - FileReader reader = new FileReader(new File(producerFilePath)); - Properties props = new Properties(); - props.load(reader); - return createBatchingPublisher(props); - } - - /** - * Create a publisher that will contain send methods that return response - * object to user. - * - * @param producerFilePath - * set all properties for publishing message - * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex - */ - public static MRBatchingPublisher createBatchingPublisher(final String producerFilePath, boolean withResponse) - throws FileNotFoundException, IOException { - FileReader reader = new FileReader(new File(producerFilePath)); - Properties props = new Properties(); - props.load(reader); - return createBatchingPublisher(props, withResponse); - } - - protected static MRBatchingPublisher createInternalBatchingPublisher(Properties props, boolean withResponse) - throws FileNotFoundException, IOException { - assert props != null; - MRSimplerBatchPublisher pub; - if (withResponse) { - pub = new MRSimplerBatchPublisher.Builder() - .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty("host")),MRConsumerImpl.stringToList(props.getProperty("ServiceName")), props.getProperty(TRANSPORT_TYPE)) - .onTopic(props.getProperty(TOPIC)) - .batchTo(Integer.parseInt(props.getProperty("maxBatchSize")), - Integer.parseInt(props.getProperty("maxAgeMs").toString())) - .compress(Boolean.parseBoolean(props.getProperty("compress"))) - .httpThreadTime(Integer.parseInt(props.getProperty("MessageSentThreadOccurance"))) - .withResponse(withResponse).build(); - } else { - pub = new MRSimplerBatchPublisher.Builder() - .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty("host")), MRConsumerImpl.stringToList(props.getProperty("ServiceName")), props.getProperty(TRANSPORT_TYPE)) - .onTopic(props.getProperty(TOPIC)) - .batchTo(Integer.parseInt(props.getProperty("maxBatchSize")), - Integer.parseInt(props.getProperty("maxAgeMs").toString())) - .compress(Boolean.parseBoolean(props.getProperty("compress"))) - .httpThreadTime(Integer.parseInt(props.getProperty("MessageSentThreadOccurance"))).build(); - } - pub.setHost(props.getProperty("host")); - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.AUTH_KEY.getValue())) { - - pub.setAuthKey(props.getProperty(AUTH_KEY)); - pub.setAuthDate(props.getProperty(AUTH_DATE)); - pub.setUsername(props.getProperty(USERNAME)); - pub.setPassword(props.getProperty(PASSWORD)); - } else { - pub.setUsername(props.getProperty(USERNAME)); - pub.setPassword(props.getProperty(PASSWORD)); - } - pub.setProtocolFlag(props.getProperty(TRANSPORT_TYPE)); - pub.setProps(props); - prop = new Properties(); - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.DME2.getValue())) { - routeFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH); - routeReader = new FileReader(new File(routeFilePath)); - File fo = new File(routeFilePath); - if (!fo.exists()) { - routeWriter = new FileWriter(new File(routeFilePath)); - } - } - return pub; - } - - /** - * Create an identity manager client to work with API keys. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param apiKey - * Your API key - * @param apiSecret - * Your API secret - * @return an identity manager - */ - public static MRIdentityManager createIdentityManager(Collection hostSet, String apiKey, String apiSecret) { - MRIdentityManager cim; - try { - cim = new MRMetaClient(hostSet); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - cim.setApiCredentials(apiKey, apiSecret); - return cim; - } - - /** - * Create a topic manager for working with topics. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param apiKey - * Your API key - * @param apiSecret - * Your API secret - * @return a topic manager - */ - public static MRTopicManager createTopicManager(Collection hostSet, String apiKey, String apiSecret) { - MRMetaClient tmi; - try { - tmi = new MRMetaClient(hostSet); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - tmi.setApiCredentials(apiKey, apiSecret); - return tmi; - } - - /** - * Inject a consumer. Used to support unit tests. - * - * @param cc - */ - public static void $testInject(MRConsumer cc) { - MRClientBuilders.sfConsumerMock = cc; - } - - public static MRConsumer createConsumer(String host, String topic, String username, String password, String group, - String id, int i, int j, String protocalFlag, String consumerFilePath) { - - MRConsumerImpl sub; - try { - sub = new MRConsumerImpl(MRConsumerImpl.stringToList(host), topic, group, id, i, j, null, null, null); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - sub.setUsername(username); - sub.setPassword(password); - sub.setHost(host); - sub.setProtocolFlag(protocalFlag); - sub.setConsumerFilePath(consumerFilePath); - return sub; - - } - - public static MRConsumer createConsumer(String host, String topic, String username, String password, String group, - String id, String protocalFlag, String consumerFilePath, int i, int j) { - - MRConsumerImpl sub; - try { - sub = new MRConsumerImpl(MRConsumerImpl.stringToList(host), topic, group, id, i, j, null, null, null); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - sub.setUsername(username); - sub.setPassword(password); - sub.setHost(host); - sub.setProtocolFlag(protocalFlag); - sub.setConsumerFilePath(consumerFilePath); - return sub; - - } - - public static MRConsumer createConsumer(String consumerFilePath) throws FileNotFoundException, IOException { - FileReader reader = new FileReader(new File(consumerFilePath)); - Properties props = new Properties(); - props.load(reader); - - return createConsumer(props); - } - - public static MRConsumer createConsumer(Properties props) throws FileNotFoundException, IOException { - int timeout; - ValidatorUtil.validateSubscriber(props); - if (props.getProperty("timeout") != null) - timeout = Integer.parseInt(props.getProperty("timeout")); - else - timeout = -1; - int limit; - if (props.getProperty("limit") != null) - limit = Integer.parseInt(props.getProperty("limit")); - else - limit = -1; - String group; - if (props.getProperty("group") == null) - group = UUID.randomUUID().toString(); - else - group = props.getProperty("group"); - MRConsumerImpl sub = null; - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.AUTH_KEY.getValue())) { - sub = new MRConsumerImpl(MRConsumerImpl.stringToList(props.getProperty("host")), props.getProperty(TOPIC), - group, props.getProperty("id"), timeout, limit, props.getProperty("filter"), - props.getProperty(AUTH_KEY), props.getProperty(AUTH_DATE)); - sub.setAuthKey(props.getProperty(AUTH_KEY)); - sub.setAuthDate(props.getProperty(AUTH_DATE)); - sub.setUsername(props.getProperty(USERNAME)); - sub.setPassword(props.getProperty(PASSWORD)); - } else { - sub = new MRConsumerImpl(MRConsumerImpl.stringToList(props.getProperty("host")), props.getProperty(TOPIC), - group, props.getProperty("id"), timeout, limit, props.getProperty("filter"), - props.getProperty(USERNAME), props.getProperty(PASSWORD)); - sub.setUsername(props.getProperty(USERNAME)); - sub.setPassword(props.getProperty(PASSWORD)); - } - - sub.setProps(props); - sub.setHost(props.getProperty("host")); - sub.setProtocolFlag(props.getProperty(TRANSPORT_TYPE)); - sub.setfFilter(props.getProperty("filter")); - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.DME2.getValue())) { - MRConsumerImpl.setRouterFilePath(props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH)); - routeFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH); - routeReader = new FileReader(new File(routeFilePath)); - prop = new Properties(); - File fo = new File(routeFilePath); - if (!fo.exists()) { - routeWriter = new FileWriter(new File(routeFilePath)); - } - } - - return sub; - } -} diff --git a/src/main/java/com/att/nsa/mr/client/MRConsumer.java b/src/main/java/com/att/nsa/mr/client/MRConsumer.java deleted file mode 100644 index 444eb7c..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRConsumer.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.io.IOException; - -import com.att.nsa.mr.client.response.MRConsumerResponse; - -public interface MRConsumer extends MRClient -{ - /** - * Fetch a set of messages. The consumer's timeout and message limit are used if set in the constructor call. - - * @return a set of messages - * @throws IOException - */ - Iterable fetch () throws IOException, Exception; - - /** - * Fetch a set of messages with an explicit timeout and limit for this call. These values - * override any set in the constructor call. - * - * @param timeoutMs The amount of time in milliseconds that the server should keep the connection - * open while waiting for message traffic. Use -1 for default timeout (controlled on the server-side). - * @param limit A limit on the number of messages returned in a single call. Use -1 for no limit. - * @return a set messages - * @throws IOException if there's a problem connecting to the server - */ - Iterable fetch ( int timeoutMs, int limit ) throws IOException, Exception; - - MRConsumerResponse fetchWithReturnConsumerResponse (); - - - MRConsumerResponse fetchWithReturnConsumerResponse ( int timeoutMs, int limit ); -} diff --git a/src/main/java/com/att/nsa/mr/client/MRIdentityManager.java b/src/main/java/com/att/nsa/mr/client/MRIdentityManager.java deleted file mode 100644 index 5483761..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRIdentityManager.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.io.IOException; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; - -/** - * A client for manipulating API keys. - * @author author - * - */ -public interface MRIdentityManager extends MRClient -{ - /** - * An API Key record - */ - public interface ApiKey - { - /** - * Get the email address associated with the API key - * @return the email address on the API key or null - */ - String getEmail (); - - /** - * Get the description associated with the API key - * @return the description on the API key or null - */ - String getDescription (); - } - - /** - * Create a new API key on the UEB cluster. The returned credential instance - * contains the new API key and API secret. This is the only time the secret - * is available to the client -- there's no API for retrieving it later -- so - * your application must store it securely. - * - * @param email - * @param description - * @return a new credential - * @throws HttpException - * @throws MRApiException - * @throws IOException - */ - ApiCredential createApiKey ( String email, String description ) throws HttpException, MRApiException, IOException; - - /** - * Get basic info about a known API key - * @param apiKey - * @return the API key's info or null if it doesn't exist - * @throws HttpObjectNotFoundException, HttpException, MRApiException - * @throws IOException - */ - ApiKey getApiKey ( String apiKey ) throws HttpObjectNotFoundException, HttpException, MRApiException, IOException; - - /** - * Update the record for the API key used to authenticate this request. The UEB - * API requires that you authenticate with the same key you're updating, so the - * API key being changed is the one used for setApiCredentials. - * - * @param email use null to keep the current value - * @param description use null to keep the current value - * @throws IOException - * @throws HttpException - * @throws HttpObjectNotFoundException - */ - void updateCurrentApiKey ( String email, String description ) throws HttpObjectNotFoundException, HttpException, IOException; - - /** - * Delete the *current* API key. After this call returns, the API key - * used to authenticate will no longer be valid. - * - * @throws IOException - * @throws HttpException - */ - void deleteCurrentApiKey () throws HttpException, IOException; -} diff --git a/src/main/java/com/att/nsa/mr/client/MRPublisher.java b/src/main/java/com/att/nsa/mr/client/MRPublisher.java deleted file mode 100644 index 651c548..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRPublisher.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.io.IOException; -import java.util.Collection; - -/** - * A MR publishing interface. - * - */ -public interface MRPublisher extends MRClient -{ - /** - * A simple message container - */ - public static class message - { - public message ( String partition, String msg ) - { - fPartition = partition == null ? "" : partition; - fMsg = msg; - if ( fMsg == null ) - { - throw new IllegalArgumentException ( "Can't send a null message." ); - } - } - - public message ( message msg ) - { - this ( msg.fPartition, msg.fMsg ); - } - - public final String fPartition; - public final String fMsg; - } - - /** - * Send the given message without partition. partition will be placed at HTTP request level. - * @param msg message to sent - * @return the number of pending messages - * @throws IOException exception - */ - int send ( String msg ) throws IOException; - /** - * Send the given message using the given partition. - * @param partition partition - * @param msg message - * @return the number of pending messages - * @throws IOException exception - */ - int send ( String partition, String msg ) throws IOException; - - /** - * Send the given message using its partition. - * @param msg mesg - * @return the number of pending messages - * @throws IOException exp - */ - int send ( message msg ) throws IOException; - - /** - * Send the given messages using their partitions. - * @param msgs msg - * @return the number of pending messages - * @throws IOException exp - */ - int send ( Collection msgs ) throws IOException; - - /** - * Close this publisher. It's an error to call send() after close() - */ - void close (); -} diff --git a/src/main/java/com/att/nsa/mr/client/MRTopicManager.java b/src/main/java/com/att/nsa/mr/client/MRTopicManager.java deleted file mode 100644 index 13524bd..0000000 --- a/src/main/java/com/att/nsa/mr/client/MRTopicManager.java +++ /dev/null @@ -1,183 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client; - -import java.io.IOException; -import java.util.Set; - -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; - - -/** - * A client for working with topic metadata. - * @author author - */ -public interface MRTopicManager extends MRClient -{ - /** - * Get the topics available in the cluster - * @return a set of topic names - * @throws IOException - */ - Set getTopics () throws IOException; - - /** - * Information about a topic. - */ - public interface TopicInfo - { - /** - * Get the owner of the topic - * @return the owner, or null if no entry - */ - String getOwner (); - - /** - * Get the description for this topic - * @return the description, or null if no entry - */ - String getDescription (); - - /** - * Get the set of allowed producers (as API keys) on this topic - * @return the set of allowed producers, null of no ACL exists/enabled - */ - Set getAllowedProducers (); - - /** - * Get the set of allowed consumers (as API keys) on this topic - * @return the set of allowed consumers, null of no ACL exists/enabled - */ - Set getAllowedConsumers (); - } - - /** - * Get information about a topic. - * @param topic - * @return topic information - * @throws IOException - * @throws HttpObjectNotFoundException - */ - TopicInfo getTopicMetadata ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Create a new topic. - * @param topicName - * @param topicDescription - * @param partitionCount - * @param replicationCount - * @throws HttpException - * @throws IOException - */ - void createTopic ( String topicName, String topicDescription, int partitionCount, int replicationCount ) throws HttpException, IOException; - - /** - * Delete the topic. This call must be authenticated and the API key listed as owner on the topic. - * NOTE: The MR (UEB) API server does not support topic deletion at this time (mid 2015) - * @param topic - * @throws HttpException - * @throws IOException - * @deprecated If/when the Kafka system supports topic delete, or the implementation changes, this will be restored. - */ - @Deprecated - void deleteTopic ( String topic ) throws HttpException, IOException; - - /** - * Can any client produce events into this topic without authentication? - * @param topic - * @return true if the topic is open for producing - * @throws IOException - * @throws HttpObjectNotFoundException - */ - boolean isOpenForProducing ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Get the set of allowed producers. If the topic is open, the result is null. - * @param topic - * @return a set of allowed producers or null - * @throws IOException - * @throws HttpObjectNotFoundException - */ - Set getAllowedProducers ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Allow the given API key to produce messages on the given topic. The caller must - * own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws HttpObjectNotFoundException - * @throws IOException - */ - void allowProducer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException; - - /** - * Revoke the given API key's authorization to produce messages on the given topic. - * The caller must own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws IOException - */ - void revokeProducer ( String topic, String apiKey ) throws HttpException, IOException; - - /** - * Can any client consume events from this topic without authentication? - * @param topic - * @return true if the topic is open for consuming - * @throws IOException - * @throws HttpObjectNotFoundException - */ - boolean isOpenForConsuming ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Get the set of allowed consumers. If the topic is open, the result is null. - * @param topic - * @return a set of allowed consumers or null - * @throws IOException - * @throws HttpObjectNotFoundException - */ - Set getAllowedConsumers ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Allow the given API key to consume messages on the given topic. The caller must - * own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws HttpObjectNotFoundException - * @throws IOException - */ - void allowConsumer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException; - - /** - * Revoke the given API key's authorization to consume messages on the given topic. - * The caller must own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws IOException - */ - void revokeConsumer ( String topic, String apiKey ) throws HttpException, IOException; -} - diff --git a/src/main/java/com/att/nsa/mr/client/impl/Clock.java b/src/main/java/com/att/nsa/mr/client/impl/Clock.java deleted file mode 100644 index ace791e..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/Clock.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -public class Clock -{ - public synchronized static Clock getIt () - { - if ( sfClock == null ) - { - sfClock = new Clock (); - } - return sfClock; - } - - /** - * Get the system's current time in milliseconds. - * @return the current time - */ - public static long now () - { - return getIt().nowImpl (); - } - - /** - * Get current time in milliseconds - * @return current time in ms - */ - protected long nowImpl () - { - return System.currentTimeMillis (); - } - - protected Clock () - { - } - - private static Clock sfClock = null; - - protected synchronized static void register ( Clock testClock ) - { - sfClock = testClock; - } -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/DmaapClientUtil.java b/src/main/java/com/att/nsa/mr/client/impl/DmaapClientUtil.java deleted file mode 100644 index a3a2ce1..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/DmaapClientUtil.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; - -public class DmaapClientUtil { - - private static final String MR_AUTH_CONSTANT = "X-CambriaAuth"; - private static final String MR_DATE_CONSTANT = "X-CambriaDate"; - - public static WebTarget getTarget(final String path, final String username, final String password) { - - Client client = ClientBuilder.newClient(); - HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password); - client.register(feature); - - return client.target(path); - } - - public static WebTarget getTarget(final String path) { - - Client client = ClientBuilder.newClient(); - return client.target(path); - } - - public static Response getResponsewtCambriaAuth(WebTarget target, String username, String password) { - return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get(); - - } - - public static Response postResponsewtCambriaAuth(WebTarget target, String username, String password,byte[] data, String contentType) { - return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).post(Entity.entity(data, contentType)); - - } - - public static Response getResponsewtBasicAuth(WebTarget target, String authHeader) { - - return target.request().header("Authorization", "Basic " + authHeader).get(); - - } - - public static Response postResponsewtBasicAuth(WebTarget target, String authHeader,byte[] data,String contentType) { - - return target.request().header("Authorization", "Basic " + authHeader).post(Entity.entity(data, contentType)); - - } - - public static Response getResponsewtNoAuth(WebTarget target) { - - return target.request().get(); - - } - - public static Response postResponsewtNoAuth(WebTarget target, byte[] data, String contentType) { - return target.request().post(Entity.entity(data, contentType)); - - } - -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/MRBaseClient.java b/src/main/java/com/att/nsa/mr/client/impl/MRBaseClient.java deleted file mode 100644 index 76bf5ce..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/MRBaseClient.java +++ /dev/null @@ -1,395 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.net.MalformedURLException; -import java.util.Collection; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.TimeUnit; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -import org.apache.http.HttpException; -import org.glassfish.jersey.internal.util.Base64; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.http.CacheUse; -import com.att.nsa.apiClient.http.HttpClient; -import com.att.nsa.mr.client.MRClient; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; - -public class MRBaseClient extends HttpClient implements MRClient { - - - protected MRBaseClient(Collection hosts) throws MalformedURLException { - super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort); - - fLog = LoggerFactory.getLogger(this.getClass().getName()); - } - - protected MRBaseClient(Collection hosts, int stdSvcPort) throws MalformedURLException { - super(ConnectionType.HTTP, hosts, stdSvcPort); - - fLog = LoggerFactory.getLogger(this.getClass().getName()); - } - - protected MRBaseClient(Collection hosts, String clientSignature) throws MalformedURLException { - super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort, clientSignature, CacheUse.NONE, 1, 1L, - TimeUnit.MILLISECONDS, 32, 32, 600000); - - fLog = LoggerFactory.getLogger(this.getClass().getName()); - } - - @Override - public void close() { - } - - protected Set jsonArrayToSet(JSONArray a) { - if (a == null) - return null; - - final TreeSet set = new TreeSet(); - for (int i = 0; i < a.length(); i++) { - set.add(a.getString(i)); - } - return set; - } - - public void logTo(Logger log) { - fLog = log; - replaceLogger(log); - } - - protected Logger getLog() { - return fLog; - } - - private Logger fLog; - - public JSONObject post(final String path, final byte[] data, final String contentType, final String username, - final String password, final String protocalFlag) throws HttpException, JSONException { - if ((null != username && null != password)) { - WebTarget target=null; - Response response=null; - target = DmaapClientUtil.getTarget(path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - - response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding,data, contentType); - - return getResponseDataInJson(response); - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); - } - } - - public JSONObject postNoAuth(final String path, final byte[] data, String contentType) - throws HttpException, JSONException { - WebTarget target = null; - Response response = null; - if (contentType == null) { - contentType = "text/pain"; - } - target = DmaapClientUtil.getTarget(path); - - response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); - - return getResponseDataInJson(response); - } - - public String postWithResponse(final String path, final byte[] data, final String contentType, - final String username, final String password, final String protocolFlag) - throws HttpException, JSONException { - String responseData = null; - if ((null != username && null != password)) { - WebTarget target=null; - Response response=null; - target = DmaapClientUtil.getTarget(path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - - response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding,data, contentType); - - responseData = (String)response.readEntity(String.class); - return responseData; - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); - } - } - - public String postNoAuthWithResponse(final String path, final byte[] data, String contentType) - throws HttpException, JSONException { - - String responseData = null; - WebTarget target = null; - Response response = null; - if (contentType == null) { - contentType = "text/pain"; - } - target = DmaapClientUtil.getTarget(path); - - response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); - responseData = (String) response.readEntity(String.class); - return responseData; - } - - public JSONObject postAuth(final String path, final byte[] data, final String contentType, final String authKey, - final String authDate, final String username, final String password, final String protocolFlag) - throws HttpException, JSONException { - if ((null != username && null != password)) { - WebTarget target=null; - Response response=null; - target = DmaapClientUtil.getTarget(path, username, password); - response =DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType); - return getResponseDataInJson(response); - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); - } - } - - public String postAuthwithResponse(final String path, final byte[] data, final String contentType, - final String authKey, final String authDate, final String username, final String password, - final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - if ((null != username && null != password)) { - WebTarget target=null; - Response response=null; - target = DmaapClientUtil.getTarget(path, username, password); - response = DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType); - responseData = (String)response.readEntity(String.class); - return responseData; - - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); - } - } - - public JSONObject get(final String path, final String username, final String password, final String protocolFlag) - throws HttpException, JSONException { - if (null != username && null != password) { - - WebTarget target=null; - Response response=null; - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - target = DmaapClientUtil.getTarget(path); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); - } else { - target = DmaapClientUtil.getTarget(path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - - response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); - - } - return getResponseDataInJson(response); - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); - } - } - - public String getResponse(final String path, final String username, final String password, - final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - if (null != username && null != password) { - WebTarget target=null; - Response response=null; - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - target = DmaapClientUtil.getTarget(path); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); - } else { - target = DmaapClientUtil.getTarget(path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); - } - MRClientFactory.HTTPHeadersMap = response.getHeaders(); - - String transactionid = response.getHeaderString("transactionid"); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info("TransactionId : " + transactionid); - } - - responseData = (String)response.readEntity(String.class); - return responseData; - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); - } - } - - public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username, - final String password, final String protocolFlag) throws HttpException, JSONException { - if (null != username && null != password) { - WebTarget target=null; - Response response=null; - target = DmaapClientUtil.getTarget(path, username, password); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); - - return getResponseDataInJson(response); - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); - } - } - - public JSONObject getNoAuth(final String path) throws HttpException, JSONException { - - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(path); - response = DmaapClientUtil.getResponsewtNoAuth(target); - - return getResponseDataInJson(response); - } - - public String getAuthResponse(final String path, final String authKey, final String authDate, final String username, - final String password, final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - if (null != username && null != password) { - WebTarget target=null; - Response response=null; - target = DmaapClientUtil.getTarget(path, username, password); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); - - MRClientFactory.HTTPHeadersMap = response.getHeaders(); - - String transactionid = response.getHeaderString("transactionid"); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info("TransactionId : " + transactionid); - } - - responseData = (String)response.readEntity(String.class); - return responseData; - } else { - throw new HttpException( - "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); - } - } - - public String getNoAuthResponse(String path, final String username, final String password, - final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - WebTarget target=null; - Response response=null; - target = DmaapClientUtil.getTarget(path, username, password); - response = DmaapClientUtil.getResponsewtNoAuth(target); - - MRClientFactory.HTTPHeadersMap = response.getHeaders(); - - String transactionid = response.getHeaderString("transactionid"); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info("TransactionId : " + transactionid); - } - - responseData = (String)response.readEntity(String.class); - return responseData; - - } - - - private JSONObject getResponseDataInJson(Response response) throws JSONException { - try { - MRClientFactory.HTTPHeadersMap = response.getHeaders(); - - - // MultivaluedMap headersMap = - // for(String key : headersMap.keySet()) { - String transactionid = response.getHeaderString("transactionid"); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info("TransactionId : " + transactionid); - } - - - if (response.getStatus() == 403) { - JSONObject jsonObject = null; - jsonObject = new JSONObject(); - JSONArray jsonArray = new JSONArray(); - jsonArray.put(response.getEntity()); - jsonObject.put("result", jsonArray); - jsonObject.put("status", response.getStatus()); - return jsonObject; - } - String responseData = (String)response.readEntity(String.class); - - JSONTokener jsonTokener = new JSONTokener(responseData); - JSONObject jsonObject = null; - final char firstChar = jsonTokener.next(); - jsonTokener.back(); - if ('[' == firstChar) { - JSONArray jsonArray = new JSONArray(jsonTokener); - jsonObject = new JSONObject(); - jsonObject.put("result", jsonArray); - jsonObject.put("status", response.getStatus()); - } else { - jsonObject = new JSONObject(jsonTokener); - jsonObject.put("status", response.getStatus()); - } - - return jsonObject; - } catch (JSONException excp) { - fLog.error("DMAAP - Error reading response data.", excp); - return null; - } - - } - - public String getHTTPErrorResponseMessage(String responseString) { - - String response = null; - int beginIndex = 0; - int endIndex = 0; - if (responseString.contains("")) { - - beginIndex = responseString.indexOf("body>") + 5; - endIndex = responseString.indexOf("")) { - beginIndex = responseString.indexOf("title>") + 6; - endIndex = responseString.indexOf(" baseUrls, String topic, int maxBatchSize, long maxAgeMs, boolean compress ) - { - if ( maxAgeMs < kMinMaxAgeMs ) - { - fLog.warn ( "Max age in ms is less than the minimum. Overriding to " + kMinMaxAgeMs ); - maxAgeMs = kMinMaxAgeMs; - } - - try { - fSender = new Sender ( baseUrls, topic, maxBatchSize, maxAgeMs, compress ); - } catch (MalformedURLException e) { - throw new IllegalArgumentException (e); - } - - // FIXME: this strategy needs an overhaul -- why not just run a thread that knows how to wait for - // the oldest msg to hit max age? (locking is complicated, but should be do-able) - fExec = new ScheduledThreadPoolExecutor ( 1 ); - fExec.scheduleAtFixedRate ( fSender, 100, 50, TimeUnit.MILLISECONDS ); - } - - @Override - public void setApiCredentials ( String apiKey, String apiSecret ) - { - fSender.setApiCredentials ( apiKey, apiSecret ); - } - - @Override - public void clearApiCredentials () - { - fSender.clearApiCredentials (); - } - - /** - * Send the given message with the given partition - * @param partition - * @param msg - * @throws IOException - */ - @Override - public int send ( String partition, String msg ) throws IOException - { - return send ( new message ( partition, msg ) ); - } - @Override - public int send ( String msg ) throws IOException - { - return send ( new message ( "",msg ) ); - } - /** - * Send the given message - * @param userMsg a message - * @throws IOException - */ - @Override - public int send ( message userMsg ) throws IOException - { - final LinkedList list = new LinkedList (); - list.add ( userMsg ); - return send ( list ); - } - - /** - * Send the given set of messages - * @param msgs the set of messages, sent in order of iteration - * @return the number of messages in the pending queue (this could actually be less than the size of the given collection, depending on thread timing) - * @throws IOException - */ - @Override - public int send ( Collection msgs ) throws IOException - { - if ( msgs.isEmpty() ) - { - fSender.queue ( msgs ); - } - return fSender.size (); - } - - @Override - public int getPendingMessageCount () - { - return fSender.size (); - } - - /** - * Send any pending messages and close this publisher. - * @throws IOException - * @throws InterruptedException - */ - @Override - public void close () - { - try - { - final List remains = close ( Long.MAX_VALUE, TimeUnit.MILLISECONDS ); - if ( remains.isEmpty() ) - { - fLog.warn ( "Closing publisher with " + remains.size() + " messages unsent. " - + "(Consider using the alternate close method to capture unsent messages in this case.)" ); - } - } - catch ( InterruptedException e ) - { - fLog.warn ( "Possible message loss. " + e.getMessage(), e ); - Thread.currentThread().interrupt(); - } - catch ( IOException e ) - { - fLog.warn ( "Possible message loss. " + e.getMessage(), e ); - } - } - - public List close ( long time, TimeUnit unit ) throws InterruptedException, IOException - { - fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy ( false ); - fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy ( false ); - fExec.shutdown (); - - final long waitInMs = TimeUnit.MILLISECONDS.convert ( time, unit ); - final long timeoutAtMs = System.currentTimeMillis () + waitInMs; - while ( System.currentTimeMillis () < timeoutAtMs && getPendingMessageCount() > 0 ) - { - fSender.checkSend ( true ); - Thread.sleep ( 250 ); - } - - final LinkedList result = new LinkedList (); - fSender.drainTo ( result ); - return result; - } - - private final ScheduledThreadPoolExecutor fExec; - private final Sender fSender; - - private static class TimestampedMessage extends message - { - public TimestampedMessage ( message m ) - { - super ( m ); - timestamp = System.currentTimeMillis (); - } - public final long timestamp; - } - - private Logger fLog = LoggerFactory.getLogger ( MRBatchPublisher.class ); - - private class Sender extends MRBaseClient implements Runnable - { - public Sender ( Collection baseUrls, String topic, int maxBatch, long maxAgeMs, boolean compress ) throws MalformedURLException - { - super ( baseUrls ); - - fNextBatch = new LinkedList (); - fSendingBatch = null; - fTopic = topic; - fMaxBatchSize = maxBatch; - fMaxAgeMs = maxAgeMs; - fCompress = compress; - fLock = new ReentrantReadWriteLock (); - fWriteLock = fLock.writeLock (); - fReadLock = fLock.readLock (); - fDontSendUntilMs = 0; - } - - public void drainTo ( LinkedList list ) - { - fWriteLock.lock (); - try - { - if ( fSendingBatch != null ) - { - list.addAll ( fSendingBatch ); - } - list.addAll ( fNextBatch ); - - fSendingBatch = null; - fNextBatch.clear (); - } - finally - { - fWriteLock.unlock (); - } - } - - /** - * Called periodically by the background executor. - */ - @Override - public void run () - { - try - { - checkSend ( false ); - } - catch ( IOException e ) - { - fLog.warn ( "MR background send: " + e.getMessage () ); - fLog.error( "IOException " + e ); - } - } - - public int size () - { - fReadLock.lock (); - try - { - return fNextBatch.size () + ( fSendingBatch == null ? 0 : fSendingBatch.size () ); - } - finally - { - fReadLock.unlock (); - } - } - - /** - * Called to queue a message. - * @param m - * @throws IOException - */ - public void queue ( Collection msgs ) throws IOException - { - fWriteLock.lock (); - try - { - for ( message userMsg : msgs ) - { - if ( userMsg != null ) - { - fNextBatch.add ( new TimestampedMessage ( userMsg ) ); - } - else - { - fLog.warn ( "MRBatchPublisher::Sender::queue received a null message." ); - } - } - } - finally - { - fWriteLock.unlock(); - } - checkSend ( false ); - } - - /** - * Send a batch if the queue is long enough, or the first pending message is old enough. - * @param force - * @throws IOException - */ - public void checkSend ( boolean force ) throws IOException - { - // hold a read lock just long enough to evaluate whether a batch - // should be sent - boolean shouldSend = false; - fReadLock.lock (); - try - { - if ( fNextBatch.isEmpty() ) - { - final long nowMs = System.currentTimeMillis (); - shouldSend = ( force || fNextBatch.size() >= fMaxBatchSize ); - if ( !shouldSend ) - { - final long sendAtMs = fNextBatch.getFirst ().timestamp + fMaxAgeMs; - shouldSend = sendAtMs <= nowMs; - } - - // however, unless forced, wait after an error - shouldSend = force || ( shouldSend && nowMs >= fDontSendUntilMs ); - } - // else: even in 'force', there's nothing to send, so shouldSend=false is fine - } - finally - { - fReadLock.unlock (); - } - - // if a send is required, acquire a write lock, swap out the next batch, - // swap in a fresh batch, and release the lock for the caller to start - // filling a batch again. After releasing the lock, send the current - // batch. (There could be more messages added between read unlock and - // write lock, but that's fine.) - if ( shouldSend ) - { - fSendingBatch = null; - - fWriteLock.lock (); - try - { - fSendingBatch = fNextBatch; - fNextBatch = new LinkedList (); - } - finally - { - fWriteLock.unlock (); - } - - if ( !doSend ( fSendingBatch, this, fTopic, fCompress, fLog ) ) - { - fLog.warn ( "Send failed, rebuilding send queue." ); - - // note the time for back-off - fDontSendUntilMs = sfWaitAfterError + System.currentTimeMillis (); - - // the send failed. reconstruct the pending queue - fWriteLock.lock (); - try - { - final LinkedList nextGroup = fNextBatch; - fNextBatch = fSendingBatch; - fNextBatch.addAll ( nextGroup ); - fSendingBatch = null; - fLog.info ( "Send queue rebuilt; " + fNextBatch.size () + " messages to send." ); - } - finally - { - fWriteLock.unlock (); - } - } - else - { - fWriteLock.lock (); - try - { - fSendingBatch = null; - } - finally - { - fWriteLock.unlock (); - } - } - } - } - - private LinkedList fNextBatch; - private LinkedList fSendingBatch; - private final String fTopic; - private final int fMaxBatchSize; - private final long fMaxAgeMs; - private final boolean fCompress; - private final ReentrantReadWriteLock fLock; - private final WriteLock fWriteLock; - private final ReadLock fReadLock; - private long fDontSendUntilMs; - private static final long sfWaitAfterError = 1000; - } - - // this is static so that it's clearly not using any mutable member data outside of a lock - private static boolean doSend ( LinkedList toSend, HttpClient client, String topic, boolean compress, Logger log ) - { - // it's possible for this call to be made with an empty list. in this case, just return. - if ( toSend.isEmpty() ) - { - return true; - } - - final long nowMs = System.currentTimeMillis (); - final String url = MRConstants.makeUrl ( topic ); - - log.info ( "sending " + toSend.size() + " msgs to " + url + ". Oldest: " + ( nowMs - toSend.getFirst().timestamp ) + " ms" ); - - final ByteArrayOutputStream baseStream = new ByteArrayOutputStream (); - try - { - OutputStream os = baseStream; - if ( compress ) - { - os = new GZIPOutputStream ( baseStream ); - } - for ( TimestampedMessage m : toSend ) - { - os.write ( ( "" + m.fPartition.length () ).getBytes() ); - os.write ( '.' ); - os.write ( ( "" + m.fMsg.length () ).getBytes() ); - os.write ( '.' ); - os.write ( m.fPartition.getBytes() ); - os.write ( m.fMsg.getBytes() ); - os.write ( '\n' ); - } - os.close (); - } - catch ( IOException e ) - { - log.warn ( "Problem writing stream to post: " + e.getMessage (),e ); - return false; - } - - boolean result = false; - final long startMs = System.currentTimeMillis (); - try - { - client.post ( url, compress ? - MRFormat.CAMBRIA_ZIP.toString () : - MRFormat.CAMBRIA.toString (), - baseStream.toByteArray(), false ); - result = true; - } - catch ( HttpException e ) - { - log.warn ( "Problem posting to MR: " + e.getMessage(),e ); - } - catch ( IOException e ) - { - log.warn ( "Problem posting to MR: " + e.getMessage(),e ); - } - - log.info ( "MR response (" + (System.currentTimeMillis ()-startMs) + " ms): OK" ); - return result; - } - - @Override - public void logTo ( Logger log ) - { - fLog = log; - } - - @Override - public MRPublisherResponse sendBatchWithResponse() { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/MRClientVersionInfo.java b/src/main/java/com/att/nsa/mr/client/impl/MRClientVersionInfo.java deleted file mode 100644 index bb6299d..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/MRClientVersionInfo.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MRClientVersionInfo -{ - private static final Logger logger = LoggerFactory.getLogger(MRClientVersionInfo.class); - public static String getVersion () - { - return version; - } - - private static final Properties props = new Properties(); - private static final String version; - static - { - String use = null; - try - { - final InputStream is = MRClientVersionInfo.class.getResourceAsStream ( "/MRClientVersion.properties" ); - if ( is != null ) - { - props.load ( is ); - use = props.getProperty ( "MRClientVersion", null ); - } - } - catch ( IOException e ) - { - logger.error("exception: ", e); - } - version = use; - } -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/MRConstants.java b/src/main/java/com/att/nsa/mr/client/impl/MRConstants.java deleted file mode 100644 index cb0fc31..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/MRConstants.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.http.HttpHost; - -class MRConstants -{ - private static final String PROTOCOL = "http"; - public static final String context = "/"; - public static final String kBasePath = "events/"; - public static final int kStdMRServicePort = 8080; - - public static String escape ( String s ) - { - try - { - return URLEncoder.encode ( s, "UTF-8"); - } - catch ( UnsupportedEncodingException e ) - { - throw new IllegalArgumentException(e); - } - } - - public static String makeUrl ( String rawTopic ) - { - final String cleanTopic = escape ( rawTopic ); - - final StringBuffer url = new StringBuffer(). - append ( MRConstants.context ). - append ( MRConstants.kBasePath ). - append ( cleanTopic ); - return url.toString (); - } - - public static String makeUrl ( final String host, final String rawTopic ) - { - final String cleanTopic = escape ( rawTopic ); - - final StringBuffer url = new StringBuffer(); - - if (!host.startsWith("http") || !host.startsWith("https") ) { - url.append( PROTOCOL + "://" ); - } - url.append(host); - url.append ( MRConstants.context ); - url.append ( MRConstants.kBasePath ); - url.append ( cleanTopic ); - return url.toString (); - } - - public static String makeUrl ( final String host, final String rawTopic, final String transferprotocol,final String parttion ) - { - final String cleanTopic = escape ( rawTopic ); - - final StringBuffer url = new StringBuffer(); - - if (transferprotocol !=null && !transferprotocol.equals("")) { - url.append( transferprotocol + "://" ); - }else{ - url.append( PROTOCOL + "://" ); - } - url.append(host); - url.append ( MRConstants.context ); - url.append ( MRConstants.kBasePath ); - url.append ( cleanTopic ); - if(parttion!=null && !parttion.equalsIgnoreCase("")) - url.append("?partitionKey=").append(parttion); - return url.toString (); - } - public static String makeConsumerUrl ( String topic, String rawConsumerGroup, String rawConsumerId ) - { - final String cleanConsumerGroup = escape ( rawConsumerGroup ); - final String cleanConsumerId = escape ( rawConsumerId ); - return MRConstants.context + MRConstants.kBasePath + topic + "/" + cleanConsumerGroup + "/" + cleanConsumerId; - } - - /** - * Create a list of HttpHosts from an input list of strings. Input strings have - * host[:port] as format. If the port section is not provided, the default port is used. - * - * @param hosts - * @return a list of hosts - */ - public static List createHostsList(Collection hosts) - { - final ArrayList convertedHosts = new ArrayList (); - for ( String host : hosts ) - { - if ( host.length () == 0 ) continue; - convertedHosts.add ( hostForString ( host ) ); - } - return convertedHosts; - } - - /** - * Return an HttpHost from an input string. Input string has - * host[:port] as format. If the port section is not provided, the default port is used. - * - * @param hosts - * @return a list of hosts - */ - public static HttpHost hostForString ( String host ) - { - if ( host.length() < 1 ) throw new IllegalArgumentException ( "An empty host entry is invalid." ); - - String hostPart = host; - int port = kStdMRServicePort; - - final int colon = host.indexOf ( ':' ); - if ( colon == 0 ) throw new IllegalArgumentException ( "Host entry '" + host + "' is invalid." ); - if ( colon > 0 ) - { - hostPart = host.substring ( 0, colon ).trim(); - - final String portPart = host.substring ( colon + 1 ).trim(); - if ( portPart.length () > 0 ) - { - try - { - port = Integer.parseInt ( portPart ); - } - catch ( NumberFormatException x ) - { - throw new IllegalArgumentException ( "Host entry '" + host + "' is invalid.", x ); - } - } - // else: use default port on "foo:" - } - - return new HttpHost ( hostPart, port ); - } - - public static String makeConsumerUrl(String host, String fTopic, String fGroup, String fId,final String transferprotocol) { - final String cleanConsumerGroup = escape ( fGroup ); - final String cleanConsumerId = escape ( fId ); - - StringBuffer url = new StringBuffer(); - - if (transferprotocol !=null && !transferprotocol.equals("")) { - url.append( transferprotocol + "://" ); - }else{ - url.append( PROTOCOL + "://" ); - } - - url.append(host); - url.append(context); - url.append(kBasePath); - url.append(fTopic + "/" + cleanConsumerGroup + "/" + cleanConsumerId); - - return url.toString(); - } -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/MRConsumerImpl.java b/src/main/java/com/att/nsa/mr/client/impl/MRConsumerImpl.java deleted file mode 100644 index bc156ea..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/MRConsumerImpl.java +++ /dev/null @@ -1,675 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import com.att.aft.dme2.api.DME2Client; -import com.att.aft.dme2.api.DME2Exception; -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.response.MRConsumerResponse; -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import org.apache.http.HttpException; -import org.apache.http.HttpStatus; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MRConsumerImpl extends MRBaseClient implements MRConsumer { - - private Logger log = LoggerFactory.getLogger(this.getClass().getName()); - - public static final String routerFilePath = null; - - public String protocolFlag = ProtocolTypeConstants.DME2.getValue(); - public String consumerFilePath; - - private static final String SUCCESS_MESSAGE = "Success"; - private static final long DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS = 10000L; - private static final long DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS = 10000L; - - private final String fTopic; - private final String fGroup; - private final String fId; - private final int fTimeoutMs; - private final int fLimit; - private String fFilter; - private String username; - private String password; - private String host; - private HostSelector fHostSelector = null; - private String url; - private DME2Client sender; - private String authKey; - private String authDate; - private Properties props; - private HashMap DMETimeOuts; - private long dme2ReplyHandlerTimeoutMs; - private long longPollingMs; - - public MRConsumerImpl(Collection hostPart, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit, String filter, String apiKey_username, - String apiSecret_password) throws MalformedURLException { - this(hostPart, topic, consumerGroup, consumerId, timeoutMs, limit, filter, apiKey_username, apiSecret_password, - false); - } - - public MRConsumerImpl(Collection hostPart, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret, - boolean allowSelfSignedCerts) throws MalformedURLException { - super(hostPart, topic + "::" + consumerGroup + "::" + consumerId); - - fTopic = topic; - fGroup = consumerGroup; - fId = consumerId; - fTimeoutMs = timeoutMs; - fLimit = limit; - fFilter = filter; - - fHostSelector = new HostSelector(hostPart); - } - - @Override - public Iterable fetch() throws IOException, Exception { - // fetch with the timeout and limit set in constructor - return fetch(fTimeoutMs, fLimit); - } - - @Override - public Iterable fetch(int timeoutMs, int limit) throws Exception { - final LinkedList msgs = new LinkedList<>(); - - try { - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { - dmeConfigure(timeoutMs, limit); - try { - String reply = sender.sendAndWait(timeoutMs + 10000L); - final JSONObject o = getResponseDataInJson(reply); - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - } catch (JSONException e) { - // unexpected response - reportProblemWithResponse(); - log.error("exception: ", e); - } catch (HttpException e) { - throw new IOException(e); - } - } - - if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { - final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); - - try { - final JSONObject o = get(urlPath, username, password, protocolFlag); - - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - } catch (JSONException e) { - // unexpected response - reportProblemWithResponse(); - log.error("exception: ", e); - } catch (HttpException e) { - throw new IOException(e); - } - } - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - final String urlPath = createUrlPath( - MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty("Protocol")), - timeoutMs, limit); - - try { - final JSONObject o = getAuth(urlPath, authKey, authDate, username, password, protocolFlag); - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - } catch (JSONException e) { - // unexpected response - reportProblemWithResponse(); - log.error("exception: ", e); - } catch (HttpException e) { - throw new IOException(e); - } - } - - if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { - final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); - - try { - final JSONObject o = getNoAuth(urlPath); - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - } catch (JSONException e) { - // unexpected response - reportProblemWithResponse(); - log.error("exception: ", e); - } catch (HttpException e) { - throw new IOException(e); - } - } - } catch (JSONException e) { - // unexpected response - reportProblemWithResponse(); - log.error("exception: ", e); - } catch (HttpException e) { - throw new IOException(e); - } catch (Exception e) { - throw e; - } - - return msgs; - } - - @Override - public MRConsumerResponse fetchWithReturnConsumerResponse() { - // fetch with the timeout and limit set in constructor - return fetchWithReturnConsumerResponse(fTimeoutMs, fLimit); - } - - @Override - public MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, int limit) { - final LinkedList msgs = new LinkedList(); - MRConsumerResponse mrConsumerResponse = new MRConsumerResponse(); - try { - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { - dmeConfigure(timeoutMs, limit); - - long timeout = (dme2ReplyHandlerTimeoutMs > 0 && longPollingMs == timeoutMs) ? dme2ReplyHandlerTimeoutMs - : (timeoutMs + DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS); - String reply = sender.sendAndWait(timeout); - - final JSONObject o = getResponseDataInJsonWithResponseReturned(reply); - - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - createMRConsumerResponse(reply, mrConsumerResponse); - } - - if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { - final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); - - String response = getResponse(urlPath, username, password, protocolFlag); - final JSONObject o = getResponseDataInJsonWithResponseReturned(response); - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - createMRConsumerResponse(response, mrConsumerResponse); - } - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - final String urlPath = createUrlPath( - MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty("Protocol")), - timeoutMs, limit); - - String response = getAuthResponse(urlPath, authKey, authDate, username, password, protocolFlag); - final JSONObject o = getResponseDataInJsonWithResponseReturned(response); - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - createMRConsumerResponse(response, mrConsumerResponse); - } - - if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { - final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); - - String response = getNoAuthResponse(urlPath, username, password, protocolFlag); - final JSONObject o = getResponseDataInJsonWithResponseReturned(response); - if (o != null) { - final JSONArray a = o.getJSONArray("result"); - - if (a != null) { - for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) - msgs.add(a.getString(i)); - else - msgs.add(a.getJSONObject(i).toString()); - } - } - } - createMRConsumerResponse(response, mrConsumerResponse); - } - - } catch (JSONException e) { - mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - mrConsumerResponse.setResponseMessage(e.getMessage()); - log.error("json exception: ", e); - } catch (HttpException e) { - mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - mrConsumerResponse.setResponseMessage(e.getMessage()); - log.error("http exception: ", e); - } catch (DME2Exception e) { - mrConsumerResponse.setResponseCode(e.getErrorCode()); - mrConsumerResponse.setResponseMessage(e.getErrorMessage()); - log.error("DME2 exception: ", e); - } catch (Exception e) { - mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - mrConsumerResponse.setResponseMessage(e.getMessage()); - log.error("exception: ", e); - } - mrConsumerResponse.setActualMessages(msgs); - return mrConsumerResponse; - } - - @Override - protected void reportProblemWithResponse() { - log.warn("There was a problem with the server response. Blacklisting for 3 minutes."); - super.reportProblemWithResponse(); - fHostSelector.reportReachabilityProblem(3, TimeUnit.MINUTES); - } - - private void createMRConsumerResponse(String reply, MRConsumerResponse mrConsumerResponse) { - if (reply.startsWith("{")) { - JSONObject jObject = new JSONObject(reply); - String message = jObject.getString("message"); - int status = jObject.getInt("status"); - - mrConsumerResponse.setResponseCode(Integer.toString(status)); - - if (null != message) { - mrConsumerResponse.setResponseMessage(message); - } - } else if (reply.startsWith("<")) { - mrConsumerResponse.setResponseCode(getHTTPErrorResponseCode(reply)); - mrConsumerResponse.setResponseMessage(getHTTPErrorResponseMessage(reply)); - } else { - mrConsumerResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK)); - mrConsumerResponse.setResponseMessage(SUCCESS_MESSAGE); - } - } - - private JSONObject getResponseDataInJson(String response) { - try { - JSONTokener jsonTokener = new JSONTokener(response); - JSONObject jsonObject = null; - final char firstChar = jsonTokener.next(); - jsonTokener.back(); - if ('[' == firstChar) { - JSONArray jsonArray = new JSONArray(jsonTokener); - jsonObject = new JSONObject(); - jsonObject.put("result", jsonArray); - } else { - jsonObject = new JSONObject(jsonTokener); - } - - return jsonObject; - } catch (JSONException excp) { - log.error("DMAAP - Error reading response data.", excp); - return null; - } - } - - private JSONObject getResponseDataInJsonWithResponseReturned(String response) { - JSONTokener jsonTokener = new JSONTokener(response); - JSONObject jsonObject = null; - final char firstChar = jsonTokener.next(); - jsonTokener.back(); - if (null != response && response.length() == 0) { - return null; - } - - if ('[' == firstChar) { - JSONArray jsonArray = new JSONArray(jsonTokener); - jsonObject = new JSONObject(); - jsonObject.put("result", jsonArray); - } else if ('{' == firstChar) { - return null; - } else if ('<' == firstChar) { - return null; - } else { - jsonObject = new JSONObject(jsonTokener); - } - - return jsonObject; - } - - private void dmeConfigure(int timeoutMs, int limit) throws IOException, DME2Exception, URISyntaxException { - this.longPollingMs = timeoutMs; - String latitude = props.getProperty("Latitude"); - String longitude = props.getProperty("Longitude"); - String version = props.getProperty("Version"); - String serviceName = props.getProperty("ServiceName"); - String env = props.getProperty("Environment"); - String partner = props.getProperty("Partner"); - String routeOffer = props.getProperty("routeOffer"); - String subContextPath = props.getProperty("SubContextPath") + fTopic + "/" + fGroup + "/" + fId; - String protocol = props.getProperty("Protocol"); - String methodType = props.getProperty("MethodType"); - String dmeuser = props.getProperty("username"); - String dmepassword = props.getProperty("password"); - String contenttype = props.getProperty("contenttype"); - String handlers = props.getProperty("sessionstickinessrequired"); - - /** - * Changes to DME2Client url to use Partner for auto failover between data centers When Partner value is not - * provided use the routeOffer value for auto failover within a cluster - */ - - String preferredRouteKey = readRoute("preferredRouteKey"); - - if (partner != null && !partner.isEmpty() && preferredRouteKey != null && !preferredRouteKey.isEmpty()) { - url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" + partner - + "&routeoffer=" + preferredRouteKey; - } else if (partner != null && !partner.isEmpty()) { - url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" + partner; - } else if (routeOffer != null && !routeOffer.isEmpty()) { - url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer=" - + routeOffer; - } - - if (timeoutMs != -1) - url = url + "&timeout=" + timeoutMs; - if (limit != -1) - url = url + "&limit=" + limit; - - // Add filter to DME2 Url - if (fFilter != null && fFilter.length() > 0) - url = url + "&filter=" + URLEncoder.encode(fFilter, "UTF-8"); - - DMETimeOuts = new HashMap<>(); - DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); - DMETimeOuts.put("Content-Type", contenttype); - System.setProperty("AFT_LATITUDE", latitude); - System.setProperty("AFT_LONGITUDE", longitude); - System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT")); - - // SSL changes - System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2"); - System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false"); - System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit"); - // SSL changes - - long dme2PerEndPointTimeoutMs; - try { - dme2PerEndPointTimeoutMs = Long.parseLong(props.getProperty("DME2_PER_HANDLER_TIMEOUT_MS")); - // backward compatibility - if (dme2PerEndPointTimeoutMs <= 0) { - dme2PerEndPointTimeoutMs = timeoutMs + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS; - } - } catch (NumberFormatException nfe) { - // backward compatibility - dme2PerEndPointTimeoutMs = timeoutMs + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS; - getLog().debug( - "DME2_PER_HANDLER_TIMEOUT_MS not set and using default " + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS); - } - - try { - dme2ReplyHandlerTimeoutMs = Long.parseLong(props.getProperty("DME2_REPLY_HANDLER_TIMEOUT_MS")); - } catch (NumberFormatException nfe) { - try { - long dme2EpReadTimeoutMs = Long.parseLong(props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); - long dme2EpConnTimeoutMs = Long.parseLong(props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); - dme2ReplyHandlerTimeoutMs = timeoutMs + dme2EpReadTimeoutMs + dme2EpConnTimeoutMs; - getLog().debug( - "DME2_REPLY_HANDLER_TIMEOUT_MS not set and using default from timeoutMs, AFT_DME2_EP_READ_TIMEOUT_MS and AFT_DME2_EP_CONN_TIMEOUT " - + dme2ReplyHandlerTimeoutMs); - } catch (NumberFormatException e) { - // backward compatibility - dme2ReplyHandlerTimeoutMs = timeoutMs + DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS; - getLog().debug("DME2_REPLY_HANDLER_TIMEOUT_MS not set and using default " + dme2ReplyHandlerTimeoutMs); - } - } - // backward compatibility - if (dme2ReplyHandlerTimeoutMs <= 0) { - dme2ReplyHandlerTimeoutMs = timeoutMs + DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS; - } - - sender = new DME2Client(new URI(url), dme2PerEndPointTimeoutMs); - sender.setAllowAllHttpReturnCodes(true); - sender.setMethod(methodType); - sender.setSubContext(subContextPath); - if (dmeuser != null && dmepassword != null) { - sender.setCredentials(dmeuser, dmepassword); - } - sender.setHeaders(DMETimeOuts); - sender.setPayload(""); - if (handlers != null && handlers.equalsIgnoreCase("yes")) { - sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", - props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS")); - sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS")); - sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON")); - } else { - sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler"); - } - } - - protected String createUrlPath(String url, int timeoutMs, int limit) throws IOException { - final StringBuilder contexturl = new StringBuilder(url); - final StringBuilder adds = new StringBuilder(); - - if (timeoutMs > -1) { - adds.append("timeout=").append(timeoutMs); - } - - if (limit > -1) { - if (adds.length() > 0) { - adds.append("&"); - } - adds.append("limit=").append(limit); - } - - if (fFilter != null && fFilter.length() > 0) { - try { - if (adds.length() > 0) { - adds.append("&"); - } - adds.append("filter=").append(URLEncoder.encode(fFilter, "UTF-8")); - } catch (UnsupportedEncodingException e) { - log.error("exception at createUrlPath () : ", e); - } - } - - if (adds.length() > 0) { - contexturl.append("?").append(adds.toString()); - } - - return contexturl.toString(); - } - - private String readRoute(String routeKey) { - try { - MRClientFactory.prop.load(new FileReader(new File(MRClientFactory.routeFilePath))); - } catch (Exception ex) { - log.error("Reply Router Error " + ex); - } - return MRClientFactory.prop.getProperty(routeKey); - } - - public static List stringToList(String str) { - final LinkedList set = new LinkedList<>(); - if (str != null) { - final String[] parts = str.trim().split(","); - for (String part : parts) { - final String trimmed = part.trim(); - if (trimmed.length() > 0) { - set.add(trimmed); - } - } - } - return set; - } - - public static String getRouterFilePath() { - return routerFilePath; - } - - public static void setRouterFilePath(String routerFilePath) { - MRSimplerBatchPublisher.routerFilePath = routerFilePath; - } - - public String getConsumerFilePath() { - return consumerFilePath; - } - - public void setConsumerFilePath(String consumerFilePath) { - this.consumerFilePath = consumerFilePath; - } - - public String getProtocolFlag() { - return protocolFlag; - } - - public void setProtocolFlag(String protocolFlag) { - this.protocolFlag = protocolFlag; - } - - public Properties getProps() { - return props; - } - - public void setProps(Properties props) { - this.props = props; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public String getAuthKey() { - return authKey; - } - - public void setAuthKey(String authKey) { - this.authKey = authKey; - } - - public String getAuthDate() { - return authDate; - } - - public void setAuthDate(String authDate) { - this.authDate = authDate; - } - - public String getfFilter() { - return fFilter; - } - - public void setfFilter(String fFilter) { - this.fFilter = fFilter; - } -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/MRFormat.java b/src/main/java/com/att/nsa/mr/client/impl/MRFormat.java deleted file mode 100644 index 1028adf..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/MRFormat.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -enum MRFormat -{ - /** - * Messages are sent using MR's message format. - */ - CAMBRIA - { - @Override - public String toString() { return "application/cambria"; } - }, - - /** - * Messages are sent using MR's message format with compression. - */ - CAMBRIA_ZIP - { - @Override - public String toString() { return "application/cambria-zip"; } - }, - - /** - * messages are sent as simple JSON objects. - */ - JSON - { - @Override - public String toString() { return "application/json"; } - } -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/MRMetaClient.java b/src/main/java/com/att/nsa/mr/client/impl/MRMetaClient.java deleted file mode 100644 index 609540b..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/MRMetaClient.java +++ /dev/null @@ -1,266 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Collection; -import java.util.Set; -import java.util.TreeSet; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.mr.client.MRIdentityManager; -import com.att.nsa.mr.client.MRTopicManager; - -public class MRMetaClient extends MRBaseClient implements MRTopicManager, MRIdentityManager -{ - private static final Logger logger = LoggerFactory.getLogger(MRMetaClient.class); - public MRMetaClient ( Collection baseUrls ) throws MalformedURLException - { - super ( baseUrls ); - } - - @Override - public Set getTopics () throws IOException - { - final TreeSet set = new TreeSet (); - try - { - final JSONObject topicSet = get ( "/topics" ); - final JSONArray a = topicSet.getJSONArray ( "topics" ); - for ( int i=0; i getAllowedProducers () - { - final JSONObject acl = topicData.optJSONObject ( "writerAcl" ); - if ( acl != null && acl.optBoolean ( "enabled", true ) ) - { - return jsonArrayToSet ( acl.optJSONArray ( "users" ) ); - } - return null; - } - - @Override - public Set getAllowedConsumers () - { - final JSONObject acl = topicData.optJSONObject ( "readerAcl" ); - if ( acl != null && acl.optBoolean ( "enabled", true ) ) - { - return jsonArrayToSet ( acl.optJSONArray ( "users" ) ); - } - return null; - } - }; - } - catch ( JSONException e ) - { - throw new IOException ( e ); - } - catch ( HttpException e ) - { - throw new IOException ( e ); - } - } - - @Override - public void createTopic ( String topicName, String topicDescription, int partitionCount, int replicationCount ) throws HttpException, IOException - { - final JSONObject o = new JSONObject (); - o.put ( "topicName", topicName ); - o.put ( "topicDescription", topicDescription ); - o.put ( "partitionCount", partitionCount ); - o.put ( "replicationCount", replicationCount ); - post ( "/topics/create", o, false ); - } - - @Override - public void deleteTopic ( String topic ) throws HttpException, IOException - { - delete ( "/topics/" + MRConstants.escape ( topic ) ); - } - - @Override - public boolean isOpenForProducing ( String topic ) throws HttpObjectNotFoundException, IOException - { - return null == getAllowedProducers ( topic ); - } - - @Override - public Set getAllowedProducers ( String topic ) throws HttpObjectNotFoundException, IOException - { - return getTopicMetadata ( topic ).getAllowedProducers (); - } - - @Override - public void allowProducer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException - { - put ( "/topics/" + MRConstants.escape ( topic ) + "/producers/" + MRConstants.escape ( apiKey ), new JSONObject() ); - } - - @Override - public void revokeProducer ( String topic, String apiKey ) throws HttpException, IOException - { - delete ( "/topics/" + MRConstants.escape ( topic ) + "/producers/" + MRConstants.escape ( apiKey ) ); - } - - @Override - public boolean isOpenForConsuming ( String topic ) throws HttpObjectNotFoundException, IOException - { - return null == getAllowedConsumers ( topic ); - } - - @Override - public Set getAllowedConsumers ( String topic ) throws HttpObjectNotFoundException, IOException - { - return getTopicMetadata ( topic ).getAllowedConsumers (); - } - - @Override - public void allowConsumer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException - { - put ( "/topics/" + MRConstants.escape ( topic ) + "/consumers/" + MRConstants.escape ( apiKey ), new JSONObject() ); - } - - @Override - public void revokeConsumer ( String topic, String apiKey ) throws HttpException, IOException - { - delete ( "/topics/" + MRConstants.escape ( topic ) + "/consumers/" + MRConstants.escape ( apiKey ) ); - } - - @Override - public ApiCredential createApiKey ( String email, String description ) throws HttpException, MRApiException, IOException - { - try - { - final JSONObject o = new JSONObject (); - o.put ( "email", email ); - o.put ( "description", description ); - final JSONObject reply = post ( "/apiKeys/create", o, true ); - return new ApiCredential ( reply.getString ( "key" ), reply.getString ( "secret" ) ); - } - catch ( JSONException e ) - { - // the response doesn't meet our expectation - throw new MRApiException ( "The API key response is incomplete.", e ); - } - } - - @Override - public ApiKey getApiKey ( String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException - { - final JSONObject keyEntry = get ( "/apiKeys/" + MRConstants.escape ( apiKey ) ); - if ( keyEntry == null ) - { - return null; - } - - return new ApiKey () - { - @Override - public String getEmail () - { - final JSONObject aux = keyEntry.optJSONObject ( "aux" ); - if ( aux != null ) - { - return aux.optString ( "email" ); - } - return null; - } - - @Override - public String getDescription () - { - final JSONObject aux = keyEntry.optJSONObject ( "aux" ); - if ( aux != null ) - { - return aux.optString ( "description" ); - } - return null; - } - }; - } - - @Override - public void updateCurrentApiKey ( String email, String description ) throws HttpObjectNotFoundException, HttpException, IOException - { - final JSONObject o = new JSONObject (); - if ( email != null ) o.put ( "email", email ); - if ( description != null ) o.put ( "description", description ); - patch ( "/apiKeys/" + MRConstants.escape ( getCurrentApiKey() ), o ); - } - - @Override - public void deleteCurrentApiKey () throws HttpException, IOException - { - delete ( "/apiKeys/" + MRConstants.escape ( getCurrentApiKey() ) ); - } -} diff --git a/src/main/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisher.java b/src/main/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisher.java deleted file mode 100644 index 4f44d30..0000000 --- a/src/main/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisher.java +++ /dev/null @@ -1,927 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.zip.GZIPOutputStream; - -import javax.ws.rs.core.MultivaluedMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.http.HttpException; -import org.apache.http.HttpStatus; -import org.json.JSONArray; -import org.json.JSONObject; -import org.json.JSONTokener; - -import com.att.aft.dme2.api.DME2Client; -import com.att.aft.dme2.api.DME2Exception; -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.response.MRPublisherResponse; -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; - -public class MRSimplerBatchPublisher extends MRBaseClient implements MRBatchingPublisher { - private static final Logger logger = LoggerFactory.getLogger(MRSimplerBatchPublisher.class); - - public static class Builder { - public Builder() { - } - - public Builder againstUrls(Collection baseUrls) { - fUrls = baseUrls; - return this; - } - - public Builder againstUrlsOrServiceName ( Collection baseUrls, Collection serviceName, String transportype ) - { - fUrls = baseUrls; - fServiceName = serviceName; - fTransportype = transportype; - return this; - } - - public Builder onTopic(String topic) { - fTopic = topic; - return this; - } - - public Builder batchTo(int maxBatchSize, long maxBatchAgeMs) { - fMaxBatchSize = maxBatchSize; - fMaxBatchAgeMs = maxBatchAgeMs; - return this; - } - - public Builder compress(boolean compress) { - fCompress = compress; - return this; - } - - public Builder httpThreadTime(int threadOccuranceTime) { - this.threadOccuranceTime = threadOccuranceTime; - return this; - } - - public Builder allowSelfSignedCertificates(boolean allowSelfSignedCerts) { - fAllowSelfSignedCerts = allowSelfSignedCerts; - return this; - } - - public Builder withResponse(boolean withResponse) { - fWithResponse = withResponse; - return this; - } - - public MRSimplerBatchPublisher build() { - if (!fWithResponse) { - try { - return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, - fAllowSelfSignedCerts, threadOccuranceTime); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } else { - try { - return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, - fAllowSelfSignedCerts, fMaxBatchSize); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } - - } - - private Collection fUrls; - private Collection fServiceName; - private String fTransportype; - private String fTopic; - private int fMaxBatchSize = 100; - private long fMaxBatchAgeMs = 1000; - private boolean fCompress = false; - private int threadOccuranceTime = 50; - private boolean fAllowSelfSignedCerts = false; - private boolean fWithResponse = false; - - }; - - @Override - public int send(String partition, String msg) { - return send(new message(partition, msg)); - } - - @Override - public int send(String msg) { - return send(new message(null, msg)); - } - - @Override - public int send(message msg) { - final LinkedList list = new LinkedList(); - list.add(msg); - return send(list); - } - - @Override - public synchronized int send(Collection msgs) { - if (fClosed) { - throw new IllegalStateException("The publisher was closed."); - } - - for (message userMsg : msgs) { - fPending.add(new TimestampedMessage(userMsg)); - } - return getPendingMessageCount(); - } - - @Override - public synchronized int getPendingMessageCount() { - return fPending.size(); - } - - @Override - public void close() { - try { - final List remains = close(Long.MAX_VALUE, TimeUnit.MILLISECONDS); - if (remains.isEmpty()) { - getLog().warn("Closing publisher with " + remains.size() + " messages unsent. " - + "Consider using MRBatchingPublisher.close( long timeout, TimeUnit timeoutUnits ) to recapture unsent messages on close."); - } - } catch (InterruptedException e) { - getLog().warn("Possible message loss. " + e.getMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - getLog().warn("Possible message loss. " + e.getMessage(), e); - } - } - - @Override - public List close(long time, TimeUnit unit) throws IOException, InterruptedException { - synchronized (this) { - fClosed = true; - - // stop the background sender - fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - fExec.shutdown(); - } - - final long now = Clock.now(); - final long waitInMs = TimeUnit.MILLISECONDS.convert(time, unit); - final long timeoutAtMs = now + waitInMs; - - while (Clock.now() < timeoutAtMs && getPendingMessageCount() > 0) { - send(true); - Thread.sleep(250); - } - - synchronized (this) { - final LinkedList result = new LinkedList(); - fPending.drainTo(result); - return result; - } - } - - /** - * Possibly send a batch to the MR server. This is called by the background - * thread and the close() method - * - * @param force - */ - private synchronized void send(boolean force) { - if (force || shouldSendNow()) { - if (!sendBatch()) { - getLog().warn("Send failed, " + fPending.size() + " message to send."); - - // note the time for back-off - fDontSendUntilMs = sfWaitAfterError + Clock.now(); - } - } - } - - private synchronized boolean shouldSendNow() { - boolean shouldSend = false; - if (fPending.isEmpty()) { - final long nowMs = Clock.now(); - - shouldSend = (fPending.size() >= fMaxBatchSize); - if (!shouldSend) { - final long sendAtMs = fPending.peek().timestamp + fMaxBatchAgeMs; - shouldSend = sendAtMs <= nowMs; - } - - // however, wait after an error - shouldSend = shouldSend && nowMs >= fDontSendUntilMs; - } - return shouldSend; - } - - /** - * Method to parse published JSON Objects and Arrays - * - * @return JSONArray - */ - private JSONArray parseJSON() { - JSONArray jsonArray = new JSONArray(); - for (TimestampedMessage m : fPending) { - JSONTokener jsonTokener = new JSONTokener(m.fMsg); - JSONObject jsonObject = null; - JSONArray tempjsonArray = null; - final char firstChar = jsonTokener.next(); - jsonTokener.back(); - if ('[' == firstChar) { - tempjsonArray = new JSONArray(jsonTokener); - if (null != tempjsonArray) { - for (int i = 0; i < tempjsonArray.length(); i++) { - jsonArray.put(tempjsonArray.getJSONObject(i)); - } - } - } else { - jsonObject = new JSONObject(jsonTokener); - jsonArray.put(jsonObject); - } - - } - return jsonArray; - } - - private synchronized boolean sendBatch() { - // it's possible for this call to be made with an empty list. in this - // case, just return. - if (fPending.size() < 1) { - return true; - } - - final long nowMs = Clock.now(); - - if (this.fHostSelector != null) { - host = this.fHostSelector.selectBaseHost(); - } - - final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"), - props.getProperty("partition")); - - try { - - final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); - OutputStream os = baseStream; - final String contentType = props.getProperty("contenttype"); - if (contentType.equalsIgnoreCase("application/json")) { - JSONArray jsonArray = parseJSON(); - os.write(jsonArray.toString().getBytes()); - os.close(); - - } else if (contentType.equalsIgnoreCase("text/plain")) { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - os.close(); - } else if (contentType.equalsIgnoreCase("application/cambria") - || (contentType.equalsIgnoreCase("application/cambria-zip"))) { - if (contentType.equalsIgnoreCase("application/cambria-zip")) { - os = new GZIPOutputStream(baseStream); - } - for (TimestampedMessage m : fPending) { - - os.write(("" + m.fPartition.length()).getBytes()); - os.write('.'); - os.write(("" + m.fMsg.length()).getBytes()); - os.write('.'); - os.write(m.fPartition.getBytes()); - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - os.close(); - } else { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - - } - os.close(); - } - - final long startMs = Clock.now(); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { - - DME2Configue(); - - Thread.sleep(5); - getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - sender.setPayload(os.toString()); - String dmeResponse = sender.sendAndWait(5000L); - - final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + dmeResponse.toString(); - getLog().info(logLine); - fPending.clear(); - return true; - } - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - final JSONObject result = postAuth(httpurl, baseStream.toByteArray(), contentType, authKey, authDate, - username, password, protocolFlag); - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - if (result.getInt("status") < 200 || result.getInt("status") > 299) { - return false; - } - final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); - getLog().info(logLine); - fPending.clear(); - return true; - } - - if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - final JSONObject result = post(httpurl, baseStream.toByteArray(), contentType, username, password, - protocolFlag); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - if (result.getInt("status") < 200 || result.getInt("status") > 299) { - return false; - } - final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); - getLog().info(logLine); - fPending.clear(); - return true; - } - - if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - final JSONObject result = postNoAuth(httpurl, baseStream.toByteArray(), contentType); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - if (result.getInt("status") < 200 || result.getInt("status") > 299) { - return false; - } - final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); - getLog().info(logLine); - fPending.clear(); - return true; - } - } catch (IllegalArgumentException x) { - getLog().warn(x.getMessage(), x); - } catch (IOException x) { - getLog().warn(x.getMessage(), x); - } catch (HttpException x) { - getLog().warn(x.getMessage(), x); - } catch (Exception x) { - getLog().warn(x.getMessage(), x); - } - return false; - } - - public synchronized MRPublisherResponse sendBatchWithResponse() { - // it's possible for this call to be made with an empty list. in this - // case, just return. - if (fPending.isEmpty()) { - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - pubResponse.setResponseMessage("No Messages to send"); - return pubResponse; - } - - final long nowMs = Clock.now(); - - host = this.fHostSelector.selectBaseHost(); - - final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"), - props.getProperty("partition")); - OutputStream os = null; - try { - - final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); - os = baseStream; - final String contentType = props.getProperty("contenttype"); - if (contentType.equalsIgnoreCase("application/json")) { - JSONArray jsonArray = parseJSON(); - os.write(jsonArray.toString().getBytes()); - } else if (contentType.equalsIgnoreCase("text/plain")) { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - } else if (contentType.equalsIgnoreCase("application/cambria") - || (contentType.equalsIgnoreCase("application/cambria-zip"))) { - if (contentType.equalsIgnoreCase("application/cambria-zip")) { - os = new GZIPOutputStream(baseStream); - } - for (TimestampedMessage m : fPending) { - - os.write(("" + m.fPartition.length()).getBytes()); - os.write('.'); - os.write(("" + m.fMsg.length()).getBytes()); - os.write('.'); - os.write(m.fPartition.getBytes()); - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - os.close(); - } else { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - - } - } - - final long startMs = Clock.now(); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { - - try { - DME2Configue(); - - Thread.sleep(5); - getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - sender.setPayload(os.toString()); - - String dmeResponse = sender.sendAndWait(5000L); - - pubResponse = createMRPublisherResponse(dmeResponse, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - final String logLine = String.valueOf((Clock.now() - startMs)) + dmeResponse.toString(); - getLog().info(logLine); - fPending.clear(); - - } catch (DME2Exception x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(x.getErrorCode()); - pubResponse.setResponseMessage(x.getErrorMessage()); - } catch (URISyntaxException x) { - - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - pubResponse.setResponseMessage(x.getMessage()); - } catch (Exception x) { - - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage(x.getMessage()); - logger.error("exception: ", x); - - } - - return pubResponse; - } - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - final String result = postAuthwithResponse(httpurl, baseStream.toByteArray(), contentType, authKey, - authDate, username, password, protocolFlag); - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - - pubResponse = createMRPublisherResponse(result, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - - final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); - getLog().info(logLine); - fPending.clear(); - return pubResponse; - } - - if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - final String result = postWithResponse(httpurl, baseStream.toByteArray(), contentType, username, - password, protocolFlag); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - pubResponse = createMRPublisherResponse(result, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - - final String logLine = String.valueOf((Clock.now() - startMs)); - getLog().info(logLine); - fPending.clear(); - return pubResponse; - } - - if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " - + (nowMs - fPending.peek().timestamp) + " ms"); - final String result = postNoAuthWithResponse(httpurl, baseStream.toByteArray(), contentType); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - pubResponse = createMRPublisherResponse(result, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - - final String logLine = String.valueOf((Clock.now() - startMs)); - getLog().info(logLine); - fPending.clear(); - return pubResponse; - } - } catch (IllegalArgumentException x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - pubResponse.setResponseMessage(x.getMessage()); - - } catch (IOException x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage(x.getMessage()); - - } catch (HttpException x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - pubResponse.setResponseMessage(x.getMessage()); - - } catch (Exception x) { - getLog().warn(x.getMessage(), x); - - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage(x.getMessage()); - - } - - finally { - if (fPending.size() > 0) { - getLog().warn("Send failed, " + fPending.size() + " message to send."); - pubResponse.setPendingMsgs(fPending.size()); - } - if (os != null) { - try { - os.close(); - } catch (Exception x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage("Error in closing Output Stream"); - } - } - } - - return pubResponse; - } - - public MRPublisherResponse createMRPublisherResponse(String reply, MRPublisherResponse mrPubResponse) { - - if (reply.isEmpty()) { - - mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - mrPubResponse.setResponseMessage("Please verify the Producer properties"); - } else if (reply.startsWith("{")) { - JSONObject jObject = new JSONObject(reply); - if (jObject.has("message") && jObject.has("status")) { - String message = jObject.getString("message"); - if (null != message) { - mrPubResponse.setResponseMessage(message); - } - mrPubResponse.setResponseCode(Integer.toString(jObject.getInt("status"))); - } else { - mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK)); - mrPubResponse.setResponseMessage(reply); - } - } else if (reply.startsWith("<")) { - String responseCode = getHTTPErrorResponseCode(reply); - if (responseCode.contains("403")) { - responseCode = "403"; - } - mrPubResponse.setResponseCode(responseCode); - mrPubResponse.setResponseMessage(getHTTPErrorResponseMessage(reply)); - } - - return mrPubResponse; - } - - private final String fTopic; - private final int fMaxBatchSize; - private final long fMaxBatchAgeMs; - private final boolean fCompress; - private int threadOccuranceTime; - private boolean fClosed; - private String username; - private String password; - private String host; - - // host selector - private HostSelector fHostSelector = null; - - private final LinkedBlockingQueue fPending; - private long fDontSendUntilMs; - private final ScheduledThreadPoolExecutor fExec; - - private String latitude; - private String longitude; - private String version; - private String serviceName; - private String env; - private String partner; - private String routeOffer; - private String subContextPath; - private String protocol; - private String methodType; - private String url; - private String dmeuser; - private String dmepassword; - private String contentType; - private static final long sfWaitAfterError = 10000; - private HashMap DMETimeOuts; - private DME2Client sender; - public String protocolFlag = ProtocolTypeConstants.DME2.getValue(); - private String authKey; - private String authDate; - private String handlers; - private Properties props; - public static String routerFilePath; - protected static final Map headers = new HashMap(); - public static MultivaluedMap headersMap; - - private MRPublisherResponse pubResponse; - - public MRPublisherResponse getPubResponse() { - return pubResponse; - } - - public void setPubResponse(MRPublisherResponse pubResponse) { - this.pubResponse = pubResponse; - } - - public static String getRouterFilePath() { - return routerFilePath; - } - - public static void setRouterFilePath(String routerFilePath) { - MRSimplerBatchPublisher.routerFilePath = routerFilePath; - } - - public Properties getProps() { - return props; - } - - public void setProps(Properties props) { - this.props = props; - } - - public String getProtocolFlag() { - return protocolFlag; - } - - public void setProtocolFlag(String protocolFlag) { - this.protocolFlag = protocolFlag; - } - - private void DME2Configue() throws Exception { - try { - - latitude = props.getProperty("Latitude"); - longitude = props.getProperty("Longitude"); - version = props.getProperty("Version"); - serviceName = props.getProperty("ServiceName"); - env = props.getProperty("Environment"); - partner = props.getProperty("Partner"); - routeOffer = props.getProperty("routeOffer"); - subContextPath = props.getProperty("SubContextPath") + fTopic; - - protocol = props.getProperty("Protocol"); - methodType = props.getProperty("MethodType"); - dmeuser = props.getProperty("username"); - dmepassword = props.getProperty("password"); - contentType = props.getProperty("contenttype"); - handlers = props.getProperty("sessionstickinessrequired"); - routerFilePath = props.getProperty("DME2preferredRouterFilePath"); - - /** - * Changes to DME2Client url to use Partner for auto failover - * between data centers When Partner value is not provided use the - * routeOffer value for auto failover within a cluster - */ - - String partitionKey = props.getProperty("partition"); - - if (partner != null && !partner.isEmpty()) { - url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" - + partner; - if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { - url = url + "&partitionKey=" + partitionKey; - } - } else if (routeOffer != null && !routeOffer.isEmpty()) { - url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer=" - + routeOffer; - if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { - url = url + "&partitionKey=" + partitionKey; - } - } - - DMETimeOuts = new HashMap(); - DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); - DMETimeOuts.put("Content-Type", contentType); - System.setProperty("AFT_LATITUDE", latitude); - System.setProperty("AFT_LONGITUDE", longitude); - System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT")); - // System.setProperty("DME2.DEBUG", "true"); - - // SSL changes - // System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", - - System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2"); - System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false"); - System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit"); - - // SSL changes - - sender = new DME2Client(new URI(url), 5000L); - - sender.setAllowAllHttpReturnCodes(true); - sender.setMethod(methodType); - sender.setSubContext(subContextPath); - sender.setCredentials(dmeuser, dmepassword); - sender.setHeaders(DMETimeOuts); - if (handlers != null &&handlers.equalsIgnoreCase("yes")) { - sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", - props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS")); - sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", - props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS")); - sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON")); - } else { - sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler"); - } - } catch (DME2Exception x) { - getLog().warn(x.getMessage(), x); - throw new DME2Exception(x.getErrorCode(), x.getErrorMessage()); - } catch (URISyntaxException x) { - - getLog().warn(x.getMessage(), x); - throw new URISyntaxException(url, x.getMessage()); - } catch (Exception x) { - - getLog().warn(x.getMessage(), x); - throw new IllegalArgumentException(x.getMessage()); - } - } - - private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, - boolean compress) throws MalformedURLException { - super(hosts); - - if (topic == null || topic.length() < 1) { - throw new IllegalArgumentException("A topic must be provided."); - } - - fHostSelector = new HostSelector(hosts, null); - fClosed = false; - fTopic = topic; - fMaxBatchSize = maxBatchSize; - fMaxBatchAgeMs = maxBatchAgeMs; - fCompress = compress; - - fPending = new LinkedBlockingQueue(); - fDontSendUntilMs = 0; - fExec = new ScheduledThreadPoolExecutor(1); - pubResponse = new MRPublisherResponse(); - - } - - private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, - boolean compress, boolean allowSelfSignedCerts, int httpThreadOccurnace) throws MalformedURLException { - super(hosts); - - if (topic == null || topic.length() < 1) { - throw new IllegalArgumentException("A topic must be provided."); - } - - fHostSelector = new HostSelector(hosts, null); - fClosed = false; - fTopic = topic; - fMaxBatchSize = maxBatchSize; - fMaxBatchAgeMs = maxBatchAgeMs; - fCompress = compress; - threadOccuranceTime = httpThreadOccurnace; - fPending = new LinkedBlockingQueue(); - fDontSendUntilMs = 0; - fExec = new ScheduledThreadPoolExecutor(1); - fExec.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - send(false); - } - }, 100, threadOccuranceTime, TimeUnit.MILLISECONDS); - pubResponse = new MRPublisherResponse(); - } - - private static class TimestampedMessage extends message { - public TimestampedMessage(message m) { - super(m); - timestamp = Clock.now(); - } - - public final long timestamp; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - public String getAuthKey() { - return authKey; - } - - public void setAuthKey(String authKey) { - this.authKey = authKey; - } - - public String getAuthDate() { - return authDate; - } - - public void setAuthDate(String authDate) { - this.authDate = authDate; - } - -} diff --git a/src/main/java/com/att/nsa/mr/client/response/MRConsumerResponse.java b/src/main/java/com/att/nsa/mr/client/response/MRConsumerResponse.java deleted file mode 100644 index 102794e..0000000 --- a/src/main/java/com/att/nsa/mr/client/response/MRConsumerResponse.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.response; - -public class MRConsumerResponse { - - private String responseCode; - - private String responseMessage; - - private Iterable actualMessages; - - - - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } - - public String getResponseMessage() { - return responseMessage; - } - - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } - - public Iterable getActualMessages() { - return actualMessages; - } - - public void setActualMessages(Iterable actualMessages) { - this.actualMessages = actualMessages; - } - - -} diff --git a/src/main/java/com/att/nsa/mr/client/response/MRPublisherResponse.java b/src/main/java/com/att/nsa/mr/client/response/MRPublisherResponse.java deleted file mode 100644 index 96c39d6..0000000 --- a/src/main/java/com/att/nsa/mr/client/response/MRPublisherResponse.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.response; - -/** - * Response for Publisher - * @author author - * - */ -public class MRPublisherResponse { - private String responseCode; - - private String responseMessage; - - private int pendingMsgs; - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } - - public String getResponseMessage() { - return responseMessage; - } - - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } - - public int getPendingMsgs() { - return pendingMsgs; - } - - public void setPendingMsgs(int pendingMsgs) { - this.pendingMsgs = pendingMsgs; - } - - @Override - public String toString() { - return "Response Code:" + this.responseCode + "," - + "Response Message:" + this.responseMessage + "," + "Pending Messages Count" - + this.pendingMsgs; - } - -} diff --git a/src/main/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandler.java b/src/main/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandler.java deleted file mode 100644 index 4f04dec..0000000 --- a/src/main/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.dme.client; - - - -import java.util.logging.Level; -import java.util.logging.Logger; - - -//import com.att.aft.dme2.api.util.DME2Constants; -//import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; -//import com.att.aft.dme2.api.util.LogMessage; -//import com.att.aft.dme2.api.util.LogUtil; -public class DefaultLoggingFailoverFaultHandler /*implements DME2FailoverFaultHandler*/ { - //TODO: This code may be enable in the future when we implement DME2FailoverFaultHandler interface - /** The logger. */ - - -// @Override - -// // LogUtil.INSTANCE.report(logger, Level.WARNING, LogMessage.SEP_FAILOVER, context.getService(),context.getRequestURL(),context.getRouteOffer(),context.getResponseCode(),context.getException()); -// } -// @Override -// /** -// * The DME2Exchange already has a log message when the route offer is failed over. We dont need to log it again here. -// */ - -// //noop -// - -} - diff --git a/src/main/java/com/att/nsa/mr/dme/client/HeaderReplyHandler.java b/src/main/java/com/att/nsa/mr/dme/client/HeaderReplyHandler.java deleted file mode 100644 index 4363902..0000000 --- a/src/main/java/com/att/nsa/mr/dme/client/HeaderReplyHandler.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.dme.client; - - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; -import com.att.aft.dme2.api.util.DME2ExchangeReplyHandler; -import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher; - - - - - - public class HeaderReplyHandler implements DME2ExchangeReplyHandler { - - private Logger fLog = LoggerFactory.getLogger ( this.getClass().getName () ); - - - @Override public void handleFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - - } - @Override public void handleEndpointFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - - } -@Override public void handleReply(DME2ExchangeResponseContext responseData) { - - if(responseData != null) { - MRClientFactory.DME2HeadersMap=responseData.getResponseHeaders(); - if (responseData.getResponseHeaders().get("transactionId")!=null) - fLog.info("Transaction Id : " + responseData.getResponseHeaders().get("transactionId")); - - } -} - -} diff --git a/src/main/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandler.java b/src/main/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandler.java deleted file mode 100644 index 2da5ce9..0000000 --- a/src/main/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.dme.client; -import java.io.File; -import java.io.FileWriter; -import java.io.InputStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; -import com.att.aft.dme2.api.util.DME2ExchangeReplyHandler; -import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher; - -public class PreferredRouteReplyHandler implements DME2ExchangeReplyHandler { - private Logger fLog = LoggerFactory.getLogger ( this.getClass().getName () ); - @Override public void handleReply(DME2ExchangeResponseContext responseData) { - - if(responseData != null) { - MRClientFactory.DME2HeadersMap=responseData.getResponseHeaders(); - if (responseData.getResponseHeaders().get("transactionId")!=null) - - fLog.info("Transaction_Id : " + responseData.getResponseHeaders().get("transactionId")); - - if(responseData.getRouteOffer() != null ){ - routeWriter("preferredRouteKey",responseData.getRouteOffer()); - - } - } -} - - @Override public void handleFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - //StaticCache.getInstance().setHandleFaultInvoked(true); - } - @Override public void handleEndpointFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - - } - public void routeWriter(String routeKey, String routeValue){ - - try(FileWriter routeWriter=new FileWriter(new File (MRSimplerBatchPublisher.routerFilePath))){ - routeWriter.write(routeKey+"="+routeValue); - routeWriter.close(); - - }catch(Exception ex){ - fLog.error("Reply Router Error " + ex); - } - - } -} diff --git a/src/main/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandler.java b/src/main/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandler.java deleted file mode 100644 index fbc32a7..0000000 --- a/src/main/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.dme.client; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.aft.dme2.api.util.DME2ExchangeRequestContext; -import com.att.aft.dme2.api.util.DME2ExchangeRequestHandler; -import com.att.nsa.mr.client.MRClientFactory; - -public class PreferredRouteRequestHandler implements DME2ExchangeRequestHandler { - private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - @Override - public void handleRequest(DME2ExchangeRequestContext requestData) { - - if (requestData != null) { - - requestData.setPreferredRouteOffer(readRoute("preferredRouteKey")); - } - } - - public String readRoute(String routeKey) { - - try { - - MRClientFactory.prop.load(MRClientFactory.routeReader); - - } catch (Exception ex) { - logger.error("Request Router Error " + ex); - } - return MRClientFactory.prop.getProperty(routeKey); - } -} diff --git a/src/main/java/com/att/nsa/mr/dme/client/SimpleExampleConsumer.java b/src/main/java/com/att/nsa/mr/dme/client/SimpleExampleConsumer.java deleted file mode 100644 index ce0138c..0000000 --- a/src/main/java/com/att/nsa/mr/dme/client/SimpleExampleConsumer.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.dme.client; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.core.MultivaluedMap; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; - -import java.util.List; - -public class SimpleExampleConsumer { - - private static final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumer.class); - - private SimpleExampleConsumer() { - } - - public static void main(String[] args) { - - long count = 0; - long nextReport = 5000; - String key; - - final long startMs = System.currentTimeMillis(); - - try { - - final MRConsumer cc = MRClientFactory.createConsumer("D:\\SG\\consumer.properties"); - while (true) { - for (String msg : cc.fetch()) { - logger.debug("Message Received: " + msg); - } - // Header for DME2 Call. - MultivaluedMap headersMap = MRClientFactory.HTTPHeadersMap; - for (MultivaluedMap.Entry> entry : headersMap.entrySet()) { - key = entry.getKey(); - logger.debug("Header Key " + key); - logger.debug("Header Value " + headersMap.get(key)); - } - // Header for HTTP Call. - - Map dme2headersMap = MRClientFactory.DME2HeadersMap; - for (Map.Entry entry : dme2headersMap.entrySet()) { - key = entry.getKey(); - logger.debug("Header Key " + key); - logger.debug("Header Value " + dme2headersMap.get(key)); - } - - if (count > nextReport) { - nextReport += 5000; - - final long endMs = System.currentTimeMillis(); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - } - } - } catch (Exception x) { - logger.error(x.toString()); - } - } -} diff --git a/src/main/java/com/att/nsa/mr/dme/client/SimpleExamplePublisher.java b/src/main/java/com/att/nsa/mr/dme/client/SimpleExamplePublisher.java deleted file mode 100644 index f9e830c..0000000 --- a/src/main/java/com/att/nsa/mr/dme/client/SimpleExamplePublisher.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.dme.client; - - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import java.util.concurrent.TimeUnit; - -import javax.ws.rs.core.MultivaluedMap; - -import org.json.JSONObject; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRPublisher.message; - -/** - * An example of how to use the Java publisher. - * - * @author author - */ -public class SimpleExamplePublisher { - static String content = null; - static String messageSize = null; - static String transport = null; - static String messageCount = null; - - public void publishMessage(String producerFilePath) throws IOException, InterruptedException { - - // create our publisher - - // publish some messages - - - StringBuilder sb = new StringBuilder(); - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); - - if (content.equalsIgnoreCase("text/plain")) { - for (int i = 0; i < Integer.parseInt(messageCount); i++) { - for (int j = 0; j < Integer.parseInt(messageSize); j++) { - sb.append("T"); - } - - pub.send(sb.toString()); - } - } else if (content.equalsIgnoreCase("application/cambria")) { - for (int i = 0; i < Integer.parseInt(messageCount); i++) { - for (int j = 0; j < Integer.parseInt(messageSize); j++) { - sb.append("C"); - } - - pub.send("Key", sb.toString()); - } - } else if (content.equalsIgnoreCase("application/json")) { - for (int i = 0; i < Integer.parseInt(messageCount); i++) { - - final JSONObject msg12 = new JSONObject(); - msg12.put("Name", "DMaaP Reference Client to Test jason Message"); - - pub.send(msg12.toString()); - - } - } - - // ... - - // close the publisher to make sure everything's sent before exiting. - // The batching - // publisher interface allows the app to get the set of unsent messages. - // It could - // write them to disk, for example, to try to send them later. - /* final List stuck = pub.close(20, TimeUnit.SECONDS); - if (stuck.size() > 0) { - System.err.println(stuck.size() + " messages unsent"); - } else { - System.out.println("Clean exit; all messages sent."); - }*/ - - if (transport.equalsIgnoreCase("HTTP")) { - MultivaluedMap headersMap = MRClientFactory.HTTPHeadersMap; - for (String key : headersMap.keySet()) { - System.out.println("Header Key " + key); - System.out.println("Header Value " + headersMap.get(key)); - } - } else { - Map dme2headersMap = MRClientFactory.DME2HeadersMap; - for (String key : dme2headersMap.keySet()) { - System.out.println("Header Key " + key); - System.out.println("Header Value " + dme2headersMap.get(key)); - } - } - - } - - public static void main(String[] args) throws InterruptedException, Exception { - - String producerFilePath = args[0]; - content = args[1]; - messageSize = args[2]; - transport = args[3]; - messageCount = args[4]; - - - - - - SimpleExamplePublisher publisher = new SimpleExamplePublisher(); - - publisher.publishMessage("D:\\SG\\producer.properties"); - } - -} diff --git a/src/main/java/com/att/nsa/mr/logging/MRAppender.java b/src/main/java/com/att/nsa/mr/logging/MRAppender.java deleted file mode 100644 index 4bb3e71..0000000 --- a/src/main/java/com/att/nsa/mr/logging/MRAppender.java +++ /dev/null @@ -1,165 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -/** - * - */ -package com.att.nsa.mr.logging; - -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRPublisher; - -/** - * @author author - * - */ -public class MRAppender extends AppenderSkeleton { - - private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - private MRPublisher fPublisher; - - //Provided through log4j configuration - private String topic; - private String partition; - private String hosts; - private int maxBatchSize = 1; - private int maxAgeMs = 1000; - private boolean compress = false; - - /** - * - */ - public MRAppender() { - super(); - } - - /** - * @param isActive - */ - public MRAppender(boolean isActive) { - super(isActive); - } - - /* (non-Javadoc) - * @see org.apache.log4j.Appender#close() - */ - @Override - public void close() { - if (!this.closed) { - this.closed = true; - fPublisher.close(); - } - } - - /* (non-Javadoc) - * @see org.apache.log4j.Appender#requiresLayout() - */ - @Override - public boolean requiresLayout() { - return false; - } - - /* (non-Javadoc) - * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent) - */ - @Override - protected void append(LoggingEvent event) { - final String message; - - if (this.layout == null) { - message = event.getRenderedMessage(); - } else { - message = this.layout.format(event); - } - - try { - fPublisher.send(partition, message); - } catch (IOException e) { - logger.error("IOException: ", e); - } - } - - @Override - public void activateOptions() { - if (hosts != null && topic != null && partition != null) { - fPublisher = MRClientFactory.createBatchingPublisher(hosts.split(","), topic, maxBatchSize, maxAgeMs, compress); - } else { - logger.error("The Hosts, Topic, and Partition parameter are required to create a MR Log4J Appender"); - } - } - public String getTopic() { - return topic; - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public String getPartition() { - return partition; - } - - public void setPartition(String partition) { - this.partition = partition; - } - - public String getHosts() { - return hosts; - } - - public void setHosts(String hosts) { - this.hosts = hosts; - } - - public int getMaxBatchSize() { - return maxBatchSize; - } - - public void setMaxBatchSize(int maxBatchSize) { - this.maxBatchSize = maxBatchSize; - } - - public int getMaxAgeMs() { - return maxAgeMs; - } - - public void setMaxAgeMs(int maxAgeMs) { - this.maxAgeMs = maxAgeMs; - } - - public boolean isCompress() { - return compress; - } - - public void setCompress(boolean compress) { - this.compress = compress; - } - -} diff --git a/src/main/java/com/att/nsa/mr/test/clients/ConsolePublisher.java b/src/main/java/com/att/nsa/mr/test/clients/ConsolePublisher.java deleted file mode 100644 index 60971c1..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/ConsolePublisher.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.test.clients; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRPublisher.message; - -/** - * A simple publisher that reads from std in, sending each line as a message. - * @author author - */ -public class ConsolePublisher -{ - - private static final Logger logger = LoggerFactory.getLogger(ConsolePublisher.class); - private ConsolePublisher() { - } - public static void main ( String[] args ) throws IOException //throws IOException, InterruptedException - { - // read the hosts(s) from the command line - final String hosts = args.length > 0 ? args[0] : "aaa.it.att.com,bbb.it.att.com,ccc.it.att.com"; - - // read the topic name from the command line - final String topic = args.length > 1 ? args[1] : "TEST-TOPIC"; - - // read the topic name from the command line - final String partition = args.length > 2 ? args[2] : UUID.randomUUID ().toString (); - - // set up some batch limits and the compression flag - final int maxBatchSize = 100; - final long maxAgeMs = 250; - final boolean withGzip = false; - - // create our publisher - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher ( hosts, topic, maxBatchSize, maxAgeMs, withGzip ); - - final BufferedReader cin = new BufferedReader ( new InputStreamReader ( System.in ) ); - try - { - String line = null; - while ( ( line = cin.readLine () ) != null ) - { - pub.send ( partition, line ); - } - } - finally - { - List leftovers = null; - try - { - leftovers = pub.close ( 10, TimeUnit.SECONDS ); - } - catch ( InterruptedException e ) - { - logger.error( "Send on close interrupted." ); - Thread.currentThread().interrupt(); - } - for ( message m : leftovers ) - { - logger.error( "Unsent message: " + m.fMsg ); - } - } - } -} diff --git a/src/main/java/com/att/nsa/mr/test/clients/ProtocolTypeConstants.java b/src/main/java/com/att/nsa/mr/test/clients/ProtocolTypeConstants.java deleted file mode 100644 index a4a176e..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/ProtocolTypeConstants.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -/** - * - */ -package com.att.nsa.mr.test.clients; - -/** - * @author author - * - */ -public enum ProtocolTypeConstants { - - DME2("DME2"), AAF_AUTH("HTTPAAF"), AUTH_KEY("HTTPAUTH"), HTTPNOAUTH("HTTPNOAUTH"); - - private String value; - - private ProtocolTypeConstants(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} diff --git a/src/main/java/com/att/nsa/mr/test/clients/SampleConsumer.java b/src/main/java/com/att/nsa/mr/test/clients/SampleConsumer.java deleted file mode 100644 index 44e5205..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/SampleConsumer.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.test.clients; - -import java.util.LinkedList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; - -public class SampleConsumer { - private SampleConsumer() { - } - public static void main ( String[] args ) - { - final Logger log = LoggerFactory.getLogger(SampleConsumer.class); - - - log.info("Sample Consumer Class executing"); - final String topic = "com.att.app.dmaap.mr.testingTopic"; - final String url = ( args.length > 1 ? args[1] : "localhost:8181" ); - final String group = ( args.length > 2 ? args[2] :"grp" ); - - final String id = ( args.length > 3 ? args[3] : "1" ); - - long count = 0; - long nextReport = 5000; - - final long startMs = System.currentTimeMillis (); - - final LinkedList urlList = new LinkedList<> (); - for ( String u : url.split ( "," ) ) - { - urlList.add ( u ); - } - - final MRConsumer cc = MRClientFactory.createConsumer ( urlList, topic, group, id, 10*1000, 1000, null, "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88" ); - try - { - while ( true ) - { - for ( String msg : cc.fetch () ) - { - log.info ( "" + (++count) + ": " + msg ); - } - - if ( count > nextReport ) - { - nextReport += 5000; - - final long endMs = System.currentTimeMillis (); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - log.info ( "Consumed " + count + " in " + elapsedSec + "; " + eps + " eps" ); - } - log.info ( "" + (++count) + ": consumed message" ); - } - } - catch ( Exception x ) - { - log.error( x.getClass().getName () + ": " + x.getMessage () ); - throw new IllegalArgumentException(x); - } - } -} diff --git a/src/main/java/com/att/nsa/mr/test/clients/SamplePublisher.java b/src/main/java/com/att/nsa/mr/test/clients/SamplePublisher.java deleted file mode 100644 index 0233dcb..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/SamplePublisher.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.test.clients; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRClientBuilders.PublisherBuilder; -import com.att.nsa.mr.client.MRPublisher.message; - -public class SamplePublisher { - public static void main ( String[] args ) throws IOException, InterruptedException - { - final Logger LOG = LoggerFactory.getLogger(SampleConsumer.class); - // read the hosts(s) from the command line - final String hosts = ( args.length > 0 ? args[0] : "localhost:8181" ); - - // read the topic name from the command line - - final String topic = ( args.length > 1 ? args[1] : "com.att.app.dmaap.mr.testingTopic" ); - - // set up some batch limits and the compression flag - final int maxBatchSize = 100; - final int maxAgeMs = 250; - final boolean withGzip = false; - - // create our publisher - - final MRBatchingPublisher pub = new PublisherBuilder (). - usingHosts ( hosts ). - onTopic ( topic ).limitBatch(maxBatchSize, maxAgeMs). - authenticatedBy ( "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88" ). - build () - ; - // publish some messages - final JSONObject msg1 = new JSONObject (); - msg1.put ( "name", "tttttttttttttttt" ); - msg1.put ( "greeting", "ooooooooooooooooo" ); - pub.send ( "MyPartitionKey", msg1.toString () ); - - final JSONObject msg2 = new JSONObject (); - msg2.put ( "now", System.currentTimeMillis () ); - pub.send ( "MyOtherPartitionKey", msg2.toString () ); - - // ... - - // close the publisher to make sure everything's sent before exiting. The batching - // publisher interface allows the app to get the set of unsent messages. It could - // write them to disk, for example, to try to send them later. - final List stuck = pub.close ( 20, TimeUnit.SECONDS ); - if ( stuck.isEmpty()) - { - LOG.warn ( stuck.size() + " messages unsent" ); - } - else - { - LOG.info ( "Clean exit; all messages sent." ); - } - } -} diff --git a/src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumer.java b/src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumer.java deleted file mode 100644 index 0e3ee5a..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumer.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.test.clients; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; - -public class SimpleExampleConsumer { - - static FileWriter routeWriter = null; - static Properties props = null; - static FileReader routeReader = null; - - public static void main(String[] args) { - final Logger LOG = LoggerFactory.getLogger(SimpleExampleConsumer.class); - - long count = 0; - long nextReport = 5000; - - final long startMs = System.currentTimeMillis(); - - try { - String routeFilePath = "/src/main/resources/dme2/preferredRoute.txt"; - - File fo = new File(routeFilePath); - if (!fo.exists()) { - routeWriter = new FileWriter(new File(routeFilePath)); - } - routeReader = new FileReader(new File(routeFilePath)); - props = new Properties(); - final MRConsumer cc = MRClientFactory.createConsumer("/src/main/resources/dme2/consumer.properties"); - int i = 0; - while (i < 10) { - Thread.sleep(2); - i++; - for (String msg : cc.fetch()) { - // System.out.println ( "" + (++count) + ": " + msg ); - System.out.println(msg); - } - - if (count > nextReport) { - nextReport += 5000; - - final long endMs = System.currentTimeMillis(); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - System.out.println("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); - } - } - } catch (Exception x) { - System.err.println(x.getClass().getName() + ": " + x.getMessage()); - LOG.error("exception: ", x); - } - } -} diff --git a/src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java b/src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java deleted file mode 100644 index 433ab9f..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.test.clients; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.response.MRConsumerResponse; - -public class SimpleExampleConsumerWithReturnResponse { - - private static final Logger LOG = LoggerFactory.getLogger(SimpleExampleConsumerWithReturnResponse.class); - - static FileWriter routeWriter= null; - static Properties props=null; - static FileReader routeReader=null; - public static void main ( String[] args ) - { - - long count = 0; - long nextReport = 5000; - - final long startMs = System.currentTimeMillis (); - - try - { - String routeFilePath="src/main/resources/dme2/preferredRoute.txt"; - - - File fo= new File(routeFilePath); - if(!fo.exists()){ - routeWriter=new FileWriter(new File (routeFilePath)); - } - routeReader= new FileReader(new File (routeFilePath)); - props= new Properties(); - final MRConsumer cc = MRClientFactory.createConsumer ( "src/main/resources/dme2/consumer.properties" ); - while ( true ) - { - MRConsumerResponse mrConsumerResponse = cc.fetchWithReturnConsumerResponse(); - System.out.println("mrConsumerResponse code :"+mrConsumerResponse.getResponseCode()); - - System.out.println("mrConsumerResponse Message :"+mrConsumerResponse.getResponseMessage()); - - System.out.println("mrConsumerResponse ActualMessage :"+mrConsumerResponse.getActualMessages()); - /*for ( String msg : mrConsumerResponse.getActualMessages() ) - { - //System.out.println ( "" + (++count) + ": " + msg ); - System.out.println(msg); - }*/ - if ( count > nextReport ) - { - nextReport += 5000; - - final long endMs = System.currentTimeMillis (); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - System.out.println ( "Consumed " + count + " in " + elapsedSec + "; " + eps + " eps" ); - } - } - } - catch ( Exception x ) - { - System.err.println ( x.getClass().getName () + ": " + x.getMessage () ); - LOG.error("exception: ", x); - } - } - -} diff --git a/src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisher.java b/src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisher.java deleted file mode 100644 index 8a6c586..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisher.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.test.clients; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.json.JSONObject; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRPublisher.message; - -/** - * An example of how to use the Java publisher. - * @author author - */ -public class SimpleExamplePublisher -{ - static FileWriter routeWriter= null; - static Properties props=null; - static FileReader routeReader=null; - public void publishMessage ( String producerFilePath ) throws IOException, InterruptedException, Exception - { - - // create our publisher - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath); - // publish some messages - final JSONObject msg1 = new JSONObject (); - msg1.put ( "Name", "Sprint" ); - - pub.send ( "First cambria messge" ); - pub.send ( "MyPartitionKey", msg1.toString () ); - - final JSONObject msg2 = new JSONObject (); - - - - // ... - - // close the publisher to make sure everything's sent before exiting. The batching - // publisher interface allows the app to get the set of unsent messages. It could - // write them to disk, for example, to try to send them later. - final List stuck = pub.close ( 20, TimeUnit.SECONDS ); - if ( stuck.isEmpty() ) - { - System.err.println ( stuck.size() + " messages unsent" ); - } - else - { - System.out.println ( "Clean exit; all messages sent." ); - } - } - - public static void main(String []args) throws InterruptedException, Exception{ - - String routeFilePath="/src/main/resources/dme2/preferredRoute.txt"; - - SimpleExamplePublisher publisher = new SimpleExamplePublisher(); - - - File fo= new File(routeFilePath); - if(!fo.exists()){ - routeWriter=new FileWriter(new File (routeFilePath)); - } - routeReader= new FileReader(new File (routeFilePath)); - props= new Properties(); - publisher.publishMessage("/src/main/resources/dme2/producer.properties"); - } - -} - diff --git a/src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponse.java b/src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponse.java deleted file mode 100644 index 9d179b2..0000000 --- a/src/main/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponse.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.test.clients; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import org.json.JSONObject; -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.response.MRPublisherResponse; - /** - *An example of how to use the Java publisher. - * @author author - * - */ - public class SimpleExamplePublisherWithResponse - { - static FileWriter routeWriter= null; - static Properties props=null; - static FileReader routeReader=null; - - public static void main(String []args) throws InterruptedException, Exception{ - - String routeFilePath="src/main/resources/dme2/preferredRoute.txt"; - String msgCount = args[0]; - SimpleExamplePublisherWithResponse publisher = new SimpleExamplePublisherWithResponse(); - File fo= new File(routeFilePath); - if(!fo.exists()){ - routeWriter=new FileWriter(new File (routeFilePath)); - } - routeReader= new FileReader(new File (routeFilePath)); - props= new Properties(); - int i=0; - while (i< Integer.valueOf(msgCount)) - { - publisher.publishMessage("src/main/resources/dme2/producer.properties",Integer.valueOf(msgCount)); - i++; - } - } - - public void publishMessage ( String producerFilePath , int count ) throws IOException, InterruptedException - { - // create our publisher - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath,true); - // publish some messages - final JSONObject msg1 = new JSONObject (); - - msg1.put ( "Partition:1", "Message:"+count); - msg1.put ( "greeting", "Hello .." ); - - - pub.send ( "1", msg1.toString()); - pub.send ( "1", msg1.toString()); - - MRPublisherResponse res= pub.sendBatchWithResponse(); - - System.out.println("Pub response->"+res.toString()); - } - - - } diff --git a/src/main/java/com/att/nsa/mr/test/support/MRBatchingPublisherMock.java b/src/main/java/com/att/nsa/mr/test/support/MRBatchingPublisherMock.java deleted file mode 100644 index 56bec36..0000000 --- a/src/main/java/com/att/nsa/mr/test/support/MRBatchingPublisherMock.java +++ /dev/null @@ -1,184 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.test.support; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.response.MRPublisherResponse; - -/** - * A helper for unit testing systems that use a MRPublisher. When setting - * up your test, inject an instance into MRClientFactory to have it return - * the mock client. - * - * @author author - * - */ -public class MRBatchingPublisherMock implements MRBatchingPublisher -{ - public class Entry - { - public Entry ( String partition, String msg ) - { - fPartition = partition; - fMessage = msg; - } - - @Override - public String toString () - { - return fMessage; - } - - public final String fPartition; - public final String fMessage; - } - - public MRBatchingPublisherMock () - { - fCaptures = new LinkedList<> (); - } - - public interface Listener - { - void onMessage ( Entry e ); - } - public void addListener ( Listener listener ) - { - fListeners.add ( listener ); - } - - public List getCaptures () - { - return getCaptures ( new MessageFilter () { @Override public boolean match ( String msg ) { return true; } } ); - } - - public interface MessageFilter - { - boolean match ( String msg ); - } - - public List getCaptures ( MessageFilter filter ) - { - final LinkedList result = new LinkedList<> (); - for ( Entry capture : fCaptures ) - { - if ( filter.match ( capture.fMessage ) ) - { - result.add ( capture ); - } - } - return result; - } - - public int received () - { - return fCaptures.size(); - } - - public void reset () - { - fCaptures.clear (); - } - - @Override - public int send ( String partition, String msg ) - { - final Entry e = new Entry ( partition, msg ); - - fCaptures.add ( e ); - for ( Listener l : fListeners ) - { - l.onMessage ( e ); - } - return 1; - } - - @Override - public int send ( message msg ) - { - return send ( msg.fPartition, msg.fMsg ); - } - @Override - public int send ( String msg ) - { - return 1; - - } - - @Override - public int send ( Collection msgs ) - { - int sum = 0; - for ( message m : msgs ) - { - sum += send ( m ); - } - return sum; - } - - @Override - public int getPendingMessageCount () - { - return 0; - } - - @Override - public List close ( long timeout, TimeUnit timeoutUnits ) - { - return new LinkedList<> (); - } - - @Override - public void close () - { - } - - @Override - public void setApiCredentials ( String apiKey, String apiSecret ) - { - } - - @Override - public void clearApiCredentials () - { - } - - @Override - public void logTo ( Logger log ) - { - } - - private final LinkedList fCaptures; - private LinkedList fListeners = new LinkedList<> (); - @Override - public MRPublisherResponse sendBatchWithResponse() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/src/main/java/com/att/nsa/mr/test/support/MRConsumerMock.java b/src/main/java/com/att/nsa/mr/test/support/MRConsumerMock.java deleted file mode 100644 index c731030..0000000 --- a/src/main/java/com/att/nsa/mr/test/support/MRConsumerMock.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.test.support; - -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - -import org.slf4j.Logger; - -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.response.MRConsumerResponse; - -/** - * A helper for unit testing systems that use a MRConsumer. When setting - * up your test, inject an instance into MRClientFactory to have it return - * the mock client. - * - * @author author - * - */ -public class MRConsumerMock implements MRConsumer -{ - public class Entry - { - public Entry ( long waitMs, int statusCode, List msgs ) - { - fWaitMs = waitMs; - fStatusCode = statusCode; - fStatusMsg = null; - fMsgs = new LinkedList<> ( msgs ); - } - - public Entry ( long waitMs, int statusCode, String statusMsg ) - { - fWaitMs = waitMs; - fStatusCode = statusCode; - fStatusMsg = statusMsg; - fMsgs = null; - } - - public LinkedList run () throws IOException - { - try - { - Thread.sleep ( fWaitMs ); - if ( fStatusCode >= 200 && fStatusCode <= 299 ) - { - return fMsgs; - } - throw new IOException ( "" + fStatusCode + " " + fStatusMsg ); - } - catch ( InterruptedException e ) - { - Thread.currentThread().interrupt(); - throw new IOException ( e ); - } - } - - private final long fWaitMs; - private final int fStatusCode; - private final String fStatusMsg; - private final LinkedList fMsgs; - } - - public MRConsumerMock () - { - fReplies = new LinkedList<> (); - } - - @Override - public void close () - { - } - - @Override - public void setApiCredentials ( String apiKey, String apiSecret ) - { - } - - @Override - public void clearApiCredentials () - { - } - - public synchronized void add ( Entry e ) - { - fReplies.add ( e ); - } - - public void addImmediateMsg ( String msg ) - { - addDelayedMsg ( 0, msg ); - } - - public void addDelayedMsg ( long delay, String msg ) - { - final LinkedList list = new LinkedList<> (); - list.add ( msg ); - add ( new Entry ( delay, 200, list ) ); - } - - public void addImmediateMsgGroup ( List msgs ) - { - addDelayedMsgGroup ( 0, msgs ); - } - - public void addDelayedMsgGroup ( long delay, List msgs ) - { - final LinkedList list = new LinkedList<> ( msgs ); - add ( new Entry ( delay, 200, list ) ); - } - - public void addImmediateError ( int statusCode, String statusText ) - { - add ( new Entry ( 0, statusCode, statusText ) ); - } - - @Override - public Iterable fetch () throws IOException - { - return fetch ( -1, -1 ); - } - - @Override - public Iterable fetch ( int timeoutMs, int limit ) throws IOException - { - return fReplies.size () > 0 ? fReplies.removeFirst ().run() : new LinkedList(); - } - - @Override - public void logTo ( Logger log ) - { - } - - private final LinkedList fReplies; - - @Override - public MRConsumerResponse fetchWithReturnConsumerResponse() { - // TODO Auto-generated method stub - return null; - } - - @Override - public MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, - int limit) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/src/main/java/com/att/nsa/mr/tools/ApiKeyCommand.java b/src/main/java/com/att/nsa/mr/tools/ApiKeyCommand.java deleted file mode 100644 index df28fc0..0000000 --- a/src/main/java/com/att/nsa/mr/tools/ApiKeyCommand.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.io.IOException; -import java.io.PrintStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRIdentityManager; -import com.att.nsa.mr.client.MRClient.MRApiException; -import com.att.nsa.mr.client.MRIdentityManager.ApiKey; - -public class ApiKeyCommand implements Command -{ - final Logger log = LoggerFactory.getLogger(ApiKeyCommand.class); - @Override - public String[] getMatches () - { - return new String[]{ - "key (create|update) (\\S*) (\\S*)", - "key (list) (\\S*)", - "key (revoke)", - }; - } - - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - if ( !context.checkClusterReady () ) - { - throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); - } - } - - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - final MRIdentityManager tm = MRClientFactory.createIdentityManager ( context.getCluster(), context.getApiKey(), context.getApiPwd() ); - context.applyTracer ( tm ); - - try - { - if ( parts[0].equals ( "list" ) ) - { - final ApiKey key = tm.getApiKey ( parts[1] ); - if ( key != null ) - { - out.println ( "email: " + key.getEmail () ); - out.println ( "description: " + key.getDescription () ); - } - else - { - out.println ( "No key returned" ); - } - } - else if ( parts[0].equals ( "create" ) ) - { - final ApiCredential ac = tm.createApiKey ( parts[1], parts[2] ); - if ( ac != null ) - { - out.println ( " key: " + ac.getApiKey () ); - out.println ( "secret: " + ac.getApiSecret () ); - } - else - { - out.println ( "No credential returned?" ); - } - } - else if ( parts[0].equals ( "update" ) ) - { - tm.updateCurrentApiKey ( parts[1], parts[2] ); - out.println ( "Updated" ); - } - else if ( parts[0].equals ( "revoke" ) ) - { - tm.deleteCurrentApiKey (); - out.println ( "Updated" ); - } - } - catch ( HttpObjectNotFoundException e ) - { - out.println ( "Object not found: " + e.getMessage () ); - log.error("HttpObjectNotFoundException: ", e); - } - catch ( HttpException e ) - { - out.println ( "HTTP exception: " + e.getMessage () ); - log.error("HttpException: ", e); - } - catch ( MRApiException e ) - { - out.println ( "API exception: " + e.getMessage () ); - log.error("MRApiException: ", e); - } - catch ( IOException e ) - { - out.println ( "IO exception: " + e.getMessage () ); - log.error("IOException: ", e); - } - finally - { - tm.close (); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "key create " ); - out.println ( "key update " ); - out.println ( "key list " ); - out.println ( "key revoke" ); - } -} diff --git a/src/main/java/com/att/nsa/mr/tools/AuthCommand.java b/src/main/java/com/att/nsa/mr/tools/AuthCommand.java deleted file mode 100644 index 72f226b..0000000 --- a/src/main/java/com/att/nsa/mr/tools/AuthCommand.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.io.PrintStream; - -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; - -public class AuthCommand implements Command -{ - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - if ( parts.length > 0 ) - { - context.setAuth ( parts[0], parts[1] ); - out.println ( "Now authenticating with " + parts[0] ); - } - else - { - context.clearAuth (); - out.println ( "No longer authenticating." ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "auth " ); - out.println ( "\tuse these credentials on subsequent transactions" ); - out.println ( "noauth" ); - out.println ( "\tdo not use credentials on subsequent transactions" ); - } - - @Override - public String[] getMatches () - { - return new String[] - { - "auth (\\S*) (\\S*)", - "noauth" - }; - } -} diff --git a/src/main/java/com/att/nsa/mr/tools/ClusterCommand.java b/src/main/java/com/att/nsa/mr/tools/ClusterCommand.java deleted file mode 100644 index 5ecaf7c..0000000 --- a/src/main/java/com/att/nsa/mr/tools/ClusterCommand.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.io.PrintStream; - -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.impl.MRConsumerImpl; - -public class ClusterCommand implements Command -{ - - @Override - public String[] getMatches () - { - return new String[]{ - "cluster", - "cluster (\\S*)?", - }; - } - - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - if ( parts.length == 0 ) - { - for ( String host : context.getCluster () ) - { - out.println ( host ); - } - } - else - { - context.clearCluster (); - for ( String part : parts ) - { - String[] hosts = part.trim().split ( "\\s+" ); - for ( String host : hosts ) - { - for ( String splitHost : MRConsumerImpl.stringToList(host) ) - { - context.addClusterHost ( splitHost ); - } - } - } - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "cluster host1 host2 ..." ); - } - -} diff --git a/src/main/java/com/att/nsa/mr/tools/MRCommandContext.java b/src/main/java/com/att/nsa/mr/tools/MRCommandContext.java deleted file mode 100644 index e512769..0000000 --- a/src/main/java/com/att/nsa/mr/tools/MRCommandContext.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.util.Collection; -import java.util.LinkedList; - -import com.att.nsa.apiClient.http.HttpClient; -import com.att.nsa.apiClient.http.HttpTracer; -import com.att.nsa.cmdtool.CommandContext; -import com.att.nsa.mr.client.MRClient; - -public class MRCommandContext implements CommandContext -{ - public MRCommandContext () - { - fApiKey = null; - fApiPwd = null; - - fCluster = new LinkedList<> (); - fCluster.add ( "localhost" ); - } - - @Override - public void requestShutdown () - { - fShutdown = true; - } - - @Override - public boolean shouldContinue () - { - return !fShutdown; - } - - public void setAuth ( String key, String pwd ) { fApiKey = key; fApiPwd = pwd; } - public void clearAuth () { setAuth(null,null); } - - public boolean checkClusterReady () - { - return ( fCluster.isEmpty()); - } - - public Collection getCluster () - { - return new LinkedList<> ( fCluster ); - } - - public void clearCluster () - { - fCluster.clear (); - } - - public void addClusterHost ( String host ) - { - fCluster.add ( host ); - } - - public String getApiKey () { return fApiKey; } - public String getApiPwd () { return fApiPwd; } - - public void useTracer ( HttpTracer t ) - { - fTracer = t; - } - public void noTracer () { fTracer = null; } - - public void applyTracer ( MRClient cc ) - { - if ( cc instanceof HttpClient && fTracer != null ) - { - ((HttpClient)cc).installTracer ( fTracer ); - } - } - - private boolean fShutdown; - private String fApiKey; - private String fApiPwd; - private final LinkedList fCluster; - private HttpTracer fTracer = null; -} diff --git a/src/main/java/com/att/nsa/mr/tools/MRTool.java b/src/main/java/com/att/nsa/mr/tools/MRTool.java deleted file mode 100644 index 7f1effd..0000000 --- a/src/main/java/com/att/nsa/mr/tools/MRTool.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.io.IOException; - -import com.att.nsa.cmdtool.CommandLineTool; -import com.att.nsa.mr.client.impl.MRClientVersionInfo; - -public class MRTool extends CommandLineTool -{ - protected MRTool () - { - super ( "MR Tool (" + MRClientVersionInfo.getVersion () + ")", "MR> " ); - - registerCommand ( new ApiKeyCommand () ); - registerCommand ( new AuthCommand () ); - registerCommand ( new ClusterCommand () ); - registerCommand ( new MessageCommand () ); - registerCommand ( new TopicCommand () ); - registerCommand ( new TraceCommand () ); - } - - public static void main ( String[] args ) throws IOException - { - final MRTool ct = new MRTool (); - final MRCommandContext ccc = new MRCommandContext (); - ct.runFromMain ( args, ccc ); - } -} diff --git a/src/main/java/com/att/nsa/mr/tools/MessageCommand.java b/src/main/java/com/att/nsa/mr/tools/MessageCommand.java deleted file mode 100644 index 54e92ae..0000000 --- a/src/main/java/com/att/nsa/mr/tools/MessageCommand.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.MRClientBuilders.PublisherBuilder; -import com.att.nsa.mr.client.MRPublisher.message; - -public class MessageCommand implements Command -{ - final Logger logger = LoggerFactory.getLogger(ApiKeyCommand.class); - @Override - public String[] getMatches () - { - return new String[]{ - "(post) (\\S*) (\\S*) (.*)", - "(read) (\\S*) (\\S*) (\\S*)", - }; - } - - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - if ( !context.checkClusterReady () ) - { - throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); - } - } - - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - if ( parts[0].equalsIgnoreCase ( "read" )) - { - final MRConsumer cc = MRClientFactory.createConsumer ( context.getCluster (), parts[1], parts[2], parts[3], - -1, -1, null, context.getApiKey(), context.getApiPwd() ); - context.applyTracer ( cc ); - try - { - for ( String msg : cc.fetch () ) - { - out.println ( msg ); - } - } - catch ( Exception e ) - { - out.println ( "Problem fetching messages: " + e.getMessage() ); - logger.error("Problem fetching messages: ", e); - } - finally - { - cc.close (); - } - } - else - { - final MRBatchingPublisher pub=ToolsUtil.createBatchPublisher(context, parts[1]); - try - { - pub.send ( parts[2], parts[3] ); - } - catch ( IOException e ) - { - out.println ( "Problem sending message: " + e.getMessage() ); - logger.error("Problem sending message: ", e); - } - finally - { - List left = null; - try - { - left = pub.close ( 500, TimeUnit.MILLISECONDS ); - } - catch ( IOException e ) - { - out.println ( "Problem sending message: " + e.getMessage() ); - logger.error("Problem sending message: ", e); - } - catch ( InterruptedException e ) - { - out.println ( "Problem sending message: " + e.getMessage() ); - logger.error("Problem sending message: ", e); - Thread.currentThread().interrupt(); - } - if ( left != null && left.isEmpty() ) - { - out.println ( left.size() + " messages not sent." ); - } - } - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "post " ); - out.println ( "read " ); - } - -} diff --git a/src/main/java/com/att/nsa/mr/tools/ToolsUtil.java b/src/main/java/com/att/nsa/mr/tools/ToolsUtil.java deleted file mode 100644 index 45b21d1..0000000 --- a/src/main/java/com/att/nsa/mr/tools/ToolsUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientBuilders.PublisherBuilder; - -public final class ToolsUtil { - - private ToolsUtil() { - } - - public static MRBatchingPublisher createBatchPublisher(MRCommandContext context,String topicName){ - - return new PublisherBuilder (). - usingHosts ( context.getCluster () ). - onTopic (topicName). - authenticatedBy ( context.getApiKey(), context.getApiPwd() ). - build (); - } - -} diff --git a/src/main/java/com/att/nsa/mr/tools/TopicCommand.java b/src/main/java/com/att/nsa/mr/tools/TopicCommand.java deleted file mode 100644 index 4b1151e..0000000 --- a/src/main/java/com/att/nsa/mr/tools/TopicCommand.java +++ /dev/null @@ -1,221 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRTopicManager; -import com.att.nsa.mr.client.MRTopicManager.TopicInfo; - -public class TopicCommand implements Command -{ - final Logger logger = LoggerFactory.getLogger(ApiKeyCommand.class); - @Override - public String[] getMatches () - { - return new String[]{ - "topic (list)", - "topic (list) (\\S*)", - "topic (create) (\\S*) (\\S*) (\\S*)", - "topic (grant|revoke) (read|write) (\\S*) (\\S*)", - }; - } - - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - if ( !context.checkClusterReady () ) - { - throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); - } - } - - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - final MRTopicManager tm = MRClientFactory.createTopicManager ( context.getCluster(), context.getApiKey(), context.getApiPwd() ); - context.applyTracer ( tm ); - - try - { - if ( parts[0].equals ( "list" ) ) - { - try - { - if ( parts.length == 1 ) - { - for ( String topic : tm.getTopics () ) - { - out.println ( topic ); - } - } - else - { - final TopicInfo ti = tm.getTopicMetadata ( parts[1] ); - - final String owner = ti.getOwner (); - out.println ( " owner: " + ( owner == null ? "" : owner ) ); - - final String desc = ti.getDescription (); - out.println ( "description: " + ( desc == null ? "" : desc ) ); - - final Set prods = ti.getAllowedProducers (); - if ( prods != null ) - { - out.println ( " write ACL: " ); - for ( String key : prods ) - { - out.println ( "\t" + key ); - } - } - else - { - out.println ( " write ACL: " ); - } - - final Set cons = ti.getAllowedConsumers (); - if ( cons != null ) - { - out.println ( " read ACL: " ); - for ( String key : cons ) - { - out.println ( "\t" + key ); - } - } - else - { - out.println ( " read ACL: " ); - } - } - } - catch ( IOException x ) - { - out.println ( "Problem with request: " + x.getMessage () ); - logger.error("IOException: ", x); - } - catch ( HttpObjectNotFoundException e ) - { - out.println ( "Not found: " + e.getMessage () ); - logger.error("HttpObjectNotFoundException: ", e); - } - } - else if ( parts[0].equals ( "create" ) ) - { - try - { - final int partitions = Integer.parseInt ( parts[2] ); - final int replicas = Integer.parseInt ( parts[3] ); - - tm.createTopic ( parts[1], "", partitions, replicas ); - } - catch ( HttpException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("HttpException: ", e); - } - catch ( IOException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("IOException: ", e); - } - catch ( NumberFormatException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("NumberFormatException: ", e); - } - } - else if ( parts[0].equals ( "grant" ) ) - { - try - { - if ( parts[1].equals ( "write" ) ) - { - tm.allowProducer ( parts[2], parts[3] ); - } - else if ( parts[1].equals ( "read" ) ) - { - tm.allowConsumer ( parts[2], parts[3] ); - } - } - catch ( HttpException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("HttpException: ", e); - } - catch ( IOException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("IOException: ", e); - } - } - else if ( parts[0].equals ( "revoke" ) ) - { - try - { - if ( parts[1].equals ( "write" ) ) - { - tm.revokeProducer ( parts[2], parts[3] ); - } - else if ( parts[1].equals ( "read" ) ) - { - tm.revokeConsumer ( parts[2], parts[3] ); - } - } - catch ( HttpException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("HttpException: ", e); - } - catch ( IOException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("IOException: ", e); - } - } - } - finally - { - tm.close (); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "topic list" ); - out.println ( "topic list " ); - out.println ( "topic create " ); - out.println ( "topic grant write|read " ); - out.println ( "topic revoke write|read " ); - } - -} diff --git a/src/main/java/com/att/nsa/mr/tools/TraceCommand.java b/src/main/java/com/att/nsa/mr/tools/TraceCommand.java deleted file mode 100644 index 0489172..0000000 --- a/src/main/java/com/att/nsa/mr/tools/TraceCommand.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.io.PrintStream; -import java.net.URI; -import java.util.List; -import java.util.Map; - -import com.att.nsa.apiClient.http.HttpTracer; -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; - -public class TraceCommand implements Command -{ - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, MRCommandContext context, final PrintStream out ) throws CommandNotReadyException - { - if ( parts[0].equalsIgnoreCase ( "on" )) - { - context.useTracer ( new HttpTracer () - { - @Override - public void outbound ( URI uri, Map> headers, String method, byte[] entity ) - { - out.println ( kLineBreak ); - out.println ( ">>> " + method + " " + uri.toString() ); - for ( Map.Entry> e : headers.entrySet () ) - { - final StringBuffer vals = new StringBuffer (); - for ( String val : e.getValue () ) - { - if ( vals.length () > 0 ) vals.append ( ", " ); - vals.append ( val ); - } - out.println ( ">>> " + e.getKey () + ": " + vals.toString() ); - } - if ( entity != null ) - { - out.println (); - out.println ( new String ( entity ) ); - } - out.println ( kLineBreak ); - } - - @Override - public void inbound ( Map> headers, int statusCode, String responseLine, byte[] entity ) - { - out.println ( kLineBreak ); - out.println ( "<<< " + responseLine ); - for ( Map.Entry> e : headers.entrySet () ) - { - final StringBuffer vals = new StringBuffer (); - for ( String val : e.getValue () ) - { - if ( vals.length () > 0 ) vals.append ( ", " ); - vals.append ( val ); - } - out.println ( "<<< " + e.getKey () + ": " + vals.toString() ); - } - if ( entity != null ) - { - out.println (); - out.println ( new String ( entity ) ); - } - out.println ( kLineBreak ); - } - } ); - } - else - { - context.noTracer (); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "trace on|off" ); - out.println ( "\tWhen trace is on, HTTP interaction is printed to the console." ); - } - - @Override - public String[] getMatches () - { - return new String[] - { - "trace (on)", - "trace (off)" - }; - } - - private static final String kLineBreak = "======================================================================"; -} diff --git a/src/main/java/com/att/nsa/mr/tools/ValidatorUtil.java b/src/main/java/com/att/nsa/mr/tools/ValidatorUtil.java deleted file mode 100644 index 0539582..0000000 --- a/src/main/java/com/att/nsa/mr/tools/ValidatorUtil.java +++ /dev/null @@ -1,174 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.tools; - -import java.util.Properties; - -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; - -public class ValidatorUtil { - - public static void validatePublisher(Properties props) { - String transportType = props.getProperty("TransportType"); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(transportType)) { - validateForDME2(props); - } else { - validateForNonDME2(props); - } - String maxBatchSize = props.getProperty("maxBatchSize"); - if (maxBatchSize == null || maxBatchSize.isEmpty()) { - throw new IllegalArgumentException ( "maxBatchSize is needed" ); - } - String maxAgeMs = props.getProperty("maxAgeMs"); - if (maxAgeMs == null || maxAgeMs.isEmpty()) { - throw new IllegalArgumentException ( "maxAgeMs is needed" ); - } - String messageSentThreadOccurance = props.getProperty("MessageSentThreadOccurance"); - if (messageSentThreadOccurance == null || messageSentThreadOccurance.isEmpty()) { - throw new IllegalArgumentException ( "MessageSentThreadOccurance is needed" ); - } - - } - - public static void validateSubscriber(Properties props) { - String transportType = props.getProperty("TransportType"); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(transportType)) { - validateForDME2(props); - } else { - validateForNonDME2(props); - } - String group = props.getProperty("group"); - if (group == null || group.isEmpty()) { - throw new IllegalArgumentException ( "group is needed" ); - } - String id = props.getProperty("id"); - if (id == null || id.isEmpty()) { - throw new IllegalArgumentException ( "Consumer (Id) is needed" ); - } - } - - private static void validateForDME2(Properties props) { - String serviceName = props.getProperty("ServiceName"); - if (serviceName == null || serviceName.isEmpty()) { - throw new IllegalArgumentException ( "Servicename is needed" ); - } - String topic = props.getProperty("topic"); - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException ( "topic is needed" ); - } - String username = props.getProperty("username"); - if (username == null || username.isEmpty()) { - throw new IllegalArgumentException ( "username is needed" ); - } - String password = props.getProperty("password"); - if (password == null || password.isEmpty()) { - throw new IllegalArgumentException ( "password is needed" ); - } - String dME2preferredRouterFilePath = props.getProperty("DME2preferredRouterFilePath"); - if (dME2preferredRouterFilePath == null || dME2preferredRouterFilePath.isEmpty()) { - throw new IllegalArgumentException ( "DME2preferredRouterFilePath is needed" ); - } - String partner = props.getProperty("Partner"); - String routeOffer = props.getProperty("routeOffer"); - if ((partner == null || partner.isEmpty()) && (routeOffer == null || routeOffer.isEmpty())) { - throw new IllegalArgumentException ( "Partner or routeOffer is needed" ); - } - String protocol = props.getProperty("Protocol"); - if (protocol == null || protocol.isEmpty()) { - throw new IllegalArgumentException ( "Protocol is needed" ); - } - String methodType = props.getProperty("MethodType"); - if (methodType == null || methodType.isEmpty()) { - throw new IllegalArgumentException ( "MethodType is needed" ); - } - String contenttype = props.getProperty("contenttype"); - if (contenttype == null || contenttype.isEmpty()) { - throw new IllegalArgumentException ( "contenttype is needed" ); - } - String latitude = props.getProperty("Latitude"); - if (latitude == null || latitude.isEmpty()) { - throw new IllegalArgumentException ( "Latitude is needed" ); - } - String longitude = props.getProperty("Longitude"); - if (longitude == null || longitude.isEmpty()) { - throw new IllegalArgumentException ( "Longitude is needed" ); - } - String aftEnv = props.getProperty("AFT_ENVIRONMENT"); - if (aftEnv == null || aftEnv.isEmpty()) { - throw new IllegalArgumentException ( "AFT_ENVIRONMENT is needed" ); - } - String version = props.getProperty("Version"); - if (version == null || version.isEmpty()) { - throw new IllegalArgumentException ( "Version is needed" ); - } - String environment = props.getProperty("Environment"); - if (environment == null || environment.isEmpty()) { - throw new IllegalArgumentException ( "Environment is needed" ); - } - String subContextPath = props.getProperty("SubContextPath"); - if (subContextPath == null || subContextPath.isEmpty()) { - throw new IllegalArgumentException ( "SubContextPath is needed" ); - } - String sessionstickinessrequired = props.getProperty("sessionstickinessrequired"); - if (sessionstickinessrequired == null || sessionstickinessrequired.isEmpty()) { - throw new IllegalArgumentException ( "sessionstickinessrequired is needed" ); - } - } - - private static void validateForNonDME2(Properties props) { - String transportType = props.getProperty("TransportType"); - String host = props.getProperty("host"); - if (host == null || host.isEmpty()) { - throw new IllegalArgumentException ( "Servicename is needed" ); - } - String topic = props.getProperty("topic"); - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException ( "topic is needed" ); - } - String contenttype = props.getProperty("contenttype"); - if (contenttype == null || contenttype.isEmpty()) { - throw new IllegalArgumentException ( "contenttype is needed" ); - } - if (!ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(transportType)){ - String username = props.getProperty("username"); - if (username == null || username.isEmpty()) { - throw new IllegalArgumentException ( "username is needed" ); - } - String password = props.getProperty("password"); - if (password == null || password.isEmpty()) { - throw new IllegalArgumentException ( "password is needed" ); - } - } - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(transportType)) { - String authKey = props.getProperty("authKey"); - if (authKey == null || authKey.isEmpty()) { - throw new IllegalArgumentException ( "authKey is needed" ); - } - String authDate = props.getProperty("authDate"); - if (authDate == null || authDate.isEmpty()) { - throw new IllegalArgumentException ( "authDate is needed" ); - } - - } - } - -} diff --git a/src/main/java/org/onap/dmaap/mr/client/HostSelector.java b/src/main/java/org/onap/dmaap/mr/client/HostSelector.java new file mode 100644 index 0000000..9bd73f9 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/HostSelector.java @@ -0,0 +1,198 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Random; +import java.util.Set; +import java.util.TreeSet; +import java.util.Vector; +import java.util.concurrent.DelayQueue; +import java.util.concurrent.Delayed; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HostSelector +{ + private final TreeSet fBaseHosts; + private final DelayQueue fBlacklist; + private String fIdealHost; + private String fCurrentHost; + private static final Logger log = LoggerFactory.getLogger(HostSelector.class); + + public HostSelector(String hostPart) + { + this(makeSet(hostPart), null); + } + + public HostSelector(Collection baseHosts) + { + this(baseHosts, null); + } + + public HostSelector(Collection baseHosts, String signature) + { + if (baseHosts.isEmpty()) + { + throw new IllegalArgumentException("At least one host must be provided."); + } + + this.fBaseHosts = new TreeSet(baseHosts); + this.fBlacklist = new DelayQueue(); + this.fIdealHost = null; + + if (signature == null) { + return; + } + int index = 0 ; + int value = signature.hashCode(); + if(value!=0) { + index = Math.abs(value) % baseHosts.size(); + } + Iterator it = this.fBaseHosts.iterator(); + while (index-- > 0) + { + it.next(); + } + this.fIdealHost = ((String)it.next()); + } + + public String selectBaseHost() + { + if (this.fCurrentHost == null) + { + makeSelection(); + } + return this.fCurrentHost; + } + + public void reportReachabilityProblem(long blacklistUnit, TimeUnit blacklistTimeUnit) + { + if (this.fCurrentHost == null) + { + log.warn("Reporting reachability problem, but no host is currently selected."); + } + + if (blacklistUnit > 0L) + { + for (BlacklistEntry be : this.fBlacklist) + { + if (be.getHost().equals(this.fCurrentHost)) + { + be.expireNow(); + } + } + + LinkedList devNull = new LinkedList(); + this.fBlacklist.drainTo(devNull); + + if (this.fCurrentHost != null) + { + this.fBlacklist.add(new BlacklistEntry(this.fCurrentHost, TimeUnit.MILLISECONDS.convert(blacklistUnit, blacklistTimeUnit))); + } + } + this.fCurrentHost = null; + } + + private String makeSelection() + { + TreeSet workingSet = new TreeSet(this.fBaseHosts); + + LinkedList devNull = new LinkedList(); + this.fBlacklist.drainTo(devNull); + for (BlacklistEntry be : this.fBlacklist) + { + workingSet.remove(be.getHost()); + } + + if (workingSet.isEmpty()) + { + log.warn("All hosts were blacklisted; reverting to full set of hosts."); + workingSet.addAll(this.fBaseHosts); + this.fCurrentHost = null; + } + + String selection = null; + if ((this.fCurrentHost != null) && (workingSet.contains(this.fCurrentHost))) + { + selection = this.fCurrentHost; + } + else if ((this.fIdealHost != null) && (workingSet.contains(this.fIdealHost))) + { + selection = this.fIdealHost; + } + else + { + int index = 0; + int value = new Random().nextInt(); + Vector v = new Vector(workingSet); + if(value!=0) { + index = Math.abs(value) % workingSet.size(); + } + selection = (String)v.elementAt(index); + } + + this.fCurrentHost = selection; + return this.fCurrentHost; + } + + private static Set makeSet(String s) + { + TreeSet set = new TreeSet(); + set.add(s); + return set; } + + private static class BlacklistEntry implements Delayed { + private final String fHost; + private long fExpireAtMs; + + public BlacklistEntry(String host, long delayMs) { + this.fHost = host; + this.fExpireAtMs = (System.currentTimeMillis() + delayMs); + } + + public void expireNow() + { + this.fExpireAtMs = 0L; + } + + public String getHost() + { + return this.fHost; + } + + public int compareTo(Delayed o) + { + Long thisDelay = Long.valueOf(getDelay(TimeUnit.MILLISECONDS)); + return thisDelay.compareTo(Long.valueOf(o.getDelay(TimeUnit.MILLISECONDS))); + } + + public long getDelay(TimeUnit unit) + { + long remainingMs = this.fExpireAtMs - System.currentTimeMillis(); + return unit.convert(remainingMs, TimeUnit.MILLISECONDS); + } + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java b/src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java new file mode 100644 index 0000000..df440bb --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; + +/** + * A MR batching publisher is a publisher with additional functionality + * for managing delayed sends. + * + * @author author + * + */ +public interface MRBatchingPublisher extends MRPublisher +{ + /** + * Get the number of messages that have not yet been sent. + * @return the number of pending messages + */ + int getPendingMessageCount (); + + /** + * Close this publisher, sending any remaining messages. + * @param timeout an amount of time to wait for unsent messages to be sent + * @param timeoutUnits the time unit for the timeout arg + * @return a list of any unsent messages after the timeout + * @throws IOException exception + * @throws InterruptedException exception + */ + List close ( long timeout, TimeUnit timeoutUnits ) throws IOException, InterruptedException; + + MRPublisherResponse sendBatchWithResponse (); +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRClient.java b/src/main/java/org/onap/dmaap/mr/client/MRClient.java new file mode 100644 index 0000000..8cbf9e0 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRClient.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import org.slf4j.Logger; + + +public interface MRClient +{ + /** + * An exception at the MR layer. This is used when the HTTP transport + * layer returns a success code but the transaction is not completed as expected. + */ + public class MRApiException extends Exception + { + private static final long serialVersionUID = 1L; + public MRApiException ( String msg ) { super ( msg ); } + public MRApiException ( String msg, Throwable t ) { super ( msg, t ); } + } + + /** + * Optionally set the Logger to use + * @param log log + */ + void logTo ( Logger log ); + + /** + * Set the API credentials for this client connection. Subsequent calls will + * include authentication headers.who i + */ + /** + * @param apiKey apikey + * @param apiSecret apisec + */ + void setApiCredentials ( String apiKey, String apiSecret ); + + /** + * Remove API credentials, if any, on this connection. Subsequent calls will not include + * authentication headers. + */ + void clearApiCredentials (); + + /** + * Close this connection. Some client interfaces have additional close capability. + */ + void close (); +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java b/src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java new file mode 100644 index 0000000..60e0666 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java @@ -0,0 +1,449 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.net.MalformedURLException; +import java.util.Collection; +import java.util.TreeSet; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.dmaap.mr.client.impl.MRConsumerImpl; +import org.onap.dmaap.mr.client.impl.MRMetaClient; +import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; + +/** + * A collection of builders for various types of MR API clients + * + * @author author + */ +public class MRClientBuilders +{ + + /** + * Instantiates MRClientBuilders. + */ + private MRClientBuilders() { + // prevent instantiation + } + + /** + * A builder for a topic Consumer + * @author author + */ + public static class ConsumerBuilder + { + /** + * Construct a consumer builder. + */ + public ConsumerBuilder () {} + + /** + * Set the host list + * @param hostList a comma-separated list of hosts to use to connect to MR + * @return this builder + */ + public ConsumerBuilder usingHosts ( String hostList ) { + return usingHosts ( MRConsumerImpl.stringToList(hostList) ); + } + + /** + * Set the host list + * @param hostSet a set of hosts to use to connect to MR + * @return this builder + */ + public ConsumerBuilder usingHosts ( Collection hostSet ) { + fHosts = hostSet; return this; + } + + /** + * Set the topic + * @param topic the name of the topic to consume + * @return this builder + */ + public ConsumerBuilder onTopic ( String topic ) { + fTopic=topic; + return this; + } + + /** + * Set the consumer's group and ID + * @param consumerGroup The name of the consumer group this consumer is part of + * @param consumerId The unique id of this consumer in its group + * @return this builder + */ + public ConsumerBuilder knownAs ( String consumerGroup, String consumerId ) { + fGroup = consumerGroup; + fId = consumerId; + return this; + } + + /** + * Set the API key and secret for this client. + * @param apiKey + * @param apiSecret + * @return this builder + */ + public ConsumerBuilder authenticatedBy ( String apiKey, String apiSecret ) { + fApiKey = apiKey; + fApiSecret = apiSecret; + return this; + } + + /** + * Set the server side timeout + * @param timeoutMs The amount of time in milliseconds that the server should keep the connection open while waiting for message traffic. + * @return this builder + */ + public ConsumerBuilder waitAtServer ( int timeoutMs ) { + fTimeoutMs = timeoutMs; + return this; + }; + + /** + * Set the maximum number of messages to receive per transaction + * @param limit The maximum number of messages to receive from the server in one transaction. + * @return this builder + */ + public ConsumerBuilder receivingAtMost ( int limit ) { + fLimit = limit; + return this; + }; + + /** + * Set a filter to use on the server + * @param filter a Highland Park standard library filter encoded in JSON + * @return this builder + */ + public ConsumerBuilder withServerSideFilter ( String filter ) { + fFilter = filter; + return this; + } + + /** + * Build the consumer + * @return a consumer + */ + public MRConsumer build () + { + if ( fHosts == null || fHosts.size() == 0 || fTopic == null ) + { + throw new IllegalArgumentException ( "You must provide at least one host and a topic name." ); + } + + if ( fGroup == null ) + { + fGroup = UUID.randomUUID ().toString (); + fId = "0"; + log.info ( "Creating non-restartable client with group " + fGroup + " and ID " + fId + "." ); + } + + if ( sfConsumerMock != null ) return sfConsumerMock; + try { + return new MRConsumerImpl ( fHosts, fTopic, fGroup, fId, fTimeoutMs, fLimit, fFilter, fApiKey, fApiSecret ); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } + + private Collection fHosts = null; + private String fTopic = null; + private String fGroup = null; + private String fId = null; + private String fApiKey = null; + private String fApiSecret = null; + private int fTimeoutMs = -1; + private int fLimit = -1; + private String fFilter = null; + } + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + /** + * A publisher builder + * @author author + */ + public static class PublisherBuilder + { + public PublisherBuilder () {} + + /** + * Set the MR/UEB host(s) to use + * @param hostlist The host(s) used in the URL to MR. Can be "host:port", can be multiple comma-separated entries. + * @return this builder + */ + public PublisherBuilder usingHosts ( String hostlist ) { + return usingHosts ( MRConsumerImpl.stringToList(hostlist) ); + } + + /** + * Set the MR/UEB host(s) to use + * @param hostSet The host(s) used in the URL to MR. Can be "host:port" + * @return this builder + */ + public PublisherBuilder usingHosts ( String[] hostSet ) + { + final TreeSet hosts = new TreeSet (); + for ( String hp : hostSet ) + { + hosts.add ( hp ); + } + return usingHosts ( hosts ); + } + + /** + * Set the MR/UEB host(s) to use + * @param hostlist The host(s) used in the URL to MR. Can be "host:port". + * @return this builder + */ + public PublisherBuilder usingHosts ( Collection hostlist ) { + fHosts=hostlist; + return this; + } + + /** + * Set the topic to publish on + * @param topic The topic on which to publish messages. + * @return this builder + */ + public PublisherBuilder onTopic ( String topic ) { + fTopic = topic; + return this; + } + + /** + * Batch message sends with the given limits. + * @param messageCount The largest set of messages to batch. + * @param ageInMs The maximum age of a message waiting in a batch. + * @return this builder + */ + public PublisherBuilder limitBatch ( int messageCount, int ageInMs ) { + fMaxBatchSize = messageCount; + fMaxBatchAgeMs = ageInMs; + return this; + } + + /** + * Compress transactions + * @return this builder + */ + public PublisherBuilder withCompresion () { + return enableCompresion(true); + } + + /** + * Do not compress transactions + * @return this builder + */ + public PublisherBuilder withoutCompresion () { + return enableCompresion(false); + } + + /** + * Set the compression option + * @param compress true to gzip compress transactions + * @return this builder + */ + public PublisherBuilder enableCompresion ( boolean compress ) { + fCompress = compress; + return this; + } + + /** + * Set the API key and secret for this client. + * @param apiKey + * @param apiSecret + * @return this builder + */ + public PublisherBuilder authenticatedBy ( String apiKey, String apiSecret ) { + fApiKey = apiKey; + fApiSecret = apiSecret; + return this; + } + + /** + * Build the publisher + * @return a batching publisher + */ + public MRBatchingPublisher build () + { + if ( fHosts == null || fHosts.isEmpty() || fTopic == null ) + { + throw new IllegalArgumentException ( "You must provide at least one host and a topic name." ); + } + + if ( sfPublisherMock != null ) return sfPublisherMock; + + final MRSimplerBatchPublisher pub = new MRSimplerBatchPublisher.Builder (). + againstUrls ( fHosts ). + onTopic ( fTopic ). + batchTo ( fMaxBatchSize, fMaxBatchAgeMs ). + compress ( fCompress ). + build (); + if ( fApiKey != null ) + { + pub.setApiCredentials ( fApiKey, fApiSecret ); + } + return pub; + } + + private Collection fHosts = null; + private String fTopic = null; + private int fMaxBatchSize = 1; + private int fMaxBatchAgeMs = 1; + private boolean fCompress = false; + private String fApiKey = null; + private String fApiSecret = null; + } + + /** + * A builder for an identity manager + * @author author + */ + public static class IdentityManagerBuilder extends AbstractAuthenticatedManagerBuilder + { + /** + * Construct an identity manager builder. + */ + public IdentityManagerBuilder () {} + + @Override + protected MRIdentityManager constructClient ( Collection hosts ) { try { + return new MRMetaClient ( hosts ); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } } + } + + /** + * A builder for a topic manager + * @author author + */ + public static class TopicManagerBuilder extends AbstractAuthenticatedManagerBuilder + { + /** + * Construct an topic manager builder. + */ + public TopicManagerBuilder () {} + + @Override + protected MRTopicManager constructClient ( Collection hosts ) { try { + return new MRMetaClient ( hosts ); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } } + } + + /** + * Inject a consumer. Used to support unit tests. + * @param cc + */ + public static void $testInject ( MRConsumer cc ) + { + sfConsumerMock = cc; + } + + /** + * Inject a publisher. Used to support unit tests. + * @param pub + */ + public static void $testInject ( MRBatchingPublisher pub ) + { + sfPublisherMock = pub; + } + + static MRConsumer sfConsumerMock = null; + static MRBatchingPublisher sfPublisherMock = null; + + /** + * A builder for an identity manager + * @author author + */ + public static abstract class AbstractAuthenticatedManagerBuilder + { + /** + * Construct an identity manager builder. + */ + public AbstractAuthenticatedManagerBuilder () {} + + /** + * Set the host list + * @param hostList a comma-separated list of hosts to use to connect to MR + * @return this builder + */ + public AbstractAuthenticatedManagerBuilder usingHosts ( String hostList ) { + return usingHosts ( MRConsumerImpl.stringToList(hostList) ); + } + + /** + * Set the host list + * @param hostSet a set of hosts to use to connect to MR + * @return this builder + */ + public AbstractAuthenticatedManagerBuilder usingHosts ( Collection hostSet ) { + fHosts = hostSet; + return this; + } + + /** + * Set the API key and secret for this client. + * @param apiKey + * @param apiSecret + * @return this builder + */ + public AbstractAuthenticatedManagerBuilder authenticatedBy ( String apiKey, String apiSecret ) { + fApiKey = apiKey; + fApiSecret = apiSecret; + return this; + } + + /** + * Build the consumer + * @return a consumer + */ + public T build () + { + if ( fHosts.isEmpty() ) + { + throw new IllegalArgumentException ( "You must provide at least one host and a topic name." ); + } + + final T mgr = constructClient ( fHosts ); + mgr.setApiCredentials ( fApiKey, fApiSecret ); + return mgr; + } + + protected abstract T constructClient ( Collection hosts ); + + private Collection fHosts = null; + private String fApiKey = null; + private String fApiSecret = null; + } + + private static final Logger log = LoggerFactory.getLogger ( MRClientBuilders.class ); +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java b/src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java new file mode 100644 index 0000000..dc9d555 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java @@ -0,0 +1,691 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.Collection; +import java.util.Map; +import java.util.Properties; +import java.util.TreeSet; +import java.util.UUID; + +import javax.ws.rs.core.MultivaluedMap; + +import org.onap.dmaap.mr.client.impl.MRConsumerImpl; +import org.onap.dmaap.mr.client.impl.MRMetaClient; +import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; +import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import org.onap.dmaap.mr.tools.ValidatorUtil; + +/** + * A factory for MR clients.
+ *
+ * Use caution selecting a consumer creator factory. If the call doesn't accept + * a consumer group name, then it creates a consumer that is not restartable. + * That is, if you stop your process and start it again, your client will NOT + * receive any missed messages on the topic. If you need to ensure receipt of + * missed messages, then you must use a consumer that's created with a group + * name and ID. (If you create multiple consumer processes using the same group, + * load is split across them. Be sure to use a different ID for each + * instance.)
+ *
+ * Publishers + * + * @author author + */ +public class MRClientFactory { + private static final String AUTH_KEY = "authKey"; + private static final String AUTH_DATE = "authDate"; + private static final String PASSWORD = "password"; + private static final String USERNAME = "username"; + private static final String DME2PREFERRED_ROUTER_FILE_PATH = "DME2preferredRouterFilePath"; + private static final String TOPIC = "topic"; + private static final String TRANSPORT_TYPE = "TransportType"; + public static MultivaluedMap HTTPHeadersMap; + public static Map DME2HeadersMap; + public static String routeFilePath; + + public static FileReader routeReader; + + public static FileWriter routeWriter = null; + public static Properties prop = null; + + /** + * Instantiates MRClientFactory. + */ + private MRClientFactory() { + //prevents instantiation. + } + + /** + * Create a consumer instance with the default timeout and no limit on + * messages returned. This consumer operates as an independent consumer + * (i.e., not in a group) and is NOT re-startable across sessions. + * + * @param hostList + * A comma separated list of hosts to use to connect to MR. You + * can include port numbers (3904 is the default). For example, + * "hostname:8080," + * + * @param topic + * The topic to consume + * + * @return a consumer + */ + public static MRConsumer createConsumer(String hostList, String topic) { + return createConsumer(MRConsumerImpl.stringToList(hostList), topic); + } + + /** + * Create a consumer instance with the default timeout and no limit on + * messages returned. This consumer operates as an independent consumer + * (i.e., not in a group) and is NOT re-startable across sessions. + * + * @param hostSet + * The host used in the URL to MR. Entries can be "host:port". + * @param topic + * The topic to consume + * + * @return a consumer + */ + public static MRConsumer createConsumer(Collection hostSet, String topic) { + return createConsumer(hostSet, topic, null); + } + + /** + * Create a consumer instance with server-side filtering, the default + * timeout, and no limit on messages returned. This consumer operates as an + * independent consumer (i.e., not in a group) and is NOT re-startable + * across sessions. + * + * @param hostSet + * The host used in the URL to MR. Entries can be "host:port". + * @param topic + * The topic to consume + * @param filter + * a filter to use on the server side + * + * @return a consumer + */ + public static MRConsumer createConsumer(Collection hostSet, String topic, String filter) { + return createConsumer(hostSet, topic, UUID.randomUUID().toString(), "0", -1, -1, filter, null, null); + } + + /** + * Create a consumer instance with the default timeout, and no limit on + * messages returned. This consumer can operate in a logical group and is + * re-startable across sessions when you use the same group and ID on + * restart. + * + * @param hostSet + * The host used in the URL to MR. Entries can be "host:port". + * @param topic + * The topic to consume + * @param consumerGroup + * The name of the consumer group this consumer is part of + * @param consumerId + * The unique id of this consume in its group + * + * @return a consumer + */ + public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, + final String consumerId) { + return createConsumer(hostSet, topic, consumerGroup, consumerId, -1, -1); + } + + /** + * Create a consumer instance with the default timeout, and no limit on + * messages returned. This consumer can operate in a logical group and is + * re-startable across sessions when you use the same group and ID on + * restart. + * + * @param hostSet + * The host used in the URL to MR. Entries can be "host:port". + * @param topic + * The topic to consume + * @param consumerGroup + * The name of the consumer group this consumer is part of + * @param consumerId + * The unique id of this consume in its group + * @param timeoutMs + * The amount of time in milliseconds that the server should keep + * the connection open while waiting for message traffic. Use -1 + * for default timeout. + * @param limit + * A limit on the number of messages returned in a single call. + * Use -1 for no limit. + * + * @return a consumer + */ + public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, + final String consumerId, int timeoutMs, int limit) { + return createConsumer(hostSet, topic, consumerGroup, consumerId, timeoutMs, limit, null, null, null); + } + + /** + * Create a consumer instance with the default timeout, and no limit on + * messages returned. This consumer can operate in a logical group and is + * re-startable across sessions when you use the same group and ID on + * restart. This consumer also uses server-side filtering. + * + * @param hostList + * A comma separated list of hosts to use to connect to MR. You + * can include port numbers (3904 is the default). For example, + * "ueb01hydc.it.att.com:8080,ueb02hydc.it.att.com" + * @param topic + * The topic to consume + * @param consumerGroup + * The name of the consumer group this consumer is part of + * @param consumerId + * The unique id of this consume in its group + * @param timeoutMs + * The amount of time in milliseconds that the server should keep + * the connection open while waiting for message traffic. Use -1 + * for default timeout. + * @param limit + * A limit on the number of messages returned in a single call. + * Use -1 for no limit. + * @param filter + * A Highland Park filter expression using only built-in filter + * components. Use null for "no filter". + * + * @return a consumer + */ + public static MRConsumer createConsumer(String hostList, final String topic, final String consumerGroup, + final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { + return createConsumer(MRConsumerImpl.stringToList(hostList), topic, consumerGroup, consumerId, timeoutMs, limit, + filter, apiKey, apiSecret); + } + + /** + * Create a consumer instance with the default timeout, and no limit on + * messages returned. This consumer can operate in a logical group and is + * re-startable across sessions when you use the same group and ID on + * restart. This consumer also uses server-side filtering. + * + * @param hostSet + * The host used in the URL to MR. Entries can be "host:port". + * @param topic + * The topic to consume + * @param consumerGroup + * The name of the consumer group this consumer is part of + * @param consumerId + * The unique id of this consume in its group + * @param timeoutMs + * The amount of time in milliseconds that the server should keep + * the connection open while waiting for message traffic. Use -1 + * for default timeout. + * @param limit + * A limit on the number of messages returned in a single call. + * Use -1 for no limit. + * @param filter + * A Highland Park filter expression using only built-in filter + * components. Use null for "no filter". + * + * @return a consumer + */ + public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, + final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { + if (MRClientBuilders.sfConsumerMock != null) + return MRClientBuilders.sfConsumerMock; + try { + return new MRConsumerImpl(hostSet, topic, consumerGroup, consumerId, timeoutMs, limit, filter, apiKey, + apiSecret); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + /** + * Create a publisher that sends each message (or group of messages) + * immediately. Most applications should favor higher latency for much + * higher message throughput and the "simple publisher" is not a good + * choice. + * + * @param hostlist + * The host used in the URL to MR. Can be "host:port", can be + * multiple comma-separated entries. + * @param topic + * The topic on which to publish messages. + * @return a publisher + */ + public static MRBatchingPublisher createSimplePublisher(String hostlist, String topic) { + return createBatchingPublisher(hostlist, topic, 1, 1); + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown. Message payloads are + * not compressed. + * + * @param hostlist + * The host used in the URL to MR. Can be "host:port", can be + * multiple comma-separated entries. + * @param topic + * The topic on which to publish messages. + * @param maxBatchSize + * The largest set of messages to batch + * @param maxAgeMs + * The maximum age of a message waiting in a batch + * + * @return a publisher + */ + public static MRBatchingPublisher createBatchingPublisher(String hostlist, String topic, int maxBatchSize, + long maxAgeMs) { + return createBatchingPublisher(hostlist, topic, maxBatchSize, maxAgeMs, false); + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown. + * + * @param hostlist + * The host used in the URL to MR. Can be "host:port", can be + * multiple comma-separated entries. + * @param topic + * The topic on which to publish messages. + * @param maxBatchSize + * The largest set of messages to batch + * @param maxAgeMs + * The maximum age of a message waiting in a batch + * @param compress + * use gzip compression + * + * @return a publisher + */ + public static MRBatchingPublisher createBatchingPublisher(String hostlist, String topic, int maxBatchSize, + long maxAgeMs, boolean compress) { + return createBatchingPublisher(MRConsumerImpl.stringToList(hostlist), topic, maxBatchSize, maxAgeMs, compress); + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown. + * + * @param hostSet + * A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param topic + * The topic on which to publish messages. + * @param maxBatchSize + * The largest set of messages to batch + * @param maxAgeMs + * The maximum age of a message waiting in a batch + * @param compress + * use gzip compression + * + * @return a publisher + */ + public static MRBatchingPublisher createBatchingPublisher(String[] hostSet, String topic, int maxBatchSize, + long maxAgeMs, boolean compress) { + final TreeSet hosts = new TreeSet(); + for (String hp : hostSet) { + hosts.add(hp); + } + return createBatchingPublisher(hosts, topic, maxBatchSize, maxAgeMs, compress); + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown. + * + * @param hostSet + * A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param topic + * The topic on which to publish messages. + * @param maxBatchSize + * The largest set of messages to batch + * @param maxAgeMs + * The maximum age of a message waiting in a batch + * @param compress + * use gzip compression + * + * @return a publisher + */ + public static MRBatchingPublisher createBatchingPublisher(Collection hostSet, String topic, + int maxBatchSize, long maxAgeMs, boolean compress) { + return new MRSimplerBatchPublisher.Builder().againstUrls(hostSet).onTopic(topic).batchTo(maxBatchSize, maxAgeMs) + .compress(compress).build(); + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown. + * + * @param host + * A host to be used in the URL to MR. Can be "host:port". Use + * multiple entries to enable failover. + * @param topic + * The topic on which to publish messages. + * @param username + * username + * @param password + * password + * @param maxBatchSize + * The largest set of messages to batch + * @param maxAgeMs + * The maximum age of a message waiting in a batch + * @param compress + * use gzip compression + * @param protocolFlag + * http auth or ueb auth or dme2 method + * @param producerFilePath + * all properties for publisher + * @return MRBatchingPublisher obj + */ + public static MRBatchingPublisher createBatchingPublisher(String host, String topic, final String username, + final String password, int maxBatchSize, long maxAgeMs, boolean compress, String protocolFlag) { + MRSimplerBatchPublisher pub = new MRSimplerBatchPublisher.Builder() + .againstUrls(MRConsumerImpl.stringToList(host)).onTopic(topic).batchTo(maxBatchSize, maxAgeMs) + .compress(compress).build(); + + pub.setHost(host); + pub.setUsername(username); + pub.setPassword(password); + pub.setProtocolFlag(protocolFlag); + return pub; + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown + * + * @param Properties + * props set all properties for publishing message + * @return MRBatchingPublisher obj + * @throws FileNotFoundException + * exc + * @throws IOException + * ioex + */ + public static MRBatchingPublisher createBatchingPublisher(Properties props, boolean withResponse) + throws FileNotFoundException, IOException { + return createInternalBatchingPublisher(props, withResponse); + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown + * + * @param Properties + * props set all properties for publishing message + * @return MRBatchingPublisher obj + * @throws FileNotFoundException + * exc + * @throws IOException + * ioex + */ + public static MRBatchingPublisher createBatchingPublisher(Properties props) + throws FileNotFoundException, IOException { + return createInternalBatchingPublisher(props, false); + } + + /** + * Create a publisher that batches messages. Be sure to close the publisher + * to send the last batch and ensure a clean shutdown + * + * @param producerFilePath + * set all properties for publishing message + * @return MRBatchingPublisher obj + * @throws FileNotFoundException + * exc + * @throws IOException + * ioex + */ + public static MRBatchingPublisher createBatchingPublisher(final String producerFilePath) + throws FileNotFoundException, IOException { + FileReader reader = new FileReader(new File(producerFilePath)); + Properties props = new Properties(); + props.load(reader); + return createBatchingPublisher(props); + } + + /** + * Create a publisher that will contain send methods that return response + * object to user. + * + * @param producerFilePath + * set all properties for publishing message + * @return MRBatchingPublisher obj + * @throws FileNotFoundException + * exc + * @throws IOException + * ioex + */ + public static MRBatchingPublisher createBatchingPublisher(final String producerFilePath, boolean withResponse) + throws FileNotFoundException, IOException { + FileReader reader = new FileReader(new File(producerFilePath)); + Properties props = new Properties(); + props.load(reader); + return createBatchingPublisher(props, withResponse); + } + + protected static MRBatchingPublisher createInternalBatchingPublisher(Properties props, boolean withResponse) + throws FileNotFoundException, IOException { + assert props != null; + MRSimplerBatchPublisher pub; + if (withResponse) { + pub = new MRSimplerBatchPublisher.Builder() + .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty("host")),MRConsumerImpl.stringToList(props.getProperty("ServiceName")), props.getProperty(TRANSPORT_TYPE)) + .onTopic(props.getProperty(TOPIC)) + .batchTo(Integer.parseInt(props.getProperty("maxBatchSize")), + Integer.parseInt(props.getProperty("maxAgeMs").toString())) + .compress(Boolean.parseBoolean(props.getProperty("compress"))) + .httpThreadTime(Integer.parseInt(props.getProperty("MessageSentThreadOccurance"))) + .withResponse(withResponse).build(); + } else { + pub = new MRSimplerBatchPublisher.Builder() + .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty("host")), MRConsumerImpl.stringToList(props.getProperty("ServiceName")), props.getProperty(TRANSPORT_TYPE)) + .onTopic(props.getProperty(TOPIC)) + .batchTo(Integer.parseInt(props.getProperty("maxBatchSize")), + Integer.parseInt(props.getProperty("maxAgeMs").toString())) + .compress(Boolean.parseBoolean(props.getProperty("compress"))) + .httpThreadTime(Integer.parseInt(props.getProperty("MessageSentThreadOccurance"))).build(); + } + pub.setHost(props.getProperty("host")); + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.AUTH_KEY.getValue())) { + + pub.setAuthKey(props.getProperty(AUTH_KEY)); + pub.setAuthDate(props.getProperty(AUTH_DATE)); + pub.setUsername(props.getProperty(USERNAME)); + pub.setPassword(props.getProperty(PASSWORD)); + } else { + pub.setUsername(props.getProperty(USERNAME)); + pub.setPassword(props.getProperty(PASSWORD)); + } + pub.setProtocolFlag(props.getProperty(TRANSPORT_TYPE)); + pub.setProps(props); + prop = new Properties(); + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.DME2.getValue())) { + routeFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH); + routeReader = new FileReader(new File(routeFilePath)); + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + } + return pub; + } + + /** + * Create an identity manager client to work with API keys. + * + * @param hostSet + * A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param apiKey + * Your API key + * @param apiSecret + * Your API secret + * @return an identity manager + */ + public static MRIdentityManager createIdentityManager(Collection hostSet, String apiKey, String apiSecret) { + MRIdentityManager cim; + try { + cim = new MRMetaClient(hostSet); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + cim.setApiCredentials(apiKey, apiSecret); + return cim; + } + + /** + * Create a topic manager for working with topics. + * + * @param hostSet + * A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param apiKey + * Your API key + * @param apiSecret + * Your API secret + * @return a topic manager + */ + public static MRTopicManager createTopicManager(Collection hostSet, String apiKey, String apiSecret) { + MRMetaClient tmi; + try { + tmi = new MRMetaClient(hostSet); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + tmi.setApiCredentials(apiKey, apiSecret); + return tmi; + } + + /** + * Inject a consumer. Used to support unit tests. + * + * @param cc + */ + public static void $testInject(MRConsumer cc) { + MRClientBuilders.sfConsumerMock = cc; + } + + public static MRConsumer createConsumer(String host, String topic, String username, String password, String group, + String id, int i, int j, String protocalFlag, String consumerFilePath) { + + MRConsumerImpl sub; + try { + sub = new MRConsumerImpl(MRConsumerImpl.stringToList(host), topic, group, id, i, j, null, null, null); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + sub.setUsername(username); + sub.setPassword(password); + sub.setHost(host); + sub.setProtocolFlag(protocalFlag); + sub.setConsumerFilePath(consumerFilePath); + return sub; + + } + + public static MRConsumer createConsumer(String host, String topic, String username, String password, String group, + String id, String protocalFlag, String consumerFilePath, int i, int j) { + + MRConsumerImpl sub; + try { + sub = new MRConsumerImpl(MRConsumerImpl.stringToList(host), topic, group, id, i, j, null, null, null); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + sub.setUsername(username); + sub.setPassword(password); + sub.setHost(host); + sub.setProtocolFlag(protocalFlag); + sub.setConsumerFilePath(consumerFilePath); + return sub; + + } + + public static MRConsumer createConsumer(String consumerFilePath) throws FileNotFoundException, IOException { + FileReader reader = new FileReader(new File(consumerFilePath)); + Properties props = new Properties(); + props.load(reader); + + return createConsumer(props); + } + + public static MRConsumer createConsumer(Properties props) throws FileNotFoundException, IOException { + int timeout; + ValidatorUtil.validateSubscriber(props); + if (props.getProperty("timeout") != null) + timeout = Integer.parseInt(props.getProperty("timeout")); + else + timeout = -1; + int limit; + if (props.getProperty("limit") != null) + limit = Integer.parseInt(props.getProperty("limit")); + else + limit = -1; + String group; + if (props.getProperty("group") == null) + group = UUID.randomUUID().toString(); + else + group = props.getProperty("group"); + MRConsumerImpl sub = null; + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.AUTH_KEY.getValue())) { + sub = new MRConsumerImpl(MRConsumerImpl.stringToList(props.getProperty("host")), props.getProperty(TOPIC), + group, props.getProperty("id"), timeout, limit, props.getProperty("filter"), + props.getProperty(AUTH_KEY), props.getProperty(AUTH_DATE)); + sub.setAuthKey(props.getProperty(AUTH_KEY)); + sub.setAuthDate(props.getProperty(AUTH_DATE)); + sub.setUsername(props.getProperty(USERNAME)); + sub.setPassword(props.getProperty(PASSWORD)); + } else { + sub = new MRConsumerImpl(MRConsumerImpl.stringToList(props.getProperty("host")), props.getProperty(TOPIC), + group, props.getProperty("id"), timeout, limit, props.getProperty("filter"), + props.getProperty(USERNAME), props.getProperty(PASSWORD)); + sub.setUsername(props.getProperty(USERNAME)); + sub.setPassword(props.getProperty(PASSWORD)); + } + + sub.setProps(props); + sub.setHost(props.getProperty("host")); + sub.setProtocolFlag(props.getProperty(TRANSPORT_TYPE)); + sub.setfFilter(props.getProperty("filter")); + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.DME2.getValue())) { + MRConsumerImpl.setRouterFilePath(props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH)); + routeFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH); + routeReader = new FileReader(new File(routeFilePath)); + prop = new Properties(); + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + } + + return sub; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRConsumer.java b/src/main/java/org/onap/dmaap/mr/client/MRConsumer.java new file mode 100644 index 0000000..b2f7563 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRConsumer.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.io.IOException; + +import org.onap.dmaap.mr.client.response.MRConsumerResponse; + +public interface MRConsumer extends MRClient +{ + /** + * Fetch a set of messages. The consumer's timeout and message limit are used if set in the constructor call. + + * @return a set of messages + * @throws IOException + */ + Iterable fetch () throws IOException, Exception; + + /** + * Fetch a set of messages with an explicit timeout and limit for this call. These values + * override any set in the constructor call. + * + * @param timeoutMs The amount of time in milliseconds that the server should keep the connection + * open while waiting for message traffic. Use -1 for default timeout (controlled on the server-side). + * @param limit A limit on the number of messages returned in a single call. Use -1 for no limit. + * @return a set messages + * @throws IOException if there's a problem connecting to the server + */ + Iterable fetch ( int timeoutMs, int limit ) throws IOException, Exception; + + MRConsumerResponse fetchWithReturnConsumerResponse (); + + + MRConsumerResponse fetchWithReturnConsumerResponse ( int timeoutMs, int limit ); +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java b/src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java new file mode 100644 index 0000000..1905f82 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.io.IOException; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; + +/** + * A client for manipulating API keys. + * @author author + * + */ +public interface MRIdentityManager extends MRClient +{ + /** + * An API Key record + */ + public interface ApiKey + { + /** + * Get the email address associated with the API key + * @return the email address on the API key or null + */ + String getEmail (); + + /** + * Get the description associated with the API key + * @return the description on the API key or null + */ + String getDescription (); + } + + /** + * Create a new API key on the UEB cluster. The returned credential instance + * contains the new API key and API secret. This is the only time the secret + * is available to the client -- there's no API for retrieving it later -- so + * your application must store it securely. + * + * @param email + * @param description + * @return a new credential + * @throws HttpException + * @throws MRApiException + * @throws IOException + */ + ApiCredential createApiKey ( String email, String description ) throws HttpException, MRApiException, IOException; + + /** + * Get basic info about a known API key + * @param apiKey + * @return the API key's info or null if it doesn't exist + * @throws HttpObjectNotFoundException, HttpException, MRApiException + * @throws IOException + */ + ApiKey getApiKey ( String apiKey ) throws HttpObjectNotFoundException, HttpException, MRApiException, IOException; + + /** + * Update the record for the API key used to authenticate this request. The UEB + * API requires that you authenticate with the same key you're updating, so the + * API key being changed is the one used for setApiCredentials. + * + * @param email use null to keep the current value + * @param description use null to keep the current value + * @throws IOException + * @throws HttpException + * @throws HttpObjectNotFoundException + */ + void updateCurrentApiKey ( String email, String description ) throws HttpObjectNotFoundException, HttpException, IOException; + + /** + * Delete the *current* API key. After this call returns, the API key + * used to authenticate will no longer be valid. + * + * @throws IOException + * @throws HttpException + */ + void deleteCurrentApiKey () throws HttpException, IOException; +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRPublisher.java b/src/main/java/org/onap/dmaap/mr/client/MRPublisher.java new file mode 100644 index 0000000..e900229 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRPublisher.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.io.IOException; +import java.util.Collection; + +/** + * A MR publishing interface. + * + */ +public interface MRPublisher extends MRClient +{ + /** + * A simple message container + */ + public static class message + { + public message ( String partition, String msg ) + { + fPartition = partition == null ? "" : partition; + fMsg = msg; + if ( fMsg == null ) + { + throw new IllegalArgumentException ( "Can't send a null message." ); + } + } + + public message ( message msg ) + { + this ( msg.fPartition, msg.fMsg ); + } + + public final String fPartition; + public final String fMsg; + } + + /** + * Send the given message without partition. partition will be placed at HTTP request level. + * @param msg message to sent + * @return the number of pending messages + * @throws IOException exception + */ + int send ( String msg ) throws IOException; + /** + * Send the given message using the given partition. + * @param partition partition + * @param msg message + * @return the number of pending messages + * @throws IOException exception + */ + int send ( String partition, String msg ) throws IOException; + + /** + * Send the given message using its partition. + * @param msg mesg + * @return the number of pending messages + * @throws IOException exp + */ + int send ( message msg ) throws IOException; + + /** + * Send the given messages using their partitions. + * @param msgs msg + * @return the number of pending messages + * @throws IOException exp + */ + int send ( Collection msgs ) throws IOException; + + /** + * Close this publisher. It's an error to call send() after close() + */ + void close (); +} diff --git a/src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java b/src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java new file mode 100644 index 0000000..54ca7ec --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java @@ -0,0 +1,183 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client; + +import java.io.IOException; +import java.util.Set; + +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; + + +/** + * A client for working with topic metadata. + * @author author + */ +public interface MRTopicManager extends MRClient +{ + /** + * Get the topics available in the cluster + * @return a set of topic names + * @throws IOException + */ + Set getTopics () throws IOException; + + /** + * Information about a topic. + */ + public interface TopicInfo + { + /** + * Get the owner of the topic + * @return the owner, or null if no entry + */ + String getOwner (); + + /** + * Get the description for this topic + * @return the description, or null if no entry + */ + String getDescription (); + + /** + * Get the set of allowed producers (as API keys) on this topic + * @return the set of allowed producers, null of no ACL exists/enabled + */ + Set getAllowedProducers (); + + /** + * Get the set of allowed consumers (as API keys) on this topic + * @return the set of allowed consumers, null of no ACL exists/enabled + */ + Set getAllowedConsumers (); + } + + /** + * Get information about a topic. + * @param topic + * @return topic information + * @throws IOException + * @throws HttpObjectNotFoundException + */ + TopicInfo getTopicMetadata ( String topic ) throws HttpObjectNotFoundException, IOException; + + /** + * Create a new topic. + * @param topicName + * @param topicDescription + * @param partitionCount + * @param replicationCount + * @throws HttpException + * @throws IOException + */ + void createTopic ( String topicName, String topicDescription, int partitionCount, int replicationCount ) throws HttpException, IOException; + + /** + * Delete the topic. This call must be authenticated and the API key listed as owner on the topic. + * NOTE: The MR (UEB) API server does not support topic deletion at this time (mid 2015) + * @param topic + * @throws HttpException + * @throws IOException + * @deprecated If/when the Kafka system supports topic delete, or the implementation changes, this will be restored. + */ + @Deprecated + void deleteTopic ( String topic ) throws HttpException, IOException; + + /** + * Can any client produce events into this topic without authentication? + * @param topic + * @return true if the topic is open for producing + * @throws IOException + * @throws HttpObjectNotFoundException + */ + boolean isOpenForProducing ( String topic ) throws HttpObjectNotFoundException, IOException; + + /** + * Get the set of allowed producers. If the topic is open, the result is null. + * @param topic + * @return a set of allowed producers or null + * @throws IOException + * @throws HttpObjectNotFoundException + */ + Set getAllowedProducers ( String topic ) throws HttpObjectNotFoundException, IOException; + + /** + * Allow the given API key to produce messages on the given topic. The caller must + * own this topic. + * @param topic + * @param apiKey + * @throws HttpException + * @throws HttpObjectNotFoundException + * @throws IOException + */ + void allowProducer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException; + + /** + * Revoke the given API key's authorization to produce messages on the given topic. + * The caller must own this topic. + * @param topic + * @param apiKey + * @throws HttpException + * @throws IOException + */ + void revokeProducer ( String topic, String apiKey ) throws HttpException, IOException; + + /** + * Can any client consume events from this topic without authentication? + * @param topic + * @return true if the topic is open for consuming + * @throws IOException + * @throws HttpObjectNotFoundException + */ + boolean isOpenForConsuming ( String topic ) throws HttpObjectNotFoundException, IOException; + + /** + * Get the set of allowed consumers. If the topic is open, the result is null. + * @param topic + * @return a set of allowed consumers or null + * @throws IOException + * @throws HttpObjectNotFoundException + */ + Set getAllowedConsumers ( String topic ) throws HttpObjectNotFoundException, IOException; + + /** + * Allow the given API key to consume messages on the given topic. The caller must + * own this topic. + * @param topic + * @param apiKey + * @throws HttpException + * @throws HttpObjectNotFoundException + * @throws IOException + */ + void allowConsumer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException; + + /** + * Revoke the given API key's authorization to consume messages on the given topic. + * The caller must own this topic. + * @param topic + * @param apiKey + * @throws HttpException + * @throws IOException + */ + void revokeConsumer ( String topic, String apiKey ) throws HttpException, IOException; +} + diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/Clock.java b/src/main/java/org/onap/dmaap/mr/client/impl/Clock.java new file mode 100644 index 0000000..6670399 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/Clock.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +public class Clock +{ + public synchronized static Clock getIt () + { + if ( sfClock == null ) + { + sfClock = new Clock (); + } + return sfClock; + } + + /** + * Get the system's current time in milliseconds. + * @return the current time + */ + public static long now () + { + return getIt().nowImpl (); + } + + /** + * Get current time in milliseconds + * @return current time in ms + */ + protected long nowImpl () + { + return System.currentTimeMillis (); + } + + protected Clock () + { + } + + private static Clock sfClock = null; + + protected synchronized static void register ( Clock testClock ) + { + sfClock = testClock; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java b/src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java new file mode 100644 index 0000000..b06290a --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; + +public class DmaapClientUtil { + + private static final String MR_AUTH_CONSTANT = "X-CambriaAuth"; + private static final String MR_DATE_CONSTANT = "X-CambriaDate"; + + public static WebTarget getTarget(final String path, final String username, final String password) { + + Client client = ClientBuilder.newClient(); + HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password); + client.register(feature); + + return client.target(path); + } + + public static WebTarget getTarget(final String path) { + + Client client = ClientBuilder.newClient(); + return client.target(path); + } + + public static Response getResponsewtCambriaAuth(WebTarget target, String username, String password) { + return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get(); + + } + + public static Response postResponsewtCambriaAuth(WebTarget target, String username, String password,byte[] data, String contentType) { + return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).post(Entity.entity(data, contentType)); + + } + + public static Response getResponsewtBasicAuth(WebTarget target, String authHeader) { + + return target.request().header("Authorization", "Basic " + authHeader).get(); + + } + + public static Response postResponsewtBasicAuth(WebTarget target, String authHeader,byte[] data,String contentType) { + + return target.request().header("Authorization", "Basic " + authHeader).post(Entity.entity(data, contentType)); + + } + + public static Response getResponsewtNoAuth(WebTarget target) { + + return target.request().get(); + + } + + public static Response postResponsewtNoAuth(WebTarget target, byte[] data, String contentType) { + return target.request().post(Entity.entity(data, contentType)); + + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java new file mode 100644 index 0000000..ecea21c --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java @@ -0,0 +1,395 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.net.MalformedURLException; +import java.util.Collection; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import org.apache.http.HttpException; +import org.glassfish.jersey.internal.util.Base64; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.apiClient.http.CacheUse; +import com.att.nsa.apiClient.http.HttpClient; +import org.onap.dmaap.mr.client.MRClient; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; + +public class MRBaseClient extends HttpClient implements MRClient { + + + protected MRBaseClient(Collection hosts) throws MalformedURLException { + super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort); + + fLog = LoggerFactory.getLogger(this.getClass().getName()); + } + + protected MRBaseClient(Collection hosts, int stdSvcPort) throws MalformedURLException { + super(ConnectionType.HTTP, hosts, stdSvcPort); + + fLog = LoggerFactory.getLogger(this.getClass().getName()); + } + + protected MRBaseClient(Collection hosts, String clientSignature) throws MalformedURLException { + super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort, clientSignature, CacheUse.NONE, 1, 1L, + TimeUnit.MILLISECONDS, 32, 32, 600000); + + fLog = LoggerFactory.getLogger(this.getClass().getName()); + } + + @Override + public void close() { + } + + protected Set jsonArrayToSet(JSONArray a) { + if (a == null) + return null; + + final TreeSet set = new TreeSet(); + for (int i = 0; i < a.length(); i++) { + set.add(a.getString(i)); + } + return set; + } + + public void logTo(Logger log) { + fLog = log; + replaceLogger(log); + } + + protected Logger getLog() { + return fLog; + } + + private Logger fLog; + + public JSONObject post(final String path, final byte[] data, final String contentType, final String username, + final String password, final String protocalFlag) throws HttpException, JSONException { + if ((null != username && null != password)) { + WebTarget target=null; + Response response=null; + target = DmaapClientUtil.getTarget(path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + + response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding,data, contentType); + + return getResponseDataInJson(response); + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); + } + } + + public JSONObject postNoAuth(final String path, final byte[] data, String contentType) + throws HttpException, JSONException { + WebTarget target = null; + Response response = null; + if (contentType == null) { + contentType = "text/pain"; + } + target = DmaapClientUtil.getTarget(path); + + response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); + + return getResponseDataInJson(response); + } + + public String postWithResponse(final String path, final byte[] data, final String contentType, + final String username, final String password, final String protocolFlag) + throws HttpException, JSONException { + String responseData = null; + if ((null != username && null != password)) { + WebTarget target=null; + Response response=null; + target = DmaapClientUtil.getTarget(path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + + response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding,data, contentType); + + responseData = (String)response.readEntity(String.class); + return responseData; + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); + } + } + + public String postNoAuthWithResponse(final String path, final byte[] data, String contentType) + throws HttpException, JSONException { + + String responseData = null; + WebTarget target = null; + Response response = null; + if (contentType == null) { + contentType = "text/pain"; + } + target = DmaapClientUtil.getTarget(path); + + response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); + responseData = (String) response.readEntity(String.class); + return responseData; + } + + public JSONObject postAuth(final String path, final byte[] data, final String contentType, final String authKey, + final String authDate, final String username, final String password, final String protocolFlag) + throws HttpException, JSONException { + if ((null != username && null != password)) { + WebTarget target=null; + Response response=null; + target = DmaapClientUtil.getTarget(path, username, password); + response =DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType); + return getResponseDataInJson(response); + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); + } + } + + public String postAuthwithResponse(final String path, final byte[] data, final String contentType, + final String authKey, final String authDate, final String username, final String password, + final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + if ((null != username && null != password)) { + WebTarget target=null; + Response response=null; + target = DmaapClientUtil.getTarget(path, username, password); + response = DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType); + responseData = (String)response.readEntity(String.class); + return responseData; + + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."); + } + } + + public JSONObject get(final String path, final String username, final String password, final String protocolFlag) + throws HttpException, JSONException { + if (null != username && null != password) { + + WebTarget target=null; + Response response=null; + + if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + target = DmaapClientUtil.getTarget(path); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); + } else { + target = DmaapClientUtil.getTarget(path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + + response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); + + } + return getResponseDataInJson(response); + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); + } + } + + public String getResponse(final String path, final String username, final String password, + final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + if (null != username && null != password) { + WebTarget target=null; + Response response=null; + if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + target = DmaapClientUtil.getTarget(path); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); + } else { + target = DmaapClientUtil.getTarget(path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); + } + MRClientFactory.HTTPHeadersMap = response.getHeaders(); + + String transactionid = response.getHeaderString("transactionid"); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + fLog.info("TransactionId : " + transactionid); + } + + responseData = (String)response.readEntity(String.class); + return responseData; + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); + } + } + + public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username, + final String password, final String protocolFlag) throws HttpException, JSONException { + if (null != username && null != password) { + WebTarget target=null; + Response response=null; + target = DmaapClientUtil.getTarget(path, username, password); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); + + return getResponseDataInJson(response); + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); + } + } + + public JSONObject getNoAuth(final String path) throws HttpException, JSONException { + + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(path); + response = DmaapClientUtil.getResponsewtNoAuth(target); + + return getResponseDataInJson(response); + } + + public String getAuthResponse(final String path, final String authKey, final String authDate, final String username, + final String password, final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + if (null != username && null != password) { + WebTarget target=null; + Response response=null; + target = DmaapClientUtil.getTarget(path, username, password); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); + + MRClientFactory.HTTPHeadersMap = response.getHeaders(); + + String transactionid = response.getHeaderString("transactionid"); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + fLog.info("TransactionId : " + transactionid); + } + + responseData = (String)response.readEntity(String.class); + return responseData; + } else { + throw new HttpException( + "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty."); + } + } + + public String getNoAuthResponse(String path, final String username, final String password, + final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + WebTarget target=null; + Response response=null; + target = DmaapClientUtil.getTarget(path, username, password); + response = DmaapClientUtil.getResponsewtNoAuth(target); + + MRClientFactory.HTTPHeadersMap = response.getHeaders(); + + String transactionid = response.getHeaderString("transactionid"); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + fLog.info("TransactionId : " + transactionid); + } + + responseData = (String)response.readEntity(String.class); + return responseData; + + } + + + private JSONObject getResponseDataInJson(Response response) throws JSONException { + try { + MRClientFactory.HTTPHeadersMap = response.getHeaders(); + + + // MultivaluedMap headersMap = + // for(String key : headersMap.keySet()) { + String transactionid = response.getHeaderString("transactionid"); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + fLog.info("TransactionId : " + transactionid); + } + + + if (response.getStatus() == 403) { + JSONObject jsonObject = null; + jsonObject = new JSONObject(); + JSONArray jsonArray = new JSONArray(); + jsonArray.put(response.getEntity()); + jsonObject.put("result", jsonArray); + jsonObject.put("status", response.getStatus()); + return jsonObject; + } + String responseData = (String)response.readEntity(String.class); + + JSONTokener jsonTokener = new JSONTokener(responseData); + JSONObject jsonObject = null; + final char firstChar = jsonTokener.next(); + jsonTokener.back(); + if ('[' == firstChar) { + JSONArray jsonArray = new JSONArray(jsonTokener); + jsonObject = new JSONObject(); + jsonObject.put("result", jsonArray); + jsonObject.put("status", response.getStatus()); + } else { + jsonObject = new JSONObject(jsonTokener); + jsonObject.put("status", response.getStatus()); + } + + return jsonObject; + } catch (JSONException excp) { + fLog.error("DMAAP - Error reading response data.", excp); + return null; + } + + } + + public String getHTTPErrorResponseMessage(String responseString) { + + String response = null; + int beginIndex = 0; + int endIndex = 0; + if (responseString.contains("")) { + + beginIndex = responseString.indexOf("body>") + 5; + endIndex = responseString.indexOf("")) { + beginIndex = responseString.indexOf("title>") + 6; + endIndex = responseString.indexOf(" baseUrls, String topic, int maxBatchSize, long maxAgeMs, boolean compress ) + { + if ( maxAgeMs < kMinMaxAgeMs ) + { + fLog.warn ( "Max age in ms is less than the minimum. Overriding to " + kMinMaxAgeMs ); + maxAgeMs = kMinMaxAgeMs; + } + + try { + fSender = new Sender ( baseUrls, topic, maxBatchSize, maxAgeMs, compress ); + } catch (MalformedURLException e) { + throw new IllegalArgumentException (e); + } + + // FIXME: this strategy needs an overhaul -- why not just run a thread that knows how to wait for + // the oldest msg to hit max age? (locking is complicated, but should be do-able) + fExec = new ScheduledThreadPoolExecutor ( 1 ); + fExec.scheduleAtFixedRate ( fSender, 100, 50, TimeUnit.MILLISECONDS ); + } + + @Override + public void setApiCredentials ( String apiKey, String apiSecret ) + { + fSender.setApiCredentials ( apiKey, apiSecret ); + } + + @Override + public void clearApiCredentials () + { + fSender.clearApiCredentials (); + } + + /** + * Send the given message with the given partition + * @param partition + * @param msg + * @throws IOException + */ + @Override + public int send ( String partition, String msg ) throws IOException + { + return send ( new message ( partition, msg ) ); + } + @Override + public int send ( String msg ) throws IOException + { + return send ( new message ( "",msg ) ); + } + /** + * Send the given message + * @param userMsg a message + * @throws IOException + */ + @Override + public int send ( message userMsg ) throws IOException + { + final LinkedList list = new LinkedList (); + list.add ( userMsg ); + return send ( list ); + } + + /** + * Send the given set of messages + * @param msgs the set of messages, sent in order of iteration + * @return the number of messages in the pending queue (this could actually be less than the size of the given collection, depending on thread timing) + * @throws IOException + */ + @Override + public int send ( Collection msgs ) throws IOException + { + if ( msgs.isEmpty() ) + { + fSender.queue ( msgs ); + } + return fSender.size (); + } + + @Override + public int getPendingMessageCount () + { + return fSender.size (); + } + + /** + * Send any pending messages and close this publisher. + * @throws IOException + * @throws InterruptedException + */ + @Override + public void close () + { + try + { + final List remains = close ( Long.MAX_VALUE, TimeUnit.MILLISECONDS ); + if ( remains.isEmpty() ) + { + fLog.warn ( "Closing publisher with " + remains.size() + " messages unsent. " + + "(Consider using the alternate close method to capture unsent messages in this case.)" ); + } + } + catch ( InterruptedException e ) + { + fLog.warn ( "Possible message loss. " + e.getMessage(), e ); + Thread.currentThread().interrupt(); + } + catch ( IOException e ) + { + fLog.warn ( "Possible message loss. " + e.getMessage(), e ); + } + } + + public List close ( long time, TimeUnit unit ) throws InterruptedException, IOException + { + fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy ( false ); + fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy ( false ); + fExec.shutdown (); + + final long waitInMs = TimeUnit.MILLISECONDS.convert ( time, unit ); + final long timeoutAtMs = System.currentTimeMillis () + waitInMs; + while ( System.currentTimeMillis () < timeoutAtMs && getPendingMessageCount() > 0 ) + { + fSender.checkSend ( true ); + Thread.sleep ( 250 ); + } + + final LinkedList result = new LinkedList (); + fSender.drainTo ( result ); + return result; + } + + private final ScheduledThreadPoolExecutor fExec; + private final Sender fSender; + + private static class TimestampedMessage extends message + { + public TimestampedMessage ( message m ) + { + super ( m ); + timestamp = System.currentTimeMillis (); + } + public final long timestamp; + } + + private Logger fLog = LoggerFactory.getLogger ( MRBatchPublisher.class ); + + private class Sender extends MRBaseClient implements Runnable + { + public Sender ( Collection baseUrls, String topic, int maxBatch, long maxAgeMs, boolean compress ) throws MalformedURLException + { + super ( baseUrls ); + + fNextBatch = new LinkedList (); + fSendingBatch = null; + fTopic = topic; + fMaxBatchSize = maxBatch; + fMaxAgeMs = maxAgeMs; + fCompress = compress; + fLock = new ReentrantReadWriteLock (); + fWriteLock = fLock.writeLock (); + fReadLock = fLock.readLock (); + fDontSendUntilMs = 0; + } + + public void drainTo ( LinkedList list ) + { + fWriteLock.lock (); + try + { + if ( fSendingBatch != null ) + { + list.addAll ( fSendingBatch ); + } + list.addAll ( fNextBatch ); + + fSendingBatch = null; + fNextBatch.clear (); + } + finally + { + fWriteLock.unlock (); + } + } + + /** + * Called periodically by the background executor. + */ + @Override + public void run () + { + try + { + checkSend ( false ); + } + catch ( IOException e ) + { + fLog.warn ( "MR background send: " + e.getMessage () ); + fLog.error( "IOException " + e ); + } + } + + public int size () + { + fReadLock.lock (); + try + { + return fNextBatch.size () + ( fSendingBatch == null ? 0 : fSendingBatch.size () ); + } + finally + { + fReadLock.unlock (); + } + } + + /** + * Called to queue a message. + * @param m + * @throws IOException + */ + public void queue ( Collection msgs ) throws IOException + { + fWriteLock.lock (); + try + { + for ( message userMsg : msgs ) + { + if ( userMsg != null ) + { + fNextBatch.add ( new TimestampedMessage ( userMsg ) ); + } + else + { + fLog.warn ( "MRBatchPublisher::Sender::queue received a null message." ); + } + } + } + finally + { + fWriteLock.unlock(); + } + checkSend ( false ); + } + + /** + * Send a batch if the queue is long enough, or the first pending message is old enough. + * @param force + * @throws IOException + */ + public void checkSend ( boolean force ) throws IOException + { + // hold a read lock just long enough to evaluate whether a batch + // should be sent + boolean shouldSend = false; + fReadLock.lock (); + try + { + if ( fNextBatch.isEmpty() ) + { + final long nowMs = System.currentTimeMillis (); + shouldSend = ( force || fNextBatch.size() >= fMaxBatchSize ); + if ( !shouldSend ) + { + final long sendAtMs = fNextBatch.getFirst ().timestamp + fMaxAgeMs; + shouldSend = sendAtMs <= nowMs; + } + + // however, unless forced, wait after an error + shouldSend = force || ( shouldSend && nowMs >= fDontSendUntilMs ); + } + // else: even in 'force', there's nothing to send, so shouldSend=false is fine + } + finally + { + fReadLock.unlock (); + } + + // if a send is required, acquire a write lock, swap out the next batch, + // swap in a fresh batch, and release the lock for the caller to start + // filling a batch again. After releasing the lock, send the current + // batch. (There could be more messages added between read unlock and + // write lock, but that's fine.) + if ( shouldSend ) + { + fSendingBatch = null; + + fWriteLock.lock (); + try + { + fSendingBatch = fNextBatch; + fNextBatch = new LinkedList (); + } + finally + { + fWriteLock.unlock (); + } + + if ( !doSend ( fSendingBatch, this, fTopic, fCompress, fLog ) ) + { + fLog.warn ( "Send failed, rebuilding send queue." ); + + // note the time for back-off + fDontSendUntilMs = sfWaitAfterError + System.currentTimeMillis (); + + // the send failed. reconstruct the pending queue + fWriteLock.lock (); + try + { + final LinkedList nextGroup = fNextBatch; + fNextBatch = fSendingBatch; + fNextBatch.addAll ( nextGroup ); + fSendingBatch = null; + fLog.info ( "Send queue rebuilt; " + fNextBatch.size () + " messages to send." ); + } + finally + { + fWriteLock.unlock (); + } + } + else + { + fWriteLock.lock (); + try + { + fSendingBatch = null; + } + finally + { + fWriteLock.unlock (); + } + } + } + } + + private LinkedList fNextBatch; + private LinkedList fSendingBatch; + private final String fTopic; + private final int fMaxBatchSize; + private final long fMaxAgeMs; + private final boolean fCompress; + private final ReentrantReadWriteLock fLock; + private final WriteLock fWriteLock; + private final ReadLock fReadLock; + private long fDontSendUntilMs; + private static final long sfWaitAfterError = 1000; + } + + // this is static so that it's clearly not using any mutable member data outside of a lock + private static boolean doSend ( LinkedList toSend, HttpClient client, String topic, boolean compress, Logger log ) + { + // it's possible for this call to be made with an empty list. in this case, just return. + if ( toSend.isEmpty() ) + { + return true; + } + + final long nowMs = System.currentTimeMillis (); + final String url = MRConstants.makeUrl ( topic ); + + log.info ( "sending " + toSend.size() + " msgs to " + url + ". Oldest: " + ( nowMs - toSend.getFirst().timestamp ) + " ms" ); + + final ByteArrayOutputStream baseStream = new ByteArrayOutputStream (); + try + { + OutputStream os = baseStream; + if ( compress ) + { + os = new GZIPOutputStream ( baseStream ); + } + for ( TimestampedMessage m : toSend ) + { + os.write ( ( "" + m.fPartition.length () ).getBytes() ); + os.write ( '.' ); + os.write ( ( "" + m.fMsg.length () ).getBytes() ); + os.write ( '.' ); + os.write ( m.fPartition.getBytes() ); + os.write ( m.fMsg.getBytes() ); + os.write ( '\n' ); + } + os.close (); + } + catch ( IOException e ) + { + log.warn ( "Problem writing stream to post: " + e.getMessage (),e ); + return false; + } + + boolean result = false; + final long startMs = System.currentTimeMillis (); + try + { + client.post ( url, compress ? + MRFormat.CAMBRIA_ZIP.toString () : + MRFormat.CAMBRIA.toString (), + baseStream.toByteArray(), false ); + result = true; + } + catch ( HttpException e ) + { + log.warn ( "Problem posting to MR: " + e.getMessage(),e ); + } + catch ( IOException e ) + { + log.warn ( "Problem posting to MR: " + e.getMessage(),e ); + } + + log.info ( "MR response (" + (System.currentTimeMillis ()-startMs) + " ms): OK" ); + return result; + } + + @Override + public void logTo ( Logger log ) + { + fLog = log; + } + + @Override + public MRPublisherResponse sendBatchWithResponse() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java new file mode 100644 index 0000000..ed23918 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MRClientVersionInfo +{ + private static final Logger logger = LoggerFactory.getLogger(MRClientVersionInfo.class); + public static String getVersion () + { + return version; + } + + private static final Properties props = new Properties(); + private static final String version; + static + { + String use = null; + try + { + final InputStream is = MRClientVersionInfo.class.getResourceAsStream ( "/MRClientVersion.properties" ); + if ( is != null ) + { + props.load ( is ); + use = props.getProperty ( "MRClientVersion", null ); + } + } + catch ( IOException e ) + { + logger.error("exception: ", e); + } + version = use; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java new file mode 100644 index 0000000..f6d9578 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java @@ -0,0 +1,179 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.apache.http.HttpHost; + +class MRConstants +{ + private static final String PROTOCOL = "http"; + public static final String context = "/"; + public static final String kBasePath = "events/"; + public static final int kStdMRServicePort = 8080; + + public static String escape ( String s ) + { + try + { + return URLEncoder.encode ( s, "UTF-8"); + } + catch ( UnsupportedEncodingException e ) + { + throw new IllegalArgumentException(e); + } + } + + public static String makeUrl ( String rawTopic ) + { + final String cleanTopic = escape ( rawTopic ); + + final StringBuffer url = new StringBuffer(). + append ( MRConstants.context ). + append ( MRConstants.kBasePath ). + append ( cleanTopic ); + return url.toString (); + } + + public static String makeUrl ( final String host, final String rawTopic ) + { + final String cleanTopic = escape ( rawTopic ); + + final StringBuffer url = new StringBuffer(); + + if (!host.startsWith("http") || !host.startsWith("https") ) { + url.append( PROTOCOL + "://" ); + } + url.append(host); + url.append ( MRConstants.context ); + url.append ( MRConstants.kBasePath ); + url.append ( cleanTopic ); + return url.toString (); + } + + public static String makeUrl ( final String host, final String rawTopic, final String transferprotocol,final String parttion ) + { + final String cleanTopic = escape ( rawTopic ); + + final StringBuffer url = new StringBuffer(); + + if (transferprotocol !=null && !transferprotocol.equals("")) { + url.append( transferprotocol + "://" ); + }else{ + url.append( PROTOCOL + "://" ); + } + url.append(host); + url.append ( MRConstants.context ); + url.append ( MRConstants.kBasePath ); + url.append ( cleanTopic ); + if(parttion!=null && !parttion.equalsIgnoreCase("")) + url.append("?partitionKey=").append(parttion); + return url.toString (); + } + public static String makeConsumerUrl ( String topic, String rawConsumerGroup, String rawConsumerId ) + { + final String cleanConsumerGroup = escape ( rawConsumerGroup ); + final String cleanConsumerId = escape ( rawConsumerId ); + return MRConstants.context + MRConstants.kBasePath + topic + "/" + cleanConsumerGroup + "/" + cleanConsumerId; + } + + /** + * Create a list of HttpHosts from an input list of strings. Input strings have + * host[:port] as format. If the port section is not provided, the default port is used. + * + * @param hosts + * @return a list of hosts + */ + public static List createHostsList(Collection hosts) + { + final ArrayList convertedHosts = new ArrayList (); + for ( String host : hosts ) + { + if ( host.length () == 0 ) continue; + convertedHosts.add ( hostForString ( host ) ); + } + return convertedHosts; + } + + /** + * Return an HttpHost from an input string. Input string has + * host[:port] as format. If the port section is not provided, the default port is used. + * + * @param hosts + * @return a list of hosts + */ + public static HttpHost hostForString ( String host ) + { + if ( host.length() < 1 ) throw new IllegalArgumentException ( "An empty host entry is invalid." ); + + String hostPart = host; + int port = kStdMRServicePort; + + final int colon = host.indexOf ( ':' ); + if ( colon == 0 ) throw new IllegalArgumentException ( "Host entry '" + host + "' is invalid." ); + if ( colon > 0 ) + { + hostPart = host.substring ( 0, colon ).trim(); + + final String portPart = host.substring ( colon + 1 ).trim(); + if ( portPart.length () > 0 ) + { + try + { + port = Integer.parseInt ( portPart ); + } + catch ( NumberFormatException x ) + { + throw new IllegalArgumentException ( "Host entry '" + host + "' is invalid.", x ); + } + } + // else: use default port on "foo:" + } + + return new HttpHost ( hostPart, port ); + } + + public static String makeConsumerUrl(String host, String fTopic, String fGroup, String fId,final String transferprotocol) { + final String cleanConsumerGroup = escape ( fGroup ); + final String cleanConsumerId = escape ( fId ); + + StringBuffer url = new StringBuffer(); + + if (transferprotocol !=null && !transferprotocol.equals("")) { + url.append( transferprotocol + "://" ); + }else{ + url.append( PROTOCOL + "://" ); + } + + url.append(host); + url.append(context); + url.append(kBasePath); + url.append(fTopic + "/" + cleanConsumerGroup + "/" + cleanConsumerId); + + return url.toString(); + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java new file mode 100644 index 0000000..a1a52aa --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java @@ -0,0 +1,675 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import com.att.aft.dme2.api.DME2Client; +import com.att.aft.dme2.api.DME2Exception; +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; +import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; +import org.apache.http.HttpException; +import org.apache.http.HttpStatus; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MRConsumerImpl extends MRBaseClient implements MRConsumer { + + private Logger log = LoggerFactory.getLogger(this.getClass().getName()); + + public static final String routerFilePath = null; + + public String protocolFlag = ProtocolTypeConstants.DME2.getValue(); + public String consumerFilePath; + + private static final String SUCCESS_MESSAGE = "Success"; + private static final long DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS = 10000L; + private static final long DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS = 10000L; + + private final String fTopic; + private final String fGroup; + private final String fId; + private final int fTimeoutMs; + private final int fLimit; + private String fFilter; + private String username; + private String password; + private String host; + private HostSelector fHostSelector = null; + private String url; + private DME2Client sender; + private String authKey; + private String authDate; + private Properties props; + private HashMap DMETimeOuts; + private long dme2ReplyHandlerTimeoutMs; + private long longPollingMs; + + public MRConsumerImpl(Collection hostPart, final String topic, final String consumerGroup, + final String consumerId, int timeoutMs, int limit, String filter, String apiKey_username, + String apiSecret_password) throws MalformedURLException { + this(hostPart, topic, consumerGroup, consumerId, timeoutMs, limit, filter, apiKey_username, apiSecret_password, + false); + } + + public MRConsumerImpl(Collection hostPart, final String topic, final String consumerGroup, + final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret, + boolean allowSelfSignedCerts) throws MalformedURLException { + super(hostPart, topic + "::" + consumerGroup + "::" + consumerId); + + fTopic = topic; + fGroup = consumerGroup; + fId = consumerId; + fTimeoutMs = timeoutMs; + fLimit = limit; + fFilter = filter; + + fHostSelector = new HostSelector(hostPart); + } + + @Override + public Iterable fetch() throws IOException, Exception { + // fetch with the timeout and limit set in constructor + return fetch(fTimeoutMs, fLimit); + } + + @Override + public Iterable fetch(int timeoutMs, int limit) throws Exception { + final LinkedList msgs = new LinkedList<>(); + + try { + if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { + dmeConfigure(timeoutMs, limit); + try { + String reply = sender.sendAndWait(timeoutMs + 10000L); + final JSONObject o = getResponseDataInJson(reply); + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + } catch (JSONException e) { + // unexpected response + reportProblemWithResponse(); + log.error("exception: ", e); + } catch (HttpException e) { + throw new IOException(e); + } + } + + if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { + final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, + fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); + + try { + final JSONObject o = get(urlPath, username, password, protocolFlag); + + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + } catch (JSONException e) { + // unexpected response + reportProblemWithResponse(); + log.error("exception: ", e); + } catch (HttpException e) { + throw new IOException(e); + } + } + + if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + final String urlPath = createUrlPath( + MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty("Protocol")), + timeoutMs, limit); + + try { + final JSONObject o = getAuth(urlPath, authKey, authDate, username, password, protocolFlag); + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + } catch (JSONException e) { + // unexpected response + reportProblemWithResponse(); + log.error("exception: ", e); + } catch (HttpException e) { + throw new IOException(e); + } + } + + if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { + final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, + fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); + + try { + final JSONObject o = getNoAuth(urlPath); + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + } catch (JSONException e) { + // unexpected response + reportProblemWithResponse(); + log.error("exception: ", e); + } catch (HttpException e) { + throw new IOException(e); + } + } + } catch (JSONException e) { + // unexpected response + reportProblemWithResponse(); + log.error("exception: ", e); + } catch (HttpException e) { + throw new IOException(e); + } catch (Exception e) { + throw e; + } + + return msgs; + } + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse() { + // fetch with the timeout and limit set in constructor + return fetchWithReturnConsumerResponse(fTimeoutMs, fLimit); + } + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, int limit) { + final LinkedList msgs = new LinkedList(); + MRConsumerResponse mrConsumerResponse = new MRConsumerResponse(); + try { + if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { + dmeConfigure(timeoutMs, limit); + + long timeout = (dme2ReplyHandlerTimeoutMs > 0 && longPollingMs == timeoutMs) ? dme2ReplyHandlerTimeoutMs + : (timeoutMs + DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS); + String reply = sender.sendAndWait(timeout); + + final JSONObject o = getResponseDataInJsonWithResponseReturned(reply); + + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + createMRConsumerResponse(reply, mrConsumerResponse); + } + + if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { + final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, + fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); + + String response = getResponse(urlPath, username, password, protocolFlag); + final JSONObject o = getResponseDataInJsonWithResponseReturned(response); + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + createMRConsumerResponse(response, mrConsumerResponse); + } + + if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + final String urlPath = createUrlPath( + MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty("Protocol")), + timeoutMs, limit); + + String response = getAuthResponse(urlPath, authKey, authDate, username, password, protocolFlag); + final JSONObject o = getResponseDataInJsonWithResponseReturned(response); + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + createMRConsumerResponse(response, mrConsumerResponse); + } + + if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { + final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, + fGroup, fId, props.getProperty("Protocol")), timeoutMs, limit); + + String response = getNoAuthResponse(urlPath, username, password, protocolFlag); + final JSONObject o = getResponseDataInJsonWithResponseReturned(response); + if (o != null) { + final JSONArray a = o.getJSONArray("result"); + + if (a != null) { + for (int i = 0; i < a.length(); i++) { + if (a.get(i) instanceof String) + msgs.add(a.getString(i)); + else + msgs.add(a.getJSONObject(i).toString()); + } + } + } + createMRConsumerResponse(response, mrConsumerResponse); + } + + } catch (JSONException e) { + mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + mrConsumerResponse.setResponseMessage(e.getMessage()); + log.error("json exception: ", e); + } catch (HttpException e) { + mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + mrConsumerResponse.setResponseMessage(e.getMessage()); + log.error("http exception: ", e); + } catch (DME2Exception e) { + mrConsumerResponse.setResponseCode(e.getErrorCode()); + mrConsumerResponse.setResponseMessage(e.getErrorMessage()); + log.error("DME2 exception: ", e); + } catch (Exception e) { + mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + mrConsumerResponse.setResponseMessage(e.getMessage()); + log.error("exception: ", e); + } + mrConsumerResponse.setActualMessages(msgs); + return mrConsumerResponse; + } + + @Override + protected void reportProblemWithResponse() { + log.warn("There was a problem with the server response. Blacklisting for 3 minutes."); + super.reportProblemWithResponse(); + fHostSelector.reportReachabilityProblem(3, TimeUnit.MINUTES); + } + + private void createMRConsumerResponse(String reply, MRConsumerResponse mrConsumerResponse) { + if (reply.startsWith("{")) { + JSONObject jObject = new JSONObject(reply); + String message = jObject.getString("message"); + int status = jObject.getInt("status"); + + mrConsumerResponse.setResponseCode(Integer.toString(status)); + + if (null != message) { + mrConsumerResponse.setResponseMessage(message); + } + } else if (reply.startsWith("<")) { + mrConsumerResponse.setResponseCode(getHTTPErrorResponseCode(reply)); + mrConsumerResponse.setResponseMessage(getHTTPErrorResponseMessage(reply)); + } else { + mrConsumerResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK)); + mrConsumerResponse.setResponseMessage(SUCCESS_MESSAGE); + } + } + + private JSONObject getResponseDataInJson(String response) { + try { + JSONTokener jsonTokener = new JSONTokener(response); + JSONObject jsonObject = null; + final char firstChar = jsonTokener.next(); + jsonTokener.back(); + if ('[' == firstChar) { + JSONArray jsonArray = new JSONArray(jsonTokener); + jsonObject = new JSONObject(); + jsonObject.put("result", jsonArray); + } else { + jsonObject = new JSONObject(jsonTokener); + } + + return jsonObject; + } catch (JSONException excp) { + log.error("DMAAP - Error reading response data.", excp); + return null; + } + } + + private JSONObject getResponseDataInJsonWithResponseReturned(String response) { + JSONTokener jsonTokener = new JSONTokener(response); + JSONObject jsonObject = null; + final char firstChar = jsonTokener.next(); + jsonTokener.back(); + if (null != response && response.length() == 0) { + return null; + } + + if ('[' == firstChar) { + JSONArray jsonArray = new JSONArray(jsonTokener); + jsonObject = new JSONObject(); + jsonObject.put("result", jsonArray); + } else if ('{' == firstChar) { + return null; + } else if ('<' == firstChar) { + return null; + } else { + jsonObject = new JSONObject(jsonTokener); + } + + return jsonObject; + } + + private void dmeConfigure(int timeoutMs, int limit) throws IOException, DME2Exception, URISyntaxException { + this.longPollingMs = timeoutMs; + String latitude = props.getProperty("Latitude"); + String longitude = props.getProperty("Longitude"); + String version = props.getProperty("Version"); + String serviceName = props.getProperty("ServiceName"); + String env = props.getProperty("Environment"); + String partner = props.getProperty("Partner"); + String routeOffer = props.getProperty("routeOffer"); + String subContextPath = props.getProperty("SubContextPath") + fTopic + "/" + fGroup + "/" + fId; + String protocol = props.getProperty("Protocol"); + String methodType = props.getProperty("MethodType"); + String dmeuser = props.getProperty("username"); + String dmepassword = props.getProperty("password"); + String contenttype = props.getProperty("contenttype"); + String handlers = props.getProperty("sessionstickinessrequired"); + + /** + * Changes to DME2Client url to use Partner for auto failover between data centers When Partner value is not + * provided use the routeOffer value for auto failover within a cluster + */ + + String preferredRouteKey = readRoute("preferredRouteKey"); + + if (partner != null && !partner.isEmpty() && preferredRouteKey != null && !preferredRouteKey.isEmpty()) { + url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" + partner + + "&routeoffer=" + preferredRouteKey; + } else if (partner != null && !partner.isEmpty()) { + url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" + partner; + } else if (routeOffer != null && !routeOffer.isEmpty()) { + url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer=" + + routeOffer; + } + + if (timeoutMs != -1) + url = url + "&timeout=" + timeoutMs; + if (limit != -1) + url = url + "&limit=" + limit; + + // Add filter to DME2 Url + if (fFilter != null && fFilter.length() > 0) + url = url + "&filter=" + URLEncoder.encode(fFilter, "UTF-8"); + + DMETimeOuts = new HashMap<>(); + DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); + DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS")); + DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); + DMETimeOuts.put("Content-Type", contenttype); + System.setProperty("AFT_LATITUDE", latitude); + System.setProperty("AFT_LONGITUDE", longitude); + System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT")); + + // SSL changes + System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2"); + System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false"); + System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit"); + // SSL changes + + long dme2PerEndPointTimeoutMs; + try { + dme2PerEndPointTimeoutMs = Long.parseLong(props.getProperty("DME2_PER_HANDLER_TIMEOUT_MS")); + // backward compatibility + if (dme2PerEndPointTimeoutMs <= 0) { + dme2PerEndPointTimeoutMs = timeoutMs + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS; + } + } catch (NumberFormatException nfe) { + // backward compatibility + dme2PerEndPointTimeoutMs = timeoutMs + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS; + getLog().debug( + "DME2_PER_HANDLER_TIMEOUT_MS not set and using default " + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS); + } + + try { + dme2ReplyHandlerTimeoutMs = Long.parseLong(props.getProperty("DME2_REPLY_HANDLER_TIMEOUT_MS")); + } catch (NumberFormatException nfe) { + try { + long dme2EpReadTimeoutMs = Long.parseLong(props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); + long dme2EpConnTimeoutMs = Long.parseLong(props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); + dme2ReplyHandlerTimeoutMs = timeoutMs + dme2EpReadTimeoutMs + dme2EpConnTimeoutMs; + getLog().debug( + "DME2_REPLY_HANDLER_TIMEOUT_MS not set and using default from timeoutMs, AFT_DME2_EP_READ_TIMEOUT_MS and AFT_DME2_EP_CONN_TIMEOUT " + + dme2ReplyHandlerTimeoutMs); + } catch (NumberFormatException e) { + // backward compatibility + dme2ReplyHandlerTimeoutMs = timeoutMs + DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS; + getLog().debug("DME2_REPLY_HANDLER_TIMEOUT_MS not set and using default " + dme2ReplyHandlerTimeoutMs); + } + } + // backward compatibility + if (dme2ReplyHandlerTimeoutMs <= 0) { + dme2ReplyHandlerTimeoutMs = timeoutMs + DEFAULT_DME2_REPLY_HANDLER_TIMEOUT_MS; + } + + sender = new DME2Client(new URI(url), dme2PerEndPointTimeoutMs); + sender.setAllowAllHttpReturnCodes(true); + sender.setMethod(methodType); + sender.setSubContext(subContextPath); + if (dmeuser != null && dmepassword != null) { + sender.setCredentials(dmeuser, dmepassword); + } + sender.setHeaders(DMETimeOuts); + sender.setPayload(""); + if (handlers != null && handlers.equalsIgnoreCase("yes")) { + sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", + props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS")); + sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS")); + sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON")); + } else { + sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler"); + } + } + + protected String createUrlPath(String url, int timeoutMs, int limit) throws IOException { + final StringBuilder contexturl = new StringBuilder(url); + final StringBuilder adds = new StringBuilder(); + + if (timeoutMs > -1) { + adds.append("timeout=").append(timeoutMs); + } + + if (limit > -1) { + if (adds.length() > 0) { + adds.append("&"); + } + adds.append("limit=").append(limit); + } + + if (fFilter != null && fFilter.length() > 0) { + try { + if (adds.length() > 0) { + adds.append("&"); + } + adds.append("filter=").append(URLEncoder.encode(fFilter, "UTF-8")); + } catch (UnsupportedEncodingException e) { + log.error("exception at createUrlPath () : ", e); + } + } + + if (adds.length() > 0) { + contexturl.append("?").append(adds.toString()); + } + + return contexturl.toString(); + } + + private String readRoute(String routeKey) { + try { + MRClientFactory.prop.load(new FileReader(new File(MRClientFactory.routeFilePath))); + } catch (Exception ex) { + log.error("Reply Router Error " + ex); + } + return MRClientFactory.prop.getProperty(routeKey); + } + + public static List stringToList(String str) { + final LinkedList set = new LinkedList<>(); + if (str != null) { + final String[] parts = str.trim().split(","); + for (String part : parts) { + final String trimmed = part.trim(); + if (trimmed.length() > 0) { + set.add(trimmed); + } + } + } + return set; + } + + public static String getRouterFilePath() { + return routerFilePath; + } + + public static void setRouterFilePath(String routerFilePath) { + MRSimplerBatchPublisher.routerFilePath = routerFilePath; + } + + public String getConsumerFilePath() { + return consumerFilePath; + } + + public void setConsumerFilePath(String consumerFilePath) { + this.consumerFilePath = consumerFilePath; + } + + public String getProtocolFlag() { + return protocolFlag; + } + + public void setProtocolFlag(String protocolFlag) { + this.protocolFlag = protocolFlag; + } + + public Properties getProps() { + return props; + } + + public void setProps(Properties props) { + this.props = props; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getAuthKey() { + return authKey; + } + + public void setAuthKey(String authKey) { + this.authKey = authKey; + } + + public String getAuthDate() { + return authDate; + } + + public void setAuthDate(String authDate) { + this.authDate = authDate; + } + + public String getfFilter() { + return fFilter; + } + + public void setfFilter(String fFilter) { + this.fFilter = fFilter; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java new file mode 100644 index 0000000..538f1e3 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +enum MRFormat +{ + /** + * Messages are sent using MR's message format. + */ + CAMBRIA + { + @Override + public String toString() { return "application/cambria"; } + }, + + /** + * Messages are sent using MR's message format with compression. + */ + CAMBRIA_ZIP + { + @Override + public String toString() { return "application/cambria-zip"; } + }, + + /** + * messages are sent as simple JSON objects. + */ + JSON + { + @Override + public String toString() { return "application/json"; } + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java new file mode 100644 index 0000000..9051b99 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java @@ -0,0 +1,266 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.Collection; +import java.util.Set; +import java.util.TreeSet; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import org.onap.dmaap.mr.client.MRIdentityManager; +import org.onap.dmaap.mr.client.MRTopicManager; + +public class MRMetaClient extends MRBaseClient implements MRTopicManager, MRIdentityManager +{ + private static final Logger logger = LoggerFactory.getLogger(MRMetaClient.class); + public MRMetaClient ( Collection baseUrls ) throws MalformedURLException + { + super ( baseUrls ); + } + + @Override + public Set getTopics () throws IOException + { + final TreeSet set = new TreeSet (); + try + { + final JSONObject topicSet = get ( "/topics" ); + final JSONArray a = topicSet.getJSONArray ( "topics" ); + for ( int i=0; i getAllowedProducers () + { + final JSONObject acl = topicData.optJSONObject ( "writerAcl" ); + if ( acl != null && acl.optBoolean ( "enabled", true ) ) + { + return jsonArrayToSet ( acl.optJSONArray ( "users" ) ); + } + return null; + } + + @Override + public Set getAllowedConsumers () + { + final JSONObject acl = topicData.optJSONObject ( "readerAcl" ); + if ( acl != null && acl.optBoolean ( "enabled", true ) ) + { + return jsonArrayToSet ( acl.optJSONArray ( "users" ) ); + } + return null; + } + }; + } + catch ( JSONException e ) + { + throw new IOException ( e ); + } + catch ( HttpException e ) + { + throw new IOException ( e ); + } + } + + @Override + public void createTopic ( String topicName, String topicDescription, int partitionCount, int replicationCount ) throws HttpException, IOException + { + final JSONObject o = new JSONObject (); + o.put ( "topicName", topicName ); + o.put ( "topicDescription", topicDescription ); + o.put ( "partitionCount", partitionCount ); + o.put ( "replicationCount", replicationCount ); + post ( "/topics/create", o, false ); + } + + @Override + public void deleteTopic ( String topic ) throws HttpException, IOException + { + delete ( "/topics/" + MRConstants.escape ( topic ) ); + } + + @Override + public boolean isOpenForProducing ( String topic ) throws HttpObjectNotFoundException, IOException + { + return null == getAllowedProducers ( topic ); + } + + @Override + public Set getAllowedProducers ( String topic ) throws HttpObjectNotFoundException, IOException + { + return getTopicMetadata ( topic ).getAllowedProducers (); + } + + @Override + public void allowProducer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException + { + put ( "/topics/" + MRConstants.escape ( topic ) + "/producers/" + MRConstants.escape ( apiKey ), new JSONObject() ); + } + + @Override + public void revokeProducer ( String topic, String apiKey ) throws HttpException, IOException + { + delete ( "/topics/" + MRConstants.escape ( topic ) + "/producers/" + MRConstants.escape ( apiKey ) ); + } + + @Override + public boolean isOpenForConsuming ( String topic ) throws HttpObjectNotFoundException, IOException + { + return null == getAllowedConsumers ( topic ); + } + + @Override + public Set getAllowedConsumers ( String topic ) throws HttpObjectNotFoundException, IOException + { + return getTopicMetadata ( topic ).getAllowedConsumers (); + } + + @Override + public void allowConsumer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException + { + put ( "/topics/" + MRConstants.escape ( topic ) + "/consumers/" + MRConstants.escape ( apiKey ), new JSONObject() ); + } + + @Override + public void revokeConsumer ( String topic, String apiKey ) throws HttpException, IOException + { + delete ( "/topics/" + MRConstants.escape ( topic ) + "/consumers/" + MRConstants.escape ( apiKey ) ); + } + + @Override + public ApiCredential createApiKey ( String email, String description ) throws HttpException, MRApiException, IOException + { + try + { + final JSONObject o = new JSONObject (); + o.put ( "email", email ); + o.put ( "description", description ); + final JSONObject reply = post ( "/apiKeys/create", o, true ); + return new ApiCredential ( reply.getString ( "key" ), reply.getString ( "secret" ) ); + } + catch ( JSONException e ) + { + // the response doesn't meet our expectation + throw new MRApiException ( "The API key response is incomplete.", e ); + } + } + + @Override + public ApiKey getApiKey ( String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException + { + final JSONObject keyEntry = get ( "/apiKeys/" + MRConstants.escape ( apiKey ) ); + if ( keyEntry == null ) + { + return null; + } + + return new ApiKey () + { + @Override + public String getEmail () + { + final JSONObject aux = keyEntry.optJSONObject ( "aux" ); + if ( aux != null ) + { + return aux.optString ( "email" ); + } + return null; + } + + @Override + public String getDescription () + { + final JSONObject aux = keyEntry.optJSONObject ( "aux" ); + if ( aux != null ) + { + return aux.optString ( "description" ); + } + return null; + } + }; + } + + @Override + public void updateCurrentApiKey ( String email, String description ) throws HttpObjectNotFoundException, HttpException, IOException + { + final JSONObject o = new JSONObject (); + if ( email != null ) o.put ( "email", email ); + if ( description != null ) o.put ( "description", description ); + patch ( "/apiKeys/" + MRConstants.escape ( getCurrentApiKey() ), o ); + } + + @Override + public void deleteCurrentApiKey () throws HttpException, IOException + { + delete ( "/apiKeys/" + MRConstants.escape ( getCurrentApiKey() ) ); + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java new file mode 100644 index 0000000..c5eb3ba --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java @@ -0,0 +1,927 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.zip.GZIPOutputStream; + +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.http.HttpException; +import org.apache.http.HttpStatus; +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.JSONTokener; + +import com.att.aft.dme2.api.DME2Client; +import com.att.aft.dme2.api.DME2Exception; +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; +import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; + +public class MRSimplerBatchPublisher extends MRBaseClient implements MRBatchingPublisher { + private static final Logger logger = LoggerFactory.getLogger(MRSimplerBatchPublisher.class); + + public static class Builder { + public Builder() { + } + + public Builder againstUrls(Collection baseUrls) { + fUrls = baseUrls; + return this; + } + + public Builder againstUrlsOrServiceName ( Collection baseUrls, Collection serviceName, String transportype ) + { + fUrls = baseUrls; + fServiceName = serviceName; + fTransportype = transportype; + return this; + } + + public Builder onTopic(String topic) { + fTopic = topic; + return this; + } + + public Builder batchTo(int maxBatchSize, long maxBatchAgeMs) { + fMaxBatchSize = maxBatchSize; + fMaxBatchAgeMs = maxBatchAgeMs; + return this; + } + + public Builder compress(boolean compress) { + fCompress = compress; + return this; + } + + public Builder httpThreadTime(int threadOccuranceTime) { + this.threadOccuranceTime = threadOccuranceTime; + return this; + } + + public Builder allowSelfSignedCertificates(boolean allowSelfSignedCerts) { + fAllowSelfSignedCerts = allowSelfSignedCerts; + return this; + } + + public Builder withResponse(boolean withResponse) { + fWithResponse = withResponse; + return this; + } + + public MRSimplerBatchPublisher build() { + if (!fWithResponse) { + try { + return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, + fAllowSelfSignedCerts, threadOccuranceTime); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } else { + try { + return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, + fAllowSelfSignedCerts, fMaxBatchSize); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } + + } + + private Collection fUrls; + private Collection fServiceName; + private String fTransportype; + private String fTopic; + private int fMaxBatchSize = 100; + private long fMaxBatchAgeMs = 1000; + private boolean fCompress = false; + private int threadOccuranceTime = 50; + private boolean fAllowSelfSignedCerts = false; + private boolean fWithResponse = false; + + }; + + @Override + public int send(String partition, String msg) { + return send(new message(partition, msg)); + } + + @Override + public int send(String msg) { + return send(new message(null, msg)); + } + + @Override + public int send(message msg) { + final LinkedList list = new LinkedList(); + list.add(msg); + return send(list); + } + + @Override + public synchronized int send(Collection msgs) { + if (fClosed) { + throw new IllegalStateException("The publisher was closed."); + } + + for (message userMsg : msgs) { + fPending.add(new TimestampedMessage(userMsg)); + } + return getPendingMessageCount(); + } + + @Override + public synchronized int getPendingMessageCount() { + return fPending.size(); + } + + @Override + public void close() { + try { + final List remains = close(Long.MAX_VALUE, TimeUnit.MILLISECONDS); + if (remains.isEmpty()) { + getLog().warn("Closing publisher with " + remains.size() + " messages unsent. " + + "Consider using MRBatchingPublisher.close( long timeout, TimeUnit timeoutUnits ) to recapture unsent messages on close."); + } + } catch (InterruptedException e) { + getLog().warn("Possible message loss. " + e.getMessage(), e); + Thread.currentThread().interrupt(); + } catch (IOException e) { + getLog().warn("Possible message loss. " + e.getMessage(), e); + } + } + + @Override + public List close(long time, TimeUnit unit) throws IOException, InterruptedException { + synchronized (this) { + fClosed = true; + + // stop the background sender + fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); + fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + fExec.shutdown(); + } + + final long now = Clock.now(); + final long waitInMs = TimeUnit.MILLISECONDS.convert(time, unit); + final long timeoutAtMs = now + waitInMs; + + while (Clock.now() < timeoutAtMs && getPendingMessageCount() > 0) { + send(true); + Thread.sleep(250); + } + + synchronized (this) { + final LinkedList result = new LinkedList(); + fPending.drainTo(result); + return result; + } + } + + /** + * Possibly send a batch to the MR server. This is called by the background + * thread and the close() method + * + * @param force + */ + private synchronized void send(boolean force) { + if (force || shouldSendNow()) { + if (!sendBatch()) { + getLog().warn("Send failed, " + fPending.size() + " message to send."); + + // note the time for back-off + fDontSendUntilMs = sfWaitAfterError + Clock.now(); + } + } + } + + private synchronized boolean shouldSendNow() { + boolean shouldSend = false; + if (fPending.isEmpty()) { + final long nowMs = Clock.now(); + + shouldSend = (fPending.size() >= fMaxBatchSize); + if (!shouldSend) { + final long sendAtMs = fPending.peek().timestamp + fMaxBatchAgeMs; + shouldSend = sendAtMs <= nowMs; + } + + // however, wait after an error + shouldSend = shouldSend && nowMs >= fDontSendUntilMs; + } + return shouldSend; + } + + /** + * Method to parse published JSON Objects and Arrays + * + * @return JSONArray + */ + private JSONArray parseJSON() { + JSONArray jsonArray = new JSONArray(); + for (TimestampedMessage m : fPending) { + JSONTokener jsonTokener = new JSONTokener(m.fMsg); + JSONObject jsonObject = null; + JSONArray tempjsonArray = null; + final char firstChar = jsonTokener.next(); + jsonTokener.back(); + if ('[' == firstChar) { + tempjsonArray = new JSONArray(jsonTokener); + if (null != tempjsonArray) { + for (int i = 0; i < tempjsonArray.length(); i++) { + jsonArray.put(tempjsonArray.getJSONObject(i)); + } + } + } else { + jsonObject = new JSONObject(jsonTokener); + jsonArray.put(jsonObject); + } + + } + return jsonArray; + } + + private synchronized boolean sendBatch() { + // it's possible for this call to be made with an empty list. in this + // case, just return. + if (fPending.size() < 1) { + return true; + } + + final long nowMs = Clock.now(); + + if (this.fHostSelector != null) { + host = this.fHostSelector.selectBaseHost(); + } + + final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"), + props.getProperty("partition")); + + try { + + final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); + OutputStream os = baseStream; + final String contentType = props.getProperty("contenttype"); + if (contentType.equalsIgnoreCase("application/json")) { + JSONArray jsonArray = parseJSON(); + os.write(jsonArray.toString().getBytes()); + os.close(); + + } else if (contentType.equalsIgnoreCase("text/plain")) { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + os.close(); + } else if (contentType.equalsIgnoreCase("application/cambria") + || (contentType.equalsIgnoreCase("application/cambria-zip"))) { + if (contentType.equalsIgnoreCase("application/cambria-zip")) { + os = new GZIPOutputStream(baseStream); + } + for (TimestampedMessage m : fPending) { + + os.write(("" + m.fPartition.length()).getBytes()); + os.write('.'); + os.write(("" + m.fMsg.length()).getBytes()); + os.write('.'); + os.write(m.fPartition.getBytes()); + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + os.close(); + } else { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + + } + os.close(); + } + + final long startMs = Clock.now(); + if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { + + DME2Configue(); + + Thread.sleep(5); + getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + sender.setPayload(os.toString()); + String dmeResponse = sender.sendAndWait(5000L); + + final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + dmeResponse.toString(); + getLog().info(logLine); + fPending.clear(); + return true; + } + + if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + final JSONObject result = postAuth(httpurl, baseStream.toByteArray(), contentType, authKey, authDate, + username, password, protocolFlag); + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + if (result.getInt("status") < 200 || result.getInt("status") > 299) { + return false; + } + final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); + getLog().info(logLine); + fPending.clear(); + return true; + } + + if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { + getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + final JSONObject result = post(httpurl, baseStream.toByteArray(), contentType, username, password, + protocolFlag); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + if (result.getInt("status") < 200 || result.getInt("status") > 299) { + return false; + } + final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); + getLog().info(logLine); + fPending.clear(); + return true; + } + + if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { + getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + final JSONObject result = postNoAuth(httpurl, baseStream.toByteArray(), contentType); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + if (result.getInt("status") < 200 || result.getInt("status") > 299) { + return false; + } + final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); + getLog().info(logLine); + fPending.clear(); + return true; + } + } catch (IllegalArgumentException x) { + getLog().warn(x.getMessage(), x); + } catch (IOException x) { + getLog().warn(x.getMessage(), x); + } catch (HttpException x) { + getLog().warn(x.getMessage(), x); + } catch (Exception x) { + getLog().warn(x.getMessage(), x); + } + return false; + } + + public synchronized MRPublisherResponse sendBatchWithResponse() { + // it's possible for this call to be made with an empty list. in this + // case, just return. + if (fPending.isEmpty()) { + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + pubResponse.setResponseMessage("No Messages to send"); + return pubResponse; + } + + final long nowMs = Clock.now(); + + host = this.fHostSelector.selectBaseHost(); + + final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"), + props.getProperty("partition")); + OutputStream os = null; + try { + + final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); + os = baseStream; + final String contentType = props.getProperty("contenttype"); + if (contentType.equalsIgnoreCase("application/json")) { + JSONArray jsonArray = parseJSON(); + os.write(jsonArray.toString().getBytes()); + } else if (contentType.equalsIgnoreCase("text/plain")) { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + } else if (contentType.equalsIgnoreCase("application/cambria") + || (contentType.equalsIgnoreCase("application/cambria-zip"))) { + if (contentType.equalsIgnoreCase("application/cambria-zip")) { + os = new GZIPOutputStream(baseStream); + } + for (TimestampedMessage m : fPending) { + + os.write(("" + m.fPartition.length()).getBytes()); + os.write('.'); + os.write(("" + m.fMsg.length()).getBytes()); + os.write('.'); + os.write(m.fPartition.getBytes()); + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + os.close(); + } else { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + + } + } + + final long startMs = Clock.now(); + if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { + + try { + DME2Configue(); + + Thread.sleep(5); + getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + sender.setPayload(os.toString()); + + String dmeResponse = sender.sendAndWait(5000L); + + pubResponse = createMRPublisherResponse(dmeResponse, pubResponse); + + if (Integer.valueOf(pubResponse.getResponseCode()) < 200 + || Integer.valueOf(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + final String logLine = String.valueOf((Clock.now() - startMs)) + dmeResponse.toString(); + getLog().info(logLine); + fPending.clear(); + + } catch (DME2Exception x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(x.getErrorCode()); + pubResponse.setResponseMessage(x.getErrorMessage()); + } catch (URISyntaxException x) { + + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + pubResponse.setResponseMessage(x.getMessage()); + } catch (Exception x) { + + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage(x.getMessage()); + logger.error("exception: ", x); + + } + + return pubResponse; + } + + if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + final String result = postAuthwithResponse(httpurl, baseStream.toByteArray(), contentType, authKey, + authDate, username, password, protocolFlag); + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + + pubResponse = createMRPublisherResponse(result, pubResponse); + + if (Integer.valueOf(pubResponse.getResponseCode()) < 200 + || Integer.valueOf(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + + final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString(); + getLog().info(logLine); + fPending.clear(); + return pubResponse; + } + + if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { + getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + final String result = postWithResponse(httpurl, baseStream.toByteArray(), contentType, username, + password, protocolFlag); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + pubResponse = createMRPublisherResponse(result, pubResponse); + + if (Integer.valueOf(pubResponse.getResponseCode()) < 200 + || Integer.valueOf(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + + final String logLine = String.valueOf((Clock.now() - startMs)); + getLog().info(logLine); + fPending.clear(); + return pubResponse; + } + + if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { + getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: " + + (nowMs - fPending.peek().timestamp) + " ms"); + final String result = postNoAuthWithResponse(httpurl, baseStream.toByteArray(), contentType); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + pubResponse = createMRPublisherResponse(result, pubResponse); + + if (Integer.valueOf(pubResponse.getResponseCode()) < 200 + || Integer.valueOf(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + + final String logLine = String.valueOf((Clock.now() - startMs)); + getLog().info(logLine); + fPending.clear(); + return pubResponse; + } + } catch (IllegalArgumentException x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + pubResponse.setResponseMessage(x.getMessage()); + + } catch (IOException x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage(x.getMessage()); + + } catch (HttpException x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + pubResponse.setResponseMessage(x.getMessage()); + + } catch (Exception x) { + getLog().warn(x.getMessage(), x); + + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage(x.getMessage()); + + } + + finally { + if (fPending.size() > 0) { + getLog().warn("Send failed, " + fPending.size() + " message to send."); + pubResponse.setPendingMsgs(fPending.size()); + } + if (os != null) { + try { + os.close(); + } catch (Exception x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage("Error in closing Output Stream"); + } + } + } + + return pubResponse; + } + + public MRPublisherResponse createMRPublisherResponse(String reply, MRPublisherResponse mrPubResponse) { + + if (reply.isEmpty()) { + + mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + mrPubResponse.setResponseMessage("Please verify the Producer properties"); + } else if (reply.startsWith("{")) { + JSONObject jObject = new JSONObject(reply); + if (jObject.has("message") && jObject.has("status")) { + String message = jObject.getString("message"); + if (null != message) { + mrPubResponse.setResponseMessage(message); + } + mrPubResponse.setResponseCode(Integer.toString(jObject.getInt("status"))); + } else { + mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK)); + mrPubResponse.setResponseMessage(reply); + } + } else if (reply.startsWith("<")) { + String responseCode = getHTTPErrorResponseCode(reply); + if (responseCode.contains("403")) { + responseCode = "403"; + } + mrPubResponse.setResponseCode(responseCode); + mrPubResponse.setResponseMessage(getHTTPErrorResponseMessage(reply)); + } + + return mrPubResponse; + } + + private final String fTopic; + private final int fMaxBatchSize; + private final long fMaxBatchAgeMs; + private final boolean fCompress; + private int threadOccuranceTime; + private boolean fClosed; + private String username; + private String password; + private String host; + + // host selector + private HostSelector fHostSelector = null; + + private final LinkedBlockingQueue fPending; + private long fDontSendUntilMs; + private final ScheduledThreadPoolExecutor fExec; + + private String latitude; + private String longitude; + private String version; + private String serviceName; + private String env; + private String partner; + private String routeOffer; + private String subContextPath; + private String protocol; + private String methodType; + private String url; + private String dmeuser; + private String dmepassword; + private String contentType; + private static final long sfWaitAfterError = 10000; + private HashMap DMETimeOuts; + private DME2Client sender; + public String protocolFlag = ProtocolTypeConstants.DME2.getValue(); + private String authKey; + private String authDate; + private String handlers; + private Properties props; + public static String routerFilePath; + protected static final Map headers = new HashMap(); + public static MultivaluedMap headersMap; + + private MRPublisherResponse pubResponse; + + public MRPublisherResponse getPubResponse() { + return pubResponse; + } + + public void setPubResponse(MRPublisherResponse pubResponse) { + this.pubResponse = pubResponse; + } + + public static String getRouterFilePath() { + return routerFilePath; + } + + public static void setRouterFilePath(String routerFilePath) { + MRSimplerBatchPublisher.routerFilePath = routerFilePath; + } + + public Properties getProps() { + return props; + } + + public void setProps(Properties props) { + this.props = props; + } + + public String getProtocolFlag() { + return protocolFlag; + } + + public void setProtocolFlag(String protocolFlag) { + this.protocolFlag = protocolFlag; + } + + private void DME2Configue() throws Exception { + try { + + latitude = props.getProperty("Latitude"); + longitude = props.getProperty("Longitude"); + version = props.getProperty("Version"); + serviceName = props.getProperty("ServiceName"); + env = props.getProperty("Environment"); + partner = props.getProperty("Partner"); + routeOffer = props.getProperty("routeOffer"); + subContextPath = props.getProperty("SubContextPath") + fTopic; + + protocol = props.getProperty("Protocol"); + methodType = props.getProperty("MethodType"); + dmeuser = props.getProperty("username"); + dmepassword = props.getProperty("password"); + contentType = props.getProperty("contenttype"); + handlers = props.getProperty("sessionstickinessrequired"); + routerFilePath = props.getProperty("DME2preferredRouterFilePath"); + + /** + * Changes to DME2Client url to use Partner for auto failover + * between data centers When Partner value is not provided use the + * routeOffer value for auto failover within a cluster + */ + + String partitionKey = props.getProperty("partition"); + + if (partner != null && !partner.isEmpty()) { + url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" + + partner; + if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { + url = url + "&partitionKey=" + partitionKey; + } + } else if (routeOffer != null && !routeOffer.isEmpty()) { + url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer=" + + routeOffer; + if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { + url = url + "&partitionKey=" + partitionKey; + } + } + + DMETimeOuts = new HashMap(); + DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); + DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS")); + DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); + DMETimeOuts.put("Content-Type", contentType); + System.setProperty("AFT_LATITUDE", latitude); + System.setProperty("AFT_LONGITUDE", longitude); + System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT")); + // System.setProperty("DME2.DEBUG", "true"); + + // SSL changes + // System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", + + System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2"); + System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false"); + System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit"); + + // SSL changes + + sender = new DME2Client(new URI(url), 5000L); + + sender.setAllowAllHttpReturnCodes(true); + sender.setMethod(methodType); + sender.setSubContext(subContextPath); + sender.setCredentials(dmeuser, dmepassword); + sender.setHeaders(DMETimeOuts); + if (handlers != null &&handlers.equalsIgnoreCase("yes")) { + sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", + props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS")); + sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", + props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS")); + sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON")); + } else { + sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler"); + } + } catch (DME2Exception x) { + getLog().warn(x.getMessage(), x); + throw new DME2Exception(x.getErrorCode(), x.getErrorMessage()); + } catch (URISyntaxException x) { + + getLog().warn(x.getMessage(), x); + throw new URISyntaxException(url, x.getMessage()); + } catch (Exception x) { + + getLog().warn(x.getMessage(), x); + throw new IllegalArgumentException(x.getMessage()); + } + } + + private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, + boolean compress) throws MalformedURLException { + super(hosts); + + if (topic == null || topic.length() < 1) { + throw new IllegalArgumentException("A topic must be provided."); + } + + fHostSelector = new HostSelector(hosts, null); + fClosed = false; + fTopic = topic; + fMaxBatchSize = maxBatchSize; + fMaxBatchAgeMs = maxBatchAgeMs; + fCompress = compress; + + fPending = new LinkedBlockingQueue(); + fDontSendUntilMs = 0; + fExec = new ScheduledThreadPoolExecutor(1); + pubResponse = new MRPublisherResponse(); + + } + + private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, + boolean compress, boolean allowSelfSignedCerts, int httpThreadOccurnace) throws MalformedURLException { + super(hosts); + + if (topic == null || topic.length() < 1) { + throw new IllegalArgumentException("A topic must be provided."); + } + + fHostSelector = new HostSelector(hosts, null); + fClosed = false; + fTopic = topic; + fMaxBatchSize = maxBatchSize; + fMaxBatchAgeMs = maxBatchAgeMs; + fCompress = compress; + threadOccuranceTime = httpThreadOccurnace; + fPending = new LinkedBlockingQueue(); + fDontSendUntilMs = 0; + fExec = new ScheduledThreadPoolExecutor(1); + fExec.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + send(false); + } + }, 100, threadOccuranceTime, TimeUnit.MILLISECONDS); + pubResponse = new MRPublisherResponse(); + } + + private static class TimestampedMessage extends message { + public TimestampedMessage(message m) { + super(m); + timestamp = Clock.now(); + } + + public final long timestamp; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getAuthKey() { + return authKey; + } + + public void setAuthKey(String authKey) { + this.authKey = authKey; + } + + public String getAuthDate() { + return authDate; + } + + public void setAuthDate(String authDate) { + this.authDate = authDate; + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java b/src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java new file mode 100644 index 0000000..5dc3da0 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.response; + +public class MRConsumerResponse { + + private String responseCode; + + private String responseMessage; + + private Iterable actualMessages; + + + + + public String getResponseCode() { + return responseCode; + } + + public void setResponseCode(String responseCode) { + this.responseCode = responseCode; + } + + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + + public Iterable getActualMessages() { + return actualMessages; + } + + public void setActualMessages(Iterable actualMessages) { + this.actualMessages = actualMessages; + } + + +} diff --git a/src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java b/src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java new file mode 100644 index 0000000..f0630be --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.response; + +/** + * Response for Publisher + * @author author + * + */ +public class MRPublisherResponse { + private String responseCode; + + private String responseMessage; + + private int pendingMsgs; + + public String getResponseCode() { + return responseCode; + } + + public void setResponseCode(String responseCode) { + this.responseCode = responseCode; + } + + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + + public int getPendingMsgs() { + return pendingMsgs; + } + + public void setPendingMsgs(int pendingMsgs) { + this.pendingMsgs = pendingMsgs; + } + + @Override + public String toString() { + return "Response Code:" + this.responseCode + "," + + "Response Message:" + this.responseMessage + "," + "Pending Messages Count" + + this.pendingMsgs; + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java new file mode 100644 index 0000000..a44d858 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.dme.client; + + + +import java.util.logging.Level; +import java.util.logging.Logger; + + +//import com.att.aft.dme2.api.util.DME2Constants; +//import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; +//import com.att.aft.dme2.api.util.LogMessage; +//import com.att.aft.dme2.api.util.LogUtil; +public class DefaultLoggingFailoverFaultHandler /*implements DME2FailoverFaultHandler*/ { + //TODO: This code may be enable in the future when we implement DME2FailoverFaultHandler interface + /** The logger. */ + + +// @Override + +// // LogUtil.INSTANCE.report(logger, Level.WARNING, LogMessage.SEP_FAILOVER, context.getService(),context.getRequestURL(),context.getRouteOffer(),context.getResponseCode(),context.getException()); +// } +// @Override +// /** +// * The DME2Exchange already has a log message when the route offer is failed over. We dont need to log it again here. +// */ + +// //noop +// + +} + diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java new file mode 100644 index 0000000..da0ba62 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.dme.client; + + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; +import com.att.aft.dme2.api.util.DME2ExchangeReplyHandler; +import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; + + + + + + public class HeaderReplyHandler implements DME2ExchangeReplyHandler { + + private Logger fLog = LoggerFactory.getLogger ( this.getClass().getName () ); + + + @Override public void handleFault(DME2ExchangeFaultContext responseData) { + // TODO Auto-generated method stub + + } + @Override public void handleEndpointFault(DME2ExchangeFaultContext responseData) { + // TODO Auto-generated method stub + + } +@Override public void handleReply(DME2ExchangeResponseContext responseData) { + + if(responseData != null) { + MRClientFactory.DME2HeadersMap=responseData.getResponseHeaders(); + if (responseData.getResponseHeaders().get("transactionId")!=null) + fLog.info("Transaction Id : " + responseData.getResponseHeaders().get("transactionId")); + + } +} + +} diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java new file mode 100644 index 0000000..967ccf3 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.dme.client; +import java.io.File; +import java.io.FileWriter; +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; +import com.att.aft.dme2.api.util.DME2ExchangeReplyHandler; +import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; + +public class PreferredRouteReplyHandler implements DME2ExchangeReplyHandler { + private Logger fLog = LoggerFactory.getLogger ( this.getClass().getName () ); + @Override public void handleReply(DME2ExchangeResponseContext responseData) { + + if(responseData != null) { + MRClientFactory.DME2HeadersMap=responseData.getResponseHeaders(); + if (responseData.getResponseHeaders().get("transactionId")!=null) + + fLog.info("Transaction_Id : " + responseData.getResponseHeaders().get("transactionId")); + + if(responseData.getRouteOffer() != null ){ + routeWriter("preferredRouteKey",responseData.getRouteOffer()); + + } + } +} + + @Override public void handleFault(DME2ExchangeFaultContext responseData) { + // TODO Auto-generated method stub + //StaticCache.getInstance().setHandleFaultInvoked(true); + } + @Override public void handleEndpointFault(DME2ExchangeFaultContext responseData) { + // TODO Auto-generated method stub + + } + public void routeWriter(String routeKey, String routeValue){ + + try(FileWriter routeWriter=new FileWriter(new File (MRSimplerBatchPublisher.routerFilePath))){ + routeWriter.write(routeKey+"="+routeValue); + routeWriter.close(); + + }catch(Exception ex){ + fLog.error("Reply Router Error " + ex); + } + + } +} diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java new file mode 100644 index 0000000..4c2e546 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.dme.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.aft.dme2.api.util.DME2ExchangeRequestContext; +import com.att.aft.dme2.api.util.DME2ExchangeRequestHandler; +import org.onap.dmaap.mr.client.MRClientFactory; + +public class PreferredRouteRequestHandler implements DME2ExchangeRequestHandler { + private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Override + public void handleRequest(DME2ExchangeRequestContext requestData) { + + if (requestData != null) { + + requestData.setPreferredRouteOffer(readRoute("preferredRouteKey")); + } + } + + public String readRoute(String routeKey) { + + try { + + MRClientFactory.prop.load(MRClientFactory.routeReader); + + } catch (Exception ex) { + logger.error("Request Router Error " + ex); + } + return MRClientFactory.prop.getProperty(routeKey); + } +} diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java b/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java new file mode 100644 index 0000000..6fb02a5 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.dme.client; + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.MultivaluedMap; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; + +import java.util.List; + +public class SimpleExampleConsumer { + + private static final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumer.class); + + private SimpleExampleConsumer() { + } + + public static void main(String[] args) { + + long count = 0; + long nextReport = 5000; + String key; + + final long startMs = System.currentTimeMillis(); + + try { + + final MRConsumer cc = MRClientFactory.createConsumer("D:\\SG\\consumer.properties"); + while (true) { + for (String msg : cc.fetch()) { + logger.debug("Message Received: " + msg); + } + // Header for DME2 Call. + MultivaluedMap headersMap = MRClientFactory.HTTPHeadersMap; + for (MultivaluedMap.Entry> entry : headersMap.entrySet()) { + key = entry.getKey(); + logger.debug("Header Key " + key); + logger.debug("Header Value " + headersMap.get(key)); + } + // Header for HTTP Call. + + Map dme2headersMap = MRClientFactory.DME2HeadersMap; + for (Map.Entry entry : dme2headersMap.entrySet()) { + key = entry.getKey(); + logger.debug("Header Key " + key); + logger.debug("Header Value " + dme2headersMap.get(key)); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + } + } + } catch (Exception x) { + logger.error(x.toString()); + } + } +} diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java b/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java new file mode 100644 index 0000000..edb3994 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.dme.client; + + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.core.MultivaluedMap; + +import org.json.JSONObject; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.message; + +/** + * An example of how to use the Java publisher. + * + * @author author + */ +public class SimpleExamplePublisher { + static String content = null; + static String messageSize = null; + static String transport = null; + static String messageCount = null; + + public void publishMessage(String producerFilePath) throws IOException, InterruptedException { + + // create our publisher + + // publish some messages + + + StringBuilder sb = new StringBuilder(); + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); + + if (content.equalsIgnoreCase("text/plain")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + for (int j = 0; j < Integer.parseInt(messageSize); j++) { + sb.append("T"); + } + + pub.send(sb.toString()); + } + } else if (content.equalsIgnoreCase("application/cambria")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + for (int j = 0; j < Integer.parseInt(messageSize); j++) { + sb.append("C"); + } + + pub.send("Key", sb.toString()); + } + } else if (content.equalsIgnoreCase("application/json")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + + final JSONObject msg12 = new JSONObject(); + msg12.put("Name", "DMaaP Reference Client to Test jason Message"); + + pub.send(msg12.toString()); + + } + } + + // ... + + // close the publisher to make sure everything's sent before exiting. + // The batching + // publisher interface allows the app to get the set of unsent messages. + // It could + // write them to disk, for example, to try to send them later. + /* final List stuck = pub.close(20, TimeUnit.SECONDS); + if (stuck.size() > 0) { + System.err.println(stuck.size() + " messages unsent"); + } else { + System.out.println("Clean exit; all messages sent."); + }*/ + + if (transport.equalsIgnoreCase("HTTP")) { + MultivaluedMap headersMap = MRClientFactory.HTTPHeadersMap; + for (String key : headersMap.keySet()) { + System.out.println("Header Key " + key); + System.out.println("Header Value " + headersMap.get(key)); + } + } else { + Map dme2headersMap = MRClientFactory.DME2HeadersMap; + for (String key : dme2headersMap.keySet()) { + System.out.println("Header Key " + key); + System.out.println("Header Value " + dme2headersMap.get(key)); + } + } + + } + + public static void main(String[] args) throws InterruptedException, Exception { + + String producerFilePath = args[0]; + content = args[1]; + messageSize = args[2]; + transport = args[3]; + messageCount = args[4]; + + + + + + SimpleExamplePublisher publisher = new SimpleExamplePublisher(); + + publisher.publishMessage("D:\\SG\\producer.properties"); + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/logging/MRAppender.java b/src/main/java/org/onap/dmaap/mr/logging/MRAppender.java new file mode 100644 index 0000000..8842b14 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/logging/MRAppender.java @@ -0,0 +1,165 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +/** + * + */ +package org.onap.dmaap.mr.logging; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher; + +/** + * @author author + * + */ +public class MRAppender extends AppenderSkeleton { + + private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private MRPublisher fPublisher; + + //Provided through log4j configuration + private String topic; + private String partition; + private String hosts; + private int maxBatchSize = 1; + private int maxAgeMs = 1000; + private boolean compress = false; + + /** + * + */ + public MRAppender() { + super(); + } + + /** + * @param isActive + */ + public MRAppender(boolean isActive) { + super(isActive); + } + + /* (non-Javadoc) + * @see org.apache.log4j.Appender#close() + */ + @Override + public void close() { + if (!this.closed) { + this.closed = true; + fPublisher.close(); + } + } + + /* (non-Javadoc) + * @see org.apache.log4j.Appender#requiresLayout() + */ + @Override + public boolean requiresLayout() { + return false; + } + + /* (non-Javadoc) + * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent) + */ + @Override + protected void append(LoggingEvent event) { + final String message; + + if (this.layout == null) { + message = event.getRenderedMessage(); + } else { + message = this.layout.format(event); + } + + try { + fPublisher.send(partition, message); + } catch (IOException e) { + logger.error("IOException: ", e); + } + } + + @Override + public void activateOptions() { + if (hosts != null && topic != null && partition != null) { + fPublisher = MRClientFactory.createBatchingPublisher(hosts.split(","), topic, maxBatchSize, maxAgeMs, compress); + } else { + logger.error("The Hosts, Topic, and Partition parameter are required to create a MR Log4J Appender"); + } + } + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public String getPartition() { + return partition; + } + + public void setPartition(String partition) { + this.partition = partition; + } + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + public int getMaxBatchSize() { + return maxBatchSize; + } + + public void setMaxBatchSize(int maxBatchSize) { + this.maxBatchSize = maxBatchSize; + } + + public int getMaxAgeMs() { + return maxAgeMs; + } + + public void setMaxAgeMs(int maxAgeMs) { + this.maxAgeMs = maxAgeMs; + } + + public boolean isCompress() { + return compress; + } + + public void setCompress(boolean compress) { + this.compress = compress; + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java b/src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java new file mode 100644 index 0000000..62e4cda --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.message; + +/** + * A simple publisher that reads from std in, sending each line as a message. + * @author author + */ +public class ConsolePublisher +{ + + private static final Logger logger = LoggerFactory.getLogger(ConsolePublisher.class); + private ConsolePublisher() { + } + public static void main ( String[] args ) throws IOException //throws IOException, InterruptedException + { + // read the hosts(s) from the command line + final String hosts = args.length > 0 ? args[0] : "aaa.it.att.com,bbb.it.att.com,ccc.it.att.com"; + + // read the topic name from the command line + final String topic = args.length > 1 ? args[1] : "TEST-TOPIC"; + + // read the topic name from the command line + final String partition = args.length > 2 ? args[2] : UUID.randomUUID ().toString (); + + // set up some batch limits and the compression flag + final int maxBatchSize = 100; + final long maxAgeMs = 250; + final boolean withGzip = false; + + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher ( hosts, topic, maxBatchSize, maxAgeMs, withGzip ); + + final BufferedReader cin = new BufferedReader ( new InputStreamReader ( System.in ) ); + try + { + String line = null; + while ( ( line = cin.readLine () ) != null ) + { + pub.send ( partition, line ); + } + } + finally + { + List leftovers = null; + try + { + leftovers = pub.close ( 10, TimeUnit.SECONDS ); + } + catch ( InterruptedException e ) + { + logger.error( "Send on close interrupted." ); + Thread.currentThread().interrupt(); + } + for ( message m : leftovers ) + { + logger.error( "Unsent message: " + m.fMsg ); + } + } + } +} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java b/src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java new file mode 100644 index 0000000..6ece7f7 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +/** + * + */ +package org.onap.dmaap.mr.test.clients; + +/** + * @author author + * + */ +public enum ProtocolTypeConstants { + + DME2("DME2"), AAF_AUTH("HTTPAAF"), AUTH_KEY("HTTPAUTH"), HTTPNOAUTH("HTTPNOAUTH"); + + private String value; + + private ProtocolTypeConstants(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java b/src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java new file mode 100644 index 0000000..1f78be1 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java @@ -0,0 +1,87 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.clients; + +import java.util.LinkedList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; + +public class SampleConsumer { + private SampleConsumer() { + } + public static void main ( String[] args ) + { + final Logger log = LoggerFactory.getLogger(SampleConsumer.class); + + + log.info("Sample Consumer Class executing"); + final String topic = "com.att.app.dmaap.mr.testingTopic"; + final String url = ( args.length > 1 ? args[1] : "localhost:8181" ); + final String group = ( args.length > 2 ? args[2] :"grp" ); + + final String id = ( args.length > 3 ? args[3] : "1" ); + + long count = 0; + long nextReport = 5000; + + final long startMs = System.currentTimeMillis (); + + final LinkedList urlList = new LinkedList<> (); + for ( String u : url.split ( "," ) ) + { + urlList.add ( u ); + } + + final MRConsumer cc = MRClientFactory.createConsumer ( urlList, topic, group, id, 10*1000, 1000, null, "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88" ); + try + { + while ( true ) + { + for ( String msg : cc.fetch () ) + { + log.info ( "" + (++count) + ": " + msg ); + } + + if ( count > nextReport ) + { + nextReport += 5000; + + final long endMs = System.currentTimeMillis (); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + log.info ( "Consumed " + count + " in " + elapsedSec + "; " + eps + " eps" ); + } + log.info ( "" + (++count) + ": consumed message" ); + } + } + catch ( Exception x ) + { + log.error( x.getClass().getName () + ": " + x.getMessage () ); + throw new IllegalArgumentException(x); + } + } +} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java b/src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java new file mode 100644 index 0000000..29d7f85 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.clients; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRClientBuilders.PublisherBuilder; +import org.onap.dmaap.mr.client.MRPublisher.message; + +public class SamplePublisher { + public static void main ( String[] args ) throws IOException, InterruptedException + { + final Logger LOG = LoggerFactory.getLogger(SampleConsumer.class); + // read the hosts(s) from the command line + final String hosts = ( args.length > 0 ? args[0] : "localhost:8181" ); + + // read the topic name from the command line + + final String topic = ( args.length > 1 ? args[1] : "com.att.app.dmaap.mr.testingTopic" ); + + // set up some batch limits and the compression flag + final int maxBatchSize = 100; + final int maxAgeMs = 250; + final boolean withGzip = false; + + // create our publisher + + final MRBatchingPublisher pub = new PublisherBuilder (). + usingHosts ( hosts ). + onTopic ( topic ).limitBatch(maxBatchSize, maxAgeMs). + authenticatedBy ( "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88" ). + build () + ; + // publish some messages + final JSONObject msg1 = new JSONObject (); + msg1.put ( "name", "tttttttttttttttt" ); + msg1.put ( "greeting", "ooooooooooooooooo" ); + pub.send ( "MyPartitionKey", msg1.toString () ); + + final JSONObject msg2 = new JSONObject (); + msg2.put ( "now", System.currentTimeMillis () ); + pub.send ( "MyOtherPartitionKey", msg2.toString () ); + + // ... + + // close the publisher to make sure everything's sent before exiting. The batching + // publisher interface allows the app to get the set of unsent messages. It could + // write them to disk, for example, to try to send them later. + final List stuck = pub.close ( 20, TimeUnit.SECONDS ); + if ( stuck.isEmpty()) + { + LOG.warn ( stuck.size() + " messages unsent" ); + } + else + { + LOG.info ( "Clean exit; all messages sent." ); + } + } +} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java new file mode 100644 index 0000000..a7f283c --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; + +public class SimpleExampleConsumer { + + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public static void main(String[] args) { + final Logger LOG = LoggerFactory.getLogger(SimpleExampleConsumer.class); + + long count = 0; + long nextReport = 5000; + + final long startMs = System.currentTimeMillis(); + + try { + String routeFilePath = "/src/main/resources/dme2/preferredRoute.txt"; + + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + final MRConsumer cc = MRClientFactory.createConsumer("/src/main/resources/dme2/consumer.properties"); + int i = 0; + while (i < 10) { + Thread.sleep(2); + i++; + for (String msg : cc.fetch()) { + // System.out.println ( "" + (++count) + ": " + msg ); + System.out.println(msg); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + System.out.println("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); + } + } + } catch (Exception x) { + System.err.println(x.getClass().getName() + ": " + x.getMessage()); + LOG.error("exception: ", x); + } + } +} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java new file mode 100644 index 0000000..2e514b0 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.clients; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; + +public class SimpleExampleConsumerWithReturnResponse { + + private static final Logger LOG = LoggerFactory.getLogger(SimpleExampleConsumerWithReturnResponse.class); + + static FileWriter routeWriter= null; + static Properties props=null; + static FileReader routeReader=null; + public static void main ( String[] args ) + { + + long count = 0; + long nextReport = 5000; + + final long startMs = System.currentTimeMillis (); + + try + { + String routeFilePath="src/main/resources/dme2/preferredRoute.txt"; + + + File fo= new File(routeFilePath); + if(!fo.exists()){ + routeWriter=new FileWriter(new File (routeFilePath)); + } + routeReader= new FileReader(new File (routeFilePath)); + props= new Properties(); + final MRConsumer cc = MRClientFactory.createConsumer ( "src/main/resources/dme2/consumer.properties" ); + while ( true ) + { + MRConsumerResponse mrConsumerResponse = cc.fetchWithReturnConsumerResponse(); + System.out.println("mrConsumerResponse code :"+mrConsumerResponse.getResponseCode()); + + System.out.println("mrConsumerResponse Message :"+mrConsumerResponse.getResponseMessage()); + + System.out.println("mrConsumerResponse ActualMessage :"+mrConsumerResponse.getActualMessages()); + /*for ( String msg : mrConsumerResponse.getActualMessages() ) + { + //System.out.println ( "" + (++count) + ": " + msg ); + System.out.println(msg); + }*/ + if ( count > nextReport ) + { + nextReport += 5000; + + final long endMs = System.currentTimeMillis (); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + System.out.println ( "Consumed " + count + " in " + elapsedSec + "; " + eps + " eps" ); + } + } + } + catch ( Exception x ) + { + System.err.println ( x.getClass().getName () + ": " + x.getMessage () ); + LOG.error("exception: ", x); + } + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java new file mode 100644 index 0000000..770d916 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import org.json.JSONObject; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.message; + +/** + * An example of how to use the Java publisher. + * @author author + */ +public class SimpleExamplePublisher +{ + static FileWriter routeWriter= null; + static Properties props=null; + static FileReader routeReader=null; + public void publishMessage ( String producerFilePath ) throws IOException, InterruptedException, Exception + { + + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath); + // publish some messages + final JSONObject msg1 = new JSONObject (); + msg1.put ( "Name", "Sprint" ); + + pub.send ( "First cambria messge" ); + pub.send ( "MyPartitionKey", msg1.toString () ); + + final JSONObject msg2 = new JSONObject (); + + + + // ... + + // close the publisher to make sure everything's sent before exiting. The batching + // publisher interface allows the app to get the set of unsent messages. It could + // write them to disk, for example, to try to send them later. + final List stuck = pub.close ( 20, TimeUnit.SECONDS ); + if ( stuck.isEmpty() ) + { + System.err.println ( stuck.size() + " messages unsent" ); + } + else + { + System.out.println ( "Clean exit; all messages sent." ); + } + } + + public static void main(String []args) throws InterruptedException, Exception{ + + String routeFilePath="/src/main/resources/dme2/preferredRoute.txt"; + + SimpleExamplePublisher publisher = new SimpleExamplePublisher(); + + + File fo= new File(routeFilePath); + if(!fo.exists()){ + routeWriter=new FileWriter(new File (routeFilePath)); + } + routeReader= new FileReader(new File (routeFilePath)); + props= new Properties(); + publisher.publishMessage("/src/main/resources/dme2/producer.properties"); + } + +} + diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java new file mode 100644 index 0000000..33d1164 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.clients; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; + /** + *An example of how to use the Java publisher. + * @author author + * + */ + public class SimpleExamplePublisherWithResponse + { + static FileWriter routeWriter= null; + static Properties props=null; + static FileReader routeReader=null; + + public static void main(String []args) throws InterruptedException, Exception{ + + String routeFilePath="src/main/resources/dme2/preferredRoute.txt"; + String msgCount = args[0]; + SimpleExamplePublisherWithResponse publisher = new SimpleExamplePublisherWithResponse(); + File fo= new File(routeFilePath); + if(!fo.exists()){ + routeWriter=new FileWriter(new File (routeFilePath)); + } + routeReader= new FileReader(new File (routeFilePath)); + props= new Properties(); + int i=0; + while (i< Integer.valueOf(msgCount)) + { + publisher.publishMessage("src/main/resources/dme2/producer.properties",Integer.valueOf(msgCount)); + i++; + } + } + + public void publishMessage ( String producerFilePath , int count ) throws IOException, InterruptedException + { + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath,true); + // publish some messages + final JSONObject msg1 = new JSONObject (); + + msg1.put ( "Partition:1", "Message:"+count); + msg1.put ( "greeting", "Hello .." ); + + + pub.send ( "1", msg1.toString()); + pub.send ( "1", msg1.toString()); + + MRPublisherResponse res= pub.sendBatchWithResponse(); + + System.out.println("Pub response->"+res.toString()); + } + + + } diff --git a/src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java b/src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java new file mode 100644 index 0000000..3e64c35 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java @@ -0,0 +1,184 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.support; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; + +/** + * A helper for unit testing systems that use a MRPublisher. When setting + * up your test, inject an instance into MRClientFactory to have it return + * the mock client. + * + * @author author + * + */ +public class MRBatchingPublisherMock implements MRBatchingPublisher +{ + public class Entry + { + public Entry ( String partition, String msg ) + { + fPartition = partition; + fMessage = msg; + } + + @Override + public String toString () + { + return fMessage; + } + + public final String fPartition; + public final String fMessage; + } + + public MRBatchingPublisherMock () + { + fCaptures = new LinkedList<> (); + } + + public interface Listener + { + void onMessage ( Entry e ); + } + public void addListener ( Listener listener ) + { + fListeners.add ( listener ); + } + + public List getCaptures () + { + return getCaptures ( new MessageFilter () { @Override public boolean match ( String msg ) { return true; } } ); + } + + public interface MessageFilter + { + boolean match ( String msg ); + } + + public List getCaptures ( MessageFilter filter ) + { + final LinkedList result = new LinkedList<> (); + for ( Entry capture : fCaptures ) + { + if ( filter.match ( capture.fMessage ) ) + { + result.add ( capture ); + } + } + return result; + } + + public int received () + { + return fCaptures.size(); + } + + public void reset () + { + fCaptures.clear (); + } + + @Override + public int send ( String partition, String msg ) + { + final Entry e = new Entry ( partition, msg ); + + fCaptures.add ( e ); + for ( Listener l : fListeners ) + { + l.onMessage ( e ); + } + return 1; + } + + @Override + public int send ( message msg ) + { + return send ( msg.fPartition, msg.fMsg ); + } + @Override + public int send ( String msg ) + { + return 1; + + } + + @Override + public int send ( Collection msgs ) + { + int sum = 0; + for ( message m : msgs ) + { + sum += send ( m ); + } + return sum; + } + + @Override + public int getPendingMessageCount () + { + return 0; + } + + @Override + public List close ( long timeout, TimeUnit timeoutUnits ) + { + return new LinkedList<> (); + } + + @Override + public void close () + { + } + + @Override + public void setApiCredentials ( String apiKey, String apiSecret ) + { + } + + @Override + public void clearApiCredentials () + { + } + + @Override + public void logTo ( Logger log ) + { + } + + private final LinkedList fCaptures; + private LinkedList fListeners = new LinkedList<> (); + @Override + public MRPublisherResponse sendBatchWithResponse() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java b/src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java new file mode 100644 index 0000000..afa36ea --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java @@ -0,0 +1,169 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.support; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import org.slf4j.Logger; + +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; + +/** + * A helper for unit testing systems that use a MRConsumer. When setting + * up your test, inject an instance into MRClientFactory to have it return + * the mock client. + * + * @author author + * + */ +public class MRConsumerMock implements MRConsumer +{ + public class Entry + { + public Entry ( long waitMs, int statusCode, List msgs ) + { + fWaitMs = waitMs; + fStatusCode = statusCode; + fStatusMsg = null; + fMsgs = new LinkedList<> ( msgs ); + } + + public Entry ( long waitMs, int statusCode, String statusMsg ) + { + fWaitMs = waitMs; + fStatusCode = statusCode; + fStatusMsg = statusMsg; + fMsgs = null; + } + + public LinkedList run () throws IOException + { + try + { + Thread.sleep ( fWaitMs ); + if ( fStatusCode >= 200 && fStatusCode <= 299 ) + { + return fMsgs; + } + throw new IOException ( "" + fStatusCode + " " + fStatusMsg ); + } + catch ( InterruptedException e ) + { + Thread.currentThread().interrupt(); + throw new IOException ( e ); + } + } + + private final long fWaitMs; + private final int fStatusCode; + private final String fStatusMsg; + private final LinkedList fMsgs; + } + + public MRConsumerMock () + { + fReplies = new LinkedList<> (); + } + + @Override + public void close () + { + } + + @Override + public void setApiCredentials ( String apiKey, String apiSecret ) + { + } + + @Override + public void clearApiCredentials () + { + } + + public synchronized void add ( Entry e ) + { + fReplies.add ( e ); + } + + public void addImmediateMsg ( String msg ) + { + addDelayedMsg ( 0, msg ); + } + + public void addDelayedMsg ( long delay, String msg ) + { + final LinkedList list = new LinkedList<> (); + list.add ( msg ); + add ( new Entry ( delay, 200, list ) ); + } + + public void addImmediateMsgGroup ( List msgs ) + { + addDelayedMsgGroup ( 0, msgs ); + } + + public void addDelayedMsgGroup ( long delay, List msgs ) + { + final LinkedList list = new LinkedList<> ( msgs ); + add ( new Entry ( delay, 200, list ) ); + } + + public void addImmediateError ( int statusCode, String statusText ) + { + add ( new Entry ( 0, statusCode, statusText ) ); + } + + @Override + public Iterable fetch () throws IOException + { + return fetch ( -1, -1 ); + } + + @Override + public Iterable fetch ( int timeoutMs, int limit ) throws IOException + { + return fReplies.size () > 0 ? fReplies.removeFirst ().run() : new LinkedList(); + } + + @Override + public void logTo ( Logger log ) + { + } + + private final LinkedList fReplies; + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse() { + // TODO Auto-generated method stub + return null; + } + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, + int limit) { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java b/src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java new file mode 100644 index 0000000..a2396d8 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.io.IOException; +import java.io.PrintStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRIdentityManager; +import org.onap.dmaap.mr.client.MRClient.MRApiException; +import org.onap.dmaap.mr.client.MRIdentityManager.ApiKey; + +public class ApiKeyCommand implements Command +{ + final Logger log = LoggerFactory.getLogger(ApiKeyCommand.class); + @Override + public String[] getMatches () + { + return new String[]{ + "key (create|update) (\\S*) (\\S*)", + "key (list) (\\S*)", + "key (revoke)", + }; + } + + @Override + public void checkReady ( MRCommandContext context ) throws CommandNotReadyException + { + if ( !context.checkClusterReady () ) + { + throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); + } + } + + @Override + public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException + { + final MRIdentityManager tm = MRClientFactory.createIdentityManager ( context.getCluster(), context.getApiKey(), context.getApiPwd() ); + context.applyTracer ( tm ); + + try + { + if ( parts[0].equals ( "list" ) ) + { + final ApiKey key = tm.getApiKey ( parts[1] ); + if ( key != null ) + { + out.println ( "email: " + key.getEmail () ); + out.println ( "description: " + key.getDescription () ); + } + else + { + out.println ( "No key returned" ); + } + } + else if ( parts[0].equals ( "create" ) ) + { + final ApiCredential ac = tm.createApiKey ( parts[1], parts[2] ); + if ( ac != null ) + { + out.println ( " key: " + ac.getApiKey () ); + out.println ( "secret: " + ac.getApiSecret () ); + } + else + { + out.println ( "No credential returned?" ); + } + } + else if ( parts[0].equals ( "update" ) ) + { + tm.updateCurrentApiKey ( parts[1], parts[2] ); + out.println ( "Updated" ); + } + else if ( parts[0].equals ( "revoke" ) ) + { + tm.deleteCurrentApiKey (); + out.println ( "Updated" ); + } + } + catch ( HttpObjectNotFoundException e ) + { + out.println ( "Object not found: " + e.getMessage () ); + log.error("HttpObjectNotFoundException: ", e); + } + catch ( HttpException e ) + { + out.println ( "HTTP exception: " + e.getMessage () ); + log.error("HttpException: ", e); + } + catch ( MRApiException e ) + { + out.println ( "API exception: " + e.getMessage () ); + log.error("MRApiException: ", e); + } + catch ( IOException e ) + { + out.println ( "IO exception: " + e.getMessage () ); + log.error("IOException: ", e); + } + finally + { + tm.close (); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "key create " ); + out.println ( "key update " ); + out.println ( "key list " ); + out.println ( "key revoke" ); + } +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java b/src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java new file mode 100644 index 0000000..26a70f0 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.io.PrintStream; + +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; + +public class AuthCommand implements Command +{ + @Override + public void checkReady ( MRCommandContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException + { + if ( parts.length > 0 ) + { + context.setAuth ( parts[0], parts[1] ); + out.println ( "Now authenticating with " + parts[0] ); + } + else + { + context.clearAuth (); + out.println ( "No longer authenticating." ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "auth " ); + out.println ( "\tuse these credentials on subsequent transactions" ); + out.println ( "noauth" ); + out.println ( "\tdo not use credentials on subsequent transactions" ); + } + + @Override + public String[] getMatches () + { + return new String[] + { + "auth (\\S*) (\\S*)", + "noauth" + }; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java b/src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java new file mode 100644 index 0000000..c4ef5e4 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.io.PrintStream; + +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.impl.MRConsumerImpl; + +public class ClusterCommand implements Command +{ + + @Override + public String[] getMatches () + { + return new String[]{ + "cluster", + "cluster (\\S*)?", + }; + } + + @Override + public void checkReady ( MRCommandContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException + { + if ( parts.length == 0 ) + { + for ( String host : context.getCluster () ) + { + out.println ( host ); + } + } + else + { + context.clearCluster (); + for ( String part : parts ) + { + String[] hosts = part.trim().split ( "\\s+" ); + for ( String host : hosts ) + { + for ( String splitHost : MRConsumerImpl.stringToList(host) ) + { + context.addClusterHost ( splitHost ); + } + } + } + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "cluster host1 host2 ..." ); + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java b/src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java new file mode 100644 index 0000000..5d13b30 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.util.Collection; +import java.util.LinkedList; + +import com.att.nsa.apiClient.http.HttpClient; +import com.att.nsa.apiClient.http.HttpTracer; +import com.att.nsa.cmdtool.CommandContext; +import org.onap.dmaap.mr.client.MRClient; + +public class MRCommandContext implements CommandContext +{ + public MRCommandContext () + { + fApiKey = null; + fApiPwd = null; + + fCluster = new LinkedList<> (); + fCluster.add ( "localhost" ); + } + + @Override + public void requestShutdown () + { + fShutdown = true; + } + + @Override + public boolean shouldContinue () + { + return !fShutdown; + } + + public void setAuth ( String key, String pwd ) { fApiKey = key; fApiPwd = pwd; } + public void clearAuth () { setAuth(null,null); } + + public boolean checkClusterReady () + { + return ( fCluster.isEmpty()); + } + + public Collection getCluster () + { + return new LinkedList<> ( fCluster ); + } + + public void clearCluster () + { + fCluster.clear (); + } + + public void addClusterHost ( String host ) + { + fCluster.add ( host ); + } + + public String getApiKey () { return fApiKey; } + public String getApiPwd () { return fApiPwd; } + + public void useTracer ( HttpTracer t ) + { + fTracer = t; + } + public void noTracer () { fTracer = null; } + + public void applyTracer ( MRClient cc ) + { + if ( cc instanceof HttpClient && fTracer != null ) + { + ((HttpClient)cc).installTracer ( fTracer ); + } + } + + private boolean fShutdown; + private String fApiKey; + private String fApiPwd; + private final LinkedList fCluster; + private HttpTracer fTracer = null; +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/MRTool.java b/src/main/java/org/onap/dmaap/mr/tools/MRTool.java new file mode 100644 index 0000000..a37fa79 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/MRTool.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.io.IOException; + +import com.att.nsa.cmdtool.CommandLineTool; +import org.onap.dmaap.mr.client.impl.MRClientVersionInfo; + +public class MRTool extends CommandLineTool +{ + protected MRTool () + { + super ( "MR Tool (" + MRClientVersionInfo.getVersion () + ")", "MR> " ); + + registerCommand ( new ApiKeyCommand () ); + registerCommand ( new AuthCommand () ); + registerCommand ( new ClusterCommand () ); + registerCommand ( new MessageCommand () ); + registerCommand ( new TopicCommand () ); + registerCommand ( new TraceCommand () ); + } + + public static void main ( String[] args ) throws IOException + { + final MRTool ct = new MRTool (); + final MRCommandContext ccc = new MRCommandContext (); + ct.runFromMain ( args, ccc ); + } +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java b/src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java new file mode 100644 index 0000000..5016c95 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.MRClientBuilders.PublisherBuilder; +import org.onap.dmaap.mr.client.MRPublisher.message; + +public class MessageCommand implements Command +{ + final Logger logger = LoggerFactory.getLogger(ApiKeyCommand.class); + @Override + public String[] getMatches () + { + return new String[]{ + "(post) (\\S*) (\\S*) (.*)", + "(read) (\\S*) (\\S*) (\\S*)", + }; + } + + @Override + public void checkReady ( MRCommandContext context ) throws CommandNotReadyException + { + if ( !context.checkClusterReady () ) + { + throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); + } + } + + @Override + public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException + { + if ( parts[0].equalsIgnoreCase ( "read" )) + { + final MRConsumer cc = MRClientFactory.createConsumer ( context.getCluster (), parts[1], parts[2], parts[3], + -1, -1, null, context.getApiKey(), context.getApiPwd() ); + context.applyTracer ( cc ); + try + { + for ( String msg : cc.fetch () ) + { + out.println ( msg ); + } + } + catch ( Exception e ) + { + out.println ( "Problem fetching messages: " + e.getMessage() ); + logger.error("Problem fetching messages: ", e); + } + finally + { + cc.close (); + } + } + else + { + final MRBatchingPublisher pub=ToolsUtil.createBatchPublisher(context, parts[1]); + try + { + pub.send ( parts[2], parts[3] ); + } + catch ( IOException e ) + { + out.println ( "Problem sending message: " + e.getMessage() ); + logger.error("Problem sending message: ", e); + } + finally + { + List left = null; + try + { + left = pub.close ( 500, TimeUnit.MILLISECONDS ); + } + catch ( IOException e ) + { + out.println ( "Problem sending message: " + e.getMessage() ); + logger.error("Problem sending message: ", e); + } + catch ( InterruptedException e ) + { + out.println ( "Problem sending message: " + e.getMessage() ); + logger.error("Problem sending message: ", e); + Thread.currentThread().interrupt(); + } + if ( left != null && left.isEmpty() ) + { + out.println ( left.size() + " messages not sent." ); + } + } + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "post " ); + out.println ( "read " ); + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java b/src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java new file mode 100644 index 0000000..72e7fbf --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientBuilders.PublisherBuilder; + +public final class ToolsUtil { + + private ToolsUtil() { + } + + public static MRBatchingPublisher createBatchPublisher(MRCommandContext context,String topicName){ + + return new PublisherBuilder (). + usingHosts ( context.getCluster () ). + onTopic (topicName). + authenticatedBy ( context.getApiKey(), context.getApiPwd() ). + build (); + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java b/src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java new file mode 100644 index 0000000..278b04f --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java @@ -0,0 +1,221 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRTopicManager; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; + +public class TopicCommand implements Command +{ + final Logger logger = LoggerFactory.getLogger(ApiKeyCommand.class); + @Override + public String[] getMatches () + { + return new String[]{ + "topic (list)", + "topic (list) (\\S*)", + "topic (create) (\\S*) (\\S*) (\\S*)", + "topic (grant|revoke) (read|write) (\\S*) (\\S*)", + }; + } + + @Override + public void checkReady ( MRCommandContext context ) throws CommandNotReadyException + { + if ( !context.checkClusterReady () ) + { + throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); + } + } + + @Override + public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException + { + final MRTopicManager tm = MRClientFactory.createTopicManager ( context.getCluster(), context.getApiKey(), context.getApiPwd() ); + context.applyTracer ( tm ); + + try + { + if ( parts[0].equals ( "list" ) ) + { + try + { + if ( parts.length == 1 ) + { + for ( String topic : tm.getTopics () ) + { + out.println ( topic ); + } + } + else + { + final TopicInfo ti = tm.getTopicMetadata ( parts[1] ); + + final String owner = ti.getOwner (); + out.println ( " owner: " + ( owner == null ? "" : owner ) ); + + final String desc = ti.getDescription (); + out.println ( "description: " + ( desc == null ? "" : desc ) ); + + final Set prods = ti.getAllowedProducers (); + if ( prods != null ) + { + out.println ( " write ACL: " ); + for ( String key : prods ) + { + out.println ( "\t" + key ); + } + } + else + { + out.println ( " write ACL: " ); + } + + final Set cons = ti.getAllowedConsumers (); + if ( cons != null ) + { + out.println ( " read ACL: " ); + for ( String key : cons ) + { + out.println ( "\t" + key ); + } + } + else + { + out.println ( " read ACL: " ); + } + } + } + catch ( IOException x ) + { + out.println ( "Problem with request: " + x.getMessage () ); + logger.error("IOException: ", x); + } + catch ( HttpObjectNotFoundException e ) + { + out.println ( "Not found: " + e.getMessage () ); + logger.error("HttpObjectNotFoundException: ", e); + } + } + else if ( parts[0].equals ( "create" ) ) + { + try + { + final int partitions = Integer.parseInt ( parts[2] ); + final int replicas = Integer.parseInt ( parts[3] ); + + tm.createTopic ( parts[1], "", partitions, replicas ); + } + catch ( HttpException e ) + { + out.println ( "Problem with request: " + e.getMessage () ); + logger.error("HttpException: ", e); + } + catch ( IOException e ) + { + out.println ( "Problem with request: " + e.getMessage () ); + logger.error("IOException: ", e); + } + catch ( NumberFormatException e ) + { + out.println ( "Problem with request: " + e.getMessage () ); + logger.error("NumberFormatException: ", e); + } + } + else if ( parts[0].equals ( "grant" ) ) + { + try + { + if ( parts[1].equals ( "write" ) ) + { + tm.allowProducer ( parts[2], parts[3] ); + } + else if ( parts[1].equals ( "read" ) ) + { + tm.allowConsumer ( parts[2], parts[3] ); + } + } + catch ( HttpException e ) + { + out.println ( "Problem with request: " + e.getMessage () ); + logger.error("HttpException: ", e); + } + catch ( IOException e ) + { + out.println ( "Problem with request: " + e.getMessage () ); + logger.error("IOException: ", e); + } + } + else if ( parts[0].equals ( "revoke" ) ) + { + try + { + if ( parts[1].equals ( "write" ) ) + { + tm.revokeProducer ( parts[2], parts[3] ); + } + else if ( parts[1].equals ( "read" ) ) + { + tm.revokeConsumer ( parts[2], parts[3] ); + } + } + catch ( HttpException e ) + { + out.println ( "Problem with request: " + e.getMessage () ); + logger.error("HttpException: ", e); + } + catch ( IOException e ) + { + out.println ( "Problem with request: " + e.getMessage () ); + logger.error("IOException: ", e); + } + } + } + finally + { + tm.close (); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "topic list" ); + out.println ( "topic list " ); + out.println ( "topic create " ); + out.println ( "topic grant write|read " ); + out.println ( "topic revoke write|read " ); + } + +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java b/src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java new file mode 100644 index 0000000..95edf5b --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.io.PrintStream; +import java.net.URI; +import java.util.List; +import java.util.Map; + +import com.att.nsa.apiClient.http.HttpTracer; +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; + +public class TraceCommand implements Command +{ + @Override + public void checkReady ( MRCommandContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, MRCommandContext context, final PrintStream out ) throws CommandNotReadyException + { + if ( parts[0].equalsIgnoreCase ( "on" )) + { + context.useTracer ( new HttpTracer () + { + @Override + public void outbound ( URI uri, Map> headers, String method, byte[] entity ) + { + out.println ( kLineBreak ); + out.println ( ">>> " + method + " " + uri.toString() ); + for ( Map.Entry> e : headers.entrySet () ) + { + final StringBuffer vals = new StringBuffer (); + for ( String val : e.getValue () ) + { + if ( vals.length () > 0 ) vals.append ( ", " ); + vals.append ( val ); + } + out.println ( ">>> " + e.getKey () + ": " + vals.toString() ); + } + if ( entity != null ) + { + out.println (); + out.println ( new String ( entity ) ); + } + out.println ( kLineBreak ); + } + + @Override + public void inbound ( Map> headers, int statusCode, String responseLine, byte[] entity ) + { + out.println ( kLineBreak ); + out.println ( "<<< " + responseLine ); + for ( Map.Entry> e : headers.entrySet () ) + { + final StringBuffer vals = new StringBuffer (); + for ( String val : e.getValue () ) + { + if ( vals.length () > 0 ) vals.append ( ", " ); + vals.append ( val ); + } + out.println ( "<<< " + e.getKey () + ": " + vals.toString() ); + } + if ( entity != null ) + { + out.println (); + out.println ( new String ( entity ) ); + } + out.println ( kLineBreak ); + } + } ); + } + else + { + context.noTracer (); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "trace on|off" ); + out.println ( "\tWhen trace is on, HTTP interaction is printed to the console." ); + } + + @Override + public String[] getMatches () + { + return new String[] + { + "trace (on)", + "trace (off)" + }; + } + + private static final String kLineBreak = "======================================================================"; +} diff --git a/src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java b/src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java new file mode 100644 index 0000000..cdba1e0 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java @@ -0,0 +1,174 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.tools; + +import java.util.Properties; + +import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; + +public class ValidatorUtil { + + public static void validatePublisher(Properties props) { + String transportType = props.getProperty("TransportType"); + if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(transportType)) { + validateForDME2(props); + } else { + validateForNonDME2(props); + } + String maxBatchSize = props.getProperty("maxBatchSize"); + if (maxBatchSize == null || maxBatchSize.isEmpty()) { + throw new IllegalArgumentException ( "maxBatchSize is needed" ); + } + String maxAgeMs = props.getProperty("maxAgeMs"); + if (maxAgeMs == null || maxAgeMs.isEmpty()) { + throw new IllegalArgumentException ( "maxAgeMs is needed" ); + } + String messageSentThreadOccurance = props.getProperty("MessageSentThreadOccurance"); + if (messageSentThreadOccurance == null || messageSentThreadOccurance.isEmpty()) { + throw new IllegalArgumentException ( "MessageSentThreadOccurance is needed" ); + } + + } + + public static void validateSubscriber(Properties props) { + String transportType = props.getProperty("TransportType"); + if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(transportType)) { + validateForDME2(props); + } else { + validateForNonDME2(props); + } + String group = props.getProperty("group"); + if (group == null || group.isEmpty()) { + throw new IllegalArgumentException ( "group is needed" ); + } + String id = props.getProperty("id"); + if (id == null || id.isEmpty()) { + throw new IllegalArgumentException ( "Consumer (Id) is needed" ); + } + } + + private static void validateForDME2(Properties props) { + String serviceName = props.getProperty("ServiceName"); + if (serviceName == null || serviceName.isEmpty()) { + throw new IllegalArgumentException ( "Servicename is needed" ); + } + String topic = props.getProperty("topic"); + if (topic == null || topic.isEmpty()) { + throw new IllegalArgumentException ( "topic is needed" ); + } + String username = props.getProperty("username"); + if (username == null || username.isEmpty()) { + throw new IllegalArgumentException ( "username is needed" ); + } + String password = props.getProperty("password"); + if (password == null || password.isEmpty()) { + throw new IllegalArgumentException ( "password is needed" ); + } + String dME2preferredRouterFilePath = props.getProperty("DME2preferredRouterFilePath"); + if (dME2preferredRouterFilePath == null || dME2preferredRouterFilePath.isEmpty()) { + throw new IllegalArgumentException ( "DME2preferredRouterFilePath is needed" ); + } + String partner = props.getProperty("Partner"); + String routeOffer = props.getProperty("routeOffer"); + if ((partner == null || partner.isEmpty()) && (routeOffer == null || routeOffer.isEmpty())) { + throw new IllegalArgumentException ( "Partner or routeOffer is needed" ); + } + String protocol = props.getProperty("Protocol"); + if (protocol == null || protocol.isEmpty()) { + throw new IllegalArgumentException ( "Protocol is needed" ); + } + String methodType = props.getProperty("MethodType"); + if (methodType == null || methodType.isEmpty()) { + throw new IllegalArgumentException ( "MethodType is needed" ); + } + String contenttype = props.getProperty("contenttype"); + if (contenttype == null || contenttype.isEmpty()) { + throw new IllegalArgumentException ( "contenttype is needed" ); + } + String latitude = props.getProperty("Latitude"); + if (latitude == null || latitude.isEmpty()) { + throw new IllegalArgumentException ( "Latitude is needed" ); + } + String longitude = props.getProperty("Longitude"); + if (longitude == null || longitude.isEmpty()) { + throw new IllegalArgumentException ( "Longitude is needed" ); + } + String aftEnv = props.getProperty("AFT_ENVIRONMENT"); + if (aftEnv == null || aftEnv.isEmpty()) { + throw new IllegalArgumentException ( "AFT_ENVIRONMENT is needed" ); + } + String version = props.getProperty("Version"); + if (version == null || version.isEmpty()) { + throw new IllegalArgumentException ( "Version is needed" ); + } + String environment = props.getProperty("Environment"); + if (environment == null || environment.isEmpty()) { + throw new IllegalArgumentException ( "Environment is needed" ); + } + String subContextPath = props.getProperty("SubContextPath"); + if (subContextPath == null || subContextPath.isEmpty()) { + throw new IllegalArgumentException ( "SubContextPath is needed" ); + } + String sessionstickinessrequired = props.getProperty("sessionstickinessrequired"); + if (sessionstickinessrequired == null || sessionstickinessrequired.isEmpty()) { + throw new IllegalArgumentException ( "sessionstickinessrequired is needed" ); + } + } + + private static void validateForNonDME2(Properties props) { + String transportType = props.getProperty("TransportType"); + String host = props.getProperty("host"); + if (host == null || host.isEmpty()) { + throw new IllegalArgumentException ( "Servicename is needed" ); + } + String topic = props.getProperty("topic"); + if (topic == null || topic.isEmpty()) { + throw new IllegalArgumentException ( "topic is needed" ); + } + String contenttype = props.getProperty("contenttype"); + if (contenttype == null || contenttype.isEmpty()) { + throw new IllegalArgumentException ( "contenttype is needed" ); + } + if (!ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(transportType)){ + String username = props.getProperty("username"); + if (username == null || username.isEmpty()) { + throw new IllegalArgumentException ( "username is needed" ); + } + String password = props.getProperty("password"); + if (password == null || password.isEmpty()) { + throw new IllegalArgumentException ( "password is needed" ); + } + } + if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(transportType)) { + String authKey = props.getProperty("authKey"); + if (authKey == null || authKey.isEmpty()) { + throw new IllegalArgumentException ( "authKey is needed" ); + } + String authDate = props.getProperty("authDate"); + if (authDate == null || authDate.isEmpty()) { + throw new IllegalArgumentException ( "authDate is needed" ); + } + + } + } + +} diff --git a/src/test/java/com/att/nsa/mr/client/HostSelectorTest.java b/src/test/java/com/att/nsa/mr/client/HostSelectorTest.java deleted file mode 100644 index fd6dee8..0000000 --- a/src/test/java/com/att/nsa/mr/client/HostSelectorTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client; - -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; - -public class HostSelectorTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - - @Test - public void testSelectBaseHost() { - - HostSelector selector = new HostSelector("host"); - - selector.selectBaseHost(); - assertTrue(true); - - - } - - @Test - public void testReportReachabilityProblem() { - - HostSelector selector = new HostSelector("host"); - - selector.reportReachabilityProblem(100, null); - assertTrue(true); - - - } -} - diff --git a/src/test/java/com/att/nsa/mr/client/JUnitTestSuite.java b/src/test/java/com/att/nsa/mr/client/JUnitTestSuite.java deleted file mode 100644 index 095e1d8..0000000 --- a/src/test/java/com/att/nsa/mr/client/JUnitTestSuite.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client; - -import junit.framework.TestSuite; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.apache.log4j.Logger; - -@RunWith(Suite.class) -@SuiteClasses({ HostSelectorTest.class, MRClientBuildersTest.class, MRClientFactoryTest.class}) - -public class JUnitTestSuite { - private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); - - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/client/MRClientBuildersTest.java b/src/test/java/com/att/nsa/mr/client/MRClientBuildersTest.java deleted file mode 100644 index 9a0a3ce..0000000 --- a/src/test/java/com/att/nsa/mr/client/MRClientBuildersTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client; - -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRClient; -import com.att.nsa.mr.client.MRClientBuilders; - -public class MRClientBuildersTest { - - private Collection hostSet = new ArrayList(); - private MRClientBuilders.ConsumerBuilder builder = null; - private MRClientBuilders.PublisherBuilder pBuilder = null; - private String[] hostArray = new String[10]; - - @Before - public void setUp() throws Exception { - - for (int i = 0; i < 10; i++) { - hostSet.add("host" + (i + 1)); - hostArray[i] = "host" + (i + 1); - } - - builder = new MRClientBuilders.ConsumerBuilder(); - - pBuilder = new MRClientBuilders.PublisherBuilder(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testUsingHosts() { - - builder.usingHosts("hostList"); - assertTrue(true); - - } - - @Test - public void testUsingHosts2() { - - builder.usingHosts(hostSet); - assertTrue(true); - - } - - @Test - public void testOnTopic() { - - builder.onTopic("testTopic"); - assertTrue(true); - - } - - @Test - public void testKnownAs() { - - builder.knownAs("CG1", "23"); - assertTrue(true); - - } - - @Test - public void testAuthenticatedBy() { - - builder.authenticatedBy("apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testWaitAtServer() { - - builder.waitAtServer(100); - assertTrue(true); - - } - - @Test - public void testReceivingAtMost() { - - builder.receivingAtMost(100); - assertTrue(true); - - } - - @Test - public void testWithServerSideFilter() { - - builder.withServerSideFilter("filter"); - assertTrue(true); - - } - - @Test - public void testBuild() { - - try { - - builder.build(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - - } - - @Test - public void testUsingHosts3() { - - pBuilder.usingHosts("testTopic"); - assertTrue(true); - - } - - @Test - public void testUsingHosts4() { - - pBuilder.usingHosts(hostArray); - assertTrue(true); - - } - - @Test - public void testUsingHosts5() { - - pBuilder.usingHosts(hostSet); - assertTrue(true); - - } - - @Test - public void testOnTopic2() { - - pBuilder.onTopic("testTopic"); - assertTrue(true); - - } - - @Test - public void testLimitBatch() { - - pBuilder.limitBatch(100, 10); - assertTrue(true); - - } - - @Test - public void testWithCompresion() { - - pBuilder.withCompresion(); - assertTrue(true); - - } - - @Test - public void testWithoutCompresion() { - - pBuilder.withoutCompresion(); - assertTrue(true); - - } - - @Test - public void testEnableCompresion() { - - pBuilder.enableCompresion(true); - assertTrue(true); - - } - - @Test - public void testAuthenticatedBy2() { - - pBuilder.authenticatedBy("apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testBuild2() { - - try { - - pBuilder.build(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - - } - - @Test - public void test$testInject() { - - try { - - MRClientBuilders.$testInject(builder.build()); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - - } - - @Test - public void test$testInject2() { - - try { - - MRClientBuilders.$testInject(pBuilder.build()); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - - } -} diff --git a/src/test/java/com/att/nsa/mr/client/MRClientFactoryTest.java b/src/test/java/com/att/nsa/mr/client/MRClientFactoryTest.java deleted file mode 100644 index 7ea091b..0000000 --- a/src/test/java/com/att/nsa/mr/client/MRClientFactoryTest.java +++ /dev/null @@ -1,252 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRClient; -import com.att.nsa.mr.client.MRClientBuilders; -import com.att.nsa.mr.client.MRClientFactory; - -public class MRClientFactoryTest { - - private Collection hostSet = new ArrayList(); - - private String[] hostArray = new String[10]; - - @Before - public void setUp() throws Exception { - - for (int i = 0; i < 10; i++) { - hostSet.add("host" + (i + 1)); - hostArray[i] = "host" + (i + 1); - } - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testCreateConsumer() { - - MRClientFactory.createConsumer("hostList hostList2", "testTopic"); - assertTrue(true); - - } - - @Test - public void testCreateConsumer2() { - - MRClientFactory.createConsumer(hostSet, "testTopic"); - assertTrue(true); - - } - - @Test - public void testCreateConsumer3() { - - MRClientFactory.createConsumer(hostSet, "testTopic", "filter"); - assertTrue(true); - - } - - @Test - public void testCreateConsumer4() { - - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22"); - assertTrue(true); - - } - - @Test - public void testCreateConsumer5() { - - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100); - assertTrue(true); - - } - - @Test - public void testCreateConsumer6() { - - MRClientFactory.createConsumer("hostList", "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testCreateConsumer7() { - - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testCreateSimplePublisher() { - - MRClientFactory.createSimplePublisher("hostList", "testTopic"); - assertTrue(true); - - } - - @Test - public void testCreateBatchingPublisher1() { - - MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10); - assertTrue(true); - - } - - @Test - public void testCreateBatchingPublisher2() { - - MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10, true); - assertTrue(true); - - } - - @Test - public void testCreateBatchingPublisher3() { - - MRClientFactory.createBatchingPublisher(hostArray, "testTopic", 100, 10, true); - assertTrue(true); - - } - - @Test - public void testCreateBatchingPublisher4() { - - MRClientFactory.createBatchingPublisher(hostSet, "testTopic", 100, 10, true); - assertTrue(true); - - } - - @Test - public void testCreateBatchingPublisher5() { - - MRClientFactory.createBatchingPublisher("host", "testTopic", "username", "password", 100, 10, true, - "protocolFlag"); - assertTrue(true); - - } - - @Test - public void testCreateBatchingPublisher6() { - - try { - MRClientFactory.createBatchingPublisher("/producer"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testCreateBatchingPublisher7() { - - try { - MRClientFactory.createBatchingPublisher("/producer", true); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testCreateIdentityManager() { - - MRClientFactory.createIdentityManager(hostSet, "apikey", "apisecret"); - - assertTrue(true); - - } - - @Test - public void testCreateTopicManager() { - - MRClientFactory.createTopicManager(hostSet, "apikey", "apisecret"); - - assertTrue(true); - - } - - @Test - public void testCreateConsumer8() { - - try { - MRClientFactory.createConsumer("/consumer"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testCreateConsumer9() { - - MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", "protocolFlag", - "/consumer", 1, 2); - - assertTrue(true); - - } - - @Test - public void testCreateConsumer10() { - - MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", 1, 2, "protocolFlag", - "/consumer"); - - assertTrue(true); - - } - - @Test - public void test$testInject() { - - MRClientFactory.$testInject(null); - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/mr/client/TestRunner.java b/src/test/java/com/att/nsa/mr/client/TestRunner.java deleted file mode 100644 index 814354c..0000000 --- a/src/test/java/com/att/nsa/mr/client/TestRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.apache.log4j.Logger; - -public class TestRunner { - private static final Logger LOGGER = Logger.getLogger(TestRunner.class); - - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(result.wasSuccessful()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/DMaapClientUtilTest.java b/src/test/java/com/att/nsa/mr/client/impl/DMaapClientUtilTest.java deleted file mode 100644 index 9841adb..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/DMaapClientUtilTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2018 IBM Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.Invocation.Builder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import com.att.aft.dme2.internal.jersey.core.spi.factory.ResponseImpl; - -public class DMaapClientUtilTest { - - Builder builder; - - Response response; - - WebTarget target; - - @Before - public void setup(){ - Mockito.mock(HttpServletRequest.class); - builder = Mockito.mock(Invocation.Builder.class); - response = Mockito.mock(Response.class); - target = Mockito.mock(WebTarget.class); - - } - - @Test - public void testGetTarget() throws IOException{ - WebTarget actual = DmaapClientUtil.getTarget("testpath"); - - assertEquals("testpath", actual.getUri().getPath()); - } - - @Test - public void testGetTargetWithParams() throws IOException{ - WebTarget actual = DmaapClientUtil.getTarget("testpath", "testuser", "testpassword"); - - assertEquals("testpath", actual.getUri().getPath()); - } - - @Test - public void testGetResponsewtCambriaAuth() { - Mockito.when(target.request()).thenReturn(builder); - Mockito.when(builder.header("X-CambriaAuth", "testuser")).thenReturn(builder); - Mockito.when(builder.header("X-CambriaDate", "testpassword")).thenReturn(builder); - Mockito.when(builder.get()).thenReturn(response); - - Response actual = DmaapClientUtil.getResponsewtCambriaAuth(target, "testuser", "testpassword"); - - assertEquals(response, actual); - } - - - -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/MRBaseClientTest.java b/src/test/java/com/att/nsa/mr/client/impl/MRBaseClientTest.java deleted file mode 100644 index 055c94f..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/MRBaseClientTest.java +++ /dev/null @@ -1,471 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.net.MalformedURLException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - -import org.apache.http.HttpException; -import org.glassfish.jersey.internal.util.Base64; -import org.glassfish.jersey.internal.util.collection.StringKeyIgnoreCaseMultivaluedMap; -import org.json.JSONException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore("org.apache.http.conn.ssl.*") -@PrepareForTest({ DmaapClientUtil.class }) -public class MRBaseClientTest { - - // @InjectMocks - private MRBaseClient mrBaseClient; - private Collection hosts = new HashSet<>(Arrays.asList("localhost:8080")); - private String clientSignature = "topic" + "::" + "cg" + "::" + "cid"; - - @Before - public void setup() throws MalformedURLException { - mrBaseClient = new MRBaseClient(hosts, clientSignature); - PowerMockito.mockStatic(DmaapClientUtil.class); - } - - @Test - public void testGet() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) - .thenReturn(response); - - mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testGet_403() throws JSONException, HttpException { - ResponseBuilder responseBuilder = Response.status(403); - PowerMockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testGet_basicauth() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), - Base64.encodeAsString("username:password"))).thenReturn(response); - - mrBaseClient.get("/path", "username", "password", "HTTPAAF"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testGet_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.get("/path", null, null, "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testGet_wrongjson() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("[["); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) - .thenReturn(response); - - mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); - } - - @Test - public void testGetResponse() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) - .thenReturn(response); - - mrBaseClient.getResponse("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testGetResponse_aaf() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), - Base64.encodeAsString("username:password"))).thenReturn(response); - - mrBaseClient.getResponse("/path", "username", "password", "HTTPAAF"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testGetResponse_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.getResponse("/path", null, null, "HTTPAUTH"); - - } - - @Test - public void testAuthResponse() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) - .thenReturn(response); - - mrBaseClient.getAuthResponse("/path", "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testAuthResponsee_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.getAuthResponse("/path", null, null, null, null, "HTTPAUTH"); - - } - - @Test - public void testPostAuth() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn(response); - - mrBaseClient.postAuth("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", "username", - "password", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testPostAuth_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.postAuth("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, null, - null, null, "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testGetNoAuthResponse() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget("/path"))).thenReturn(response); - - mrBaseClient.getNoAuthResponse("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testPost() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), - Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); - - mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", "username", - "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testPost_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), - Base64.encodeAsString("username:password"))) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, null, - "HTTPAUTH"); - - } - - @Test - public void testPostAuthwithResponse() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn(response); - - mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testPostAuthwithResponse_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - null, null, null, null, "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testPostWithResponse() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), - Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); - - mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testPostWithResponse_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), - Base64.encodeAsString("username:password"))) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, - null, "HTTPAUTH"); - - } - - @Test - public void testGetAuth() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) - .thenReturn(response); - mrBaseClient.getAuth("/path", "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); - - } - - @Test(expected = HttpException.class) - public void testGetAuth_error() throws JSONException, HttpException { - - ResponseBuilder responseBuilder = Response.ok(); - PowerMockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.getAuth("/path", null, null, null, null, "HTTPAUTH"); - assertTrue(true); - - } - - @Test - public void testGetNoAuth() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - PowerMockito.when(response.getStatus()).thenReturn(200); - PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - PowerMockito.when(response.getHeaders()).thenReturn(map); - - PowerMockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget("/path"))).thenReturn(response); - mrBaseClient.getNoAuth("/path"); - assertTrue(true); - - } - - - @Test - public void testGetHTTPErrorResponseMessage() { - - assertEquals(mrBaseClient.getHTTPErrorResponseMessage("testtest"), "testtest"); - - } - - @Test - public void getGTTPErrorResponseCode() { - - assertEquals(mrBaseClient.getHTTPErrorResponseMessage("testtest"), "testtest"); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/MRBatchPublisherTest.java b/src/test/java/com/att/nsa/mr/client/impl/MRBatchPublisherTest.java deleted file mode 100644 index 19b58e9..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/MRBatchPublisherTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; - -import org.junit.Before; -import org.junit.Test; - -public class MRBatchPublisherTest { - - private Collection hosts=new HashSet<>(Arrays.asList("/test")); - private MRBatchPublisher mrBatchPublisher=new MRBatchPublisher(hosts, "topic", 2, 20, true); - - - @Before - public void setup(){ - - - } - - @Test - public void testSend() throws IOException{ - mrBatchPublisher.send("testmessage"); - } - - @Test - public void testClose() throws IOException{ - mrBatchPublisher.close(); - } - -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/MRConstantsTest.java b/src/test/java/com/att/nsa/mr/client/impl/MRConstantsTest.java deleted file mode 100644 index ed918b5..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/MRConstantsTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.apache.http.HttpHost; -import org.junit.Test; - -import com.att.nsa.mr.client.impl.MRConstants; - -public class MRConstantsTest extends TestCase -{ - @Test - public void testPlainHost () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithProtocol () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithProtocolAndPort () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithPort () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithPortAndEscapedTopic () throws IOException - { - final String rawTopic = "bar?bell"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar%3Fbell", result ); - } - - @Test - public void testConsumerPlainHost () throws IOException - { - final String rawTopic = "bar"; - final String rawGroup = "group"; - final String rawId = "id"; - final String result = MRConstants.makeConsumerUrl ( rawTopic, rawGroup, rawId ); - assertEquals ( "/events/" + "bar/group/id", result ); - } - - @Test - public void testCreateHostList () - { - final ArrayList in = new ArrayList (); - in.add ( "foo" ); - in.add ( "bar" ); - in.add ( "baz:80" ); - - final Collection hosts = MRConstants.createHostsList ( in ); - assertEquals ( 3, hosts.size () ); - - final Iterator it = hosts.iterator (); - final HttpHost first = it.next (); - assertEquals ( MRConstants.kStdMRServicePort, first.getPort () ); - assertEquals ( "foo", first.getHostName () ); - - final HttpHost second = it.next (); - assertEquals ( MRConstants.kStdMRServicePort, second.getPort () ); - assertEquals ( "bar", second.getHostName () ); - - final HttpHost third = it.next (); - assertEquals ( 80, third.getPort () ); - assertEquals ( "baz", third.getHostName () ); - } - - private static final String[][] hostTests = - { - { "host", "host", "" + MRConstants.kStdMRServicePort }, - { ":oops", null, "-1" }, - { "host:1.3", null, "-1" }, - { "host:13", "host", "13" }, - { "host:", "host", "" + MRConstants.kStdMRServicePort }, - }; - - @Test - public void testHostParse () - { - for ( String[] test : hostTests ) - { - final String hostIn = test[0]; - final String hostOut = test[1]; - final int portOut = Integer.parseInt ( test[2] ); - - try - { - final HttpHost hh = MRConstants.hostForString ( hostIn ); - assertEquals ( hostOut, hh.getHostName () ); - assertEquals ( portOut, hh.getPort () ); - } - catch ( IllegalArgumentException x ) - { - assertEquals ( -1, portOut ); - } - } - } -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/MRConsumerImplTest.java b/src/test/java/com/att/nsa/mr/client/impl/MRConsumerImplTest.java deleted file mode 100644 index bfac947..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/MRConsumerImplTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.IOException; -import java.util.LinkedList; -import java.util.Properties; - -import junit.framework.TestCase; - -import org.junit.Test; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.impl.MRConstants; -import com.att.nsa.mr.client.impl.MRConsumerImpl; - -public class MRConsumerImplTest extends TestCase -{ - @Test - public void testNullFilter () throws IOException - { - final LinkedList hosts = new LinkedList (); - hosts.add ( "localhost:8080" ); - final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, null, null, null ); - final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), -1, -1 ); - assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); - } - - @Test - public void testFilterWithNoTimeoutOrLimit () throws IOException - { - final LinkedList hosts = new LinkedList (); - hosts.add ( "localhost:8080" ); - final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, "filter", null, null ); - final String url = c.createUrlPath ( MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid" ,"http"),-1, -1 ); - assertEquals ("http://localhost:8080/events/" + "topic/cg/cid?filter=filter", url ); - } - - @Test - public void testTimeoutNoLimitNoFilter () throws IOException - { - final LinkedList hosts = new LinkedList (); - hosts.add ( "localhost:8080" ); - final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", 30000, -1, null, null, null ); - final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), 30000, -1 ); - assertEquals ( "http://localhost:8080/events/" + "topic/cg/cid?timeout=30000", url ); - } - - @Test - public void testNoTimeoutWithLimitNoFilter () throws IOException - { - final LinkedList hosts = new LinkedList (); - hosts.add ( "localhost:8080" ); - final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, 100, null, null, null ); - final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), -1, 100 ); - assertEquals ( "http://localhost:8080/events/" + "topic/cg/cid?limit=100", url ); - } - - @Test - public void testWithTimeoutWithLimitWithFilter () throws IOException - { - final LinkedList hosts = new LinkedList (); - hosts.add ( "localhost:8080" ); - final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", 1000, 400, "f", null, null ); - final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid" ,"http"), 1000, 400 ); - assertEquals ("http://localhost:8080/events/" + "topic/cg/cid?timeout=1000&limit=400&filter=f", url ); - } - - @Test - public void testFilterEncoding () throws IOException - { - final LinkedList hosts = new LinkedList (); - hosts.add ( "localhost:8080" ); - final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, "{ \"foo\"=\"bar\"bar\" }", null, null ); - final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), -1, -1 ); - assertEquals ( "http://localhost:8080/events/" + "topic/cg/cid?filter=%7B+%22foo%22%3D%22bar%22bar%22+%7D", url ); - } - - @Test - public void testFetchWithReturnConsumerResponse () throws IOException - { - final LinkedList hosts = new LinkedList (); - hosts.add ( "localhost:8080" ); - Properties properties = new Properties(); - properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, "{ \"foo\"=\"bar\"bar\" }", null, null ); - c.fetchWithReturnConsumerResponse(); - c.setProtocolFlag("HTTPAAF"); - c.fetchWithReturnConsumerResponse(); - assertTrue(true); - } -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/MRMetaClientTest.java b/src/test/java/com/att/nsa/mr/client/impl/MRMetaClientTest.java deleted file mode 100644 index 4a3650f..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/MRMetaClientTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package com.att.nsa.mr.client.impl; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Collection; -import java.util.LinkedList; -import java.util.Set; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertTrue; - -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.mr.client.MRClient.MRApiException; -import com.att.nsa.mr.client.MRTopicManager.TopicInfo; -import com.github.tomakehurst.wiremock.junit.WireMockRule; - - -public class MRMetaClientTest { - - @Rule public WireMockRule wireMock = new WireMockRule(); - - @Before - public void setUp(){ - wireMock.stubFor(get(urlEqualTo("/topics")) - .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); - wireMock.stubFor(get(urlEqualTo("/topics/topic1")) - .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); - wireMock.stubFor(post(urlEqualTo("/topics/create")) - .willReturn(aResponse().withStatus(200))); - } - - @Test - public void getTopicsTest() - { - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" + wireMock.port() ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - Set setString=c.getTopics(); - } catch (IOException e) { - e.printStackTrace(); - } - - - // assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); - - } - - @Test - public void getTopicMetadataTest() { - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" + wireMock.port() ); - - final String topic ="topic1"; - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - TopicInfo topicInfo=c.getTopicMetadata(topic); - } catch (IOException | HttpObjectNotFoundException e) { - e.printStackTrace(); - } - - } - - @Test - public void testcreateTopic(){ - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" + wireMock.port() ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - c.createTopic("topic1", "testTopic", 1, 1); - } catch (IOException | HttpException e) { - e.printStackTrace(); - } - } - @Test - public void testupdateApiKey(){ - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" + wireMock.port() ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - c.updateCurrentApiKey("test@onap.com", "test email"); - }catch (HttpException e) { - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - catch (NullPointerException e) { - assertTrue(true); - } - - } - - -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchConsumerTest.java b/src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchConsumerTest.java deleted file mode 100644 index 506d277..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchConsumerTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.client.impl; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.json.JSONObject; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.client.response.MRPublisherResponse; - -public class MRSimplerBatchConsumerTest { - - File outFile; - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - String routeFilePath="dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("DME2preferredRouterFilePath", MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - outFile = new File(file.getParent() + "/consumer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - } - - @Test - public void testSend() throws IOException, InterruptedException { - - final MRConsumer cc = MRClientFactory.createConsumer(outFile.getPath()); - - try { - for(String msg : cc.fetch()){ - System.out.println(msg); - } - } catch (Exception e) { - System.err.println ( e.getClass().getName () + ": " + e.getMessage () ); - } - - } - - -} diff --git a/src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisherTest.java b/src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisherTest.java deleted file mode 100644 index 5b8d580..0000000 --- a/src/test/java/com/att/nsa/mr/client/impl/MRSimplerBatchPublisherTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.client.impl; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.json.JSONObject; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.client.response.MRPublisherResponse; - -public class MRSimplerBatchPublisherTest { - - File outFile; - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.load(MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/producer.properties")); - - String routeFilePath="dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("DME2preferredRouterFilePath", MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - outFile = new File(file.getParent() + "/producer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - } - - @Test - public void testSend() throws IOException, InterruptedException { - - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher)MRClientFactory.createBatchingPublisher(outFile.getPath()); - - //publish some messages - final JSONObject msg1 = new JSONObject (); - pub.send ( "MyPartitionKey", msg1.toString () ); - - final List stuck = pub.close ( 1, TimeUnit.SECONDS ); - if ( stuck.size () > 0 ) { - System.out.println( stuck.size() + " messages unsent" ); - } - else - { - System.out.println ( "Clean exit; all messages sent." ); - } - - - } - - @Test - public void testSendBatchWithResponse() throws IOException, InterruptedException { - - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher)MRClientFactory.createBatchingPublisher(outFile.getPath(), true); - - //publish some messages - final JSONObject msg1 = new JSONObject (); - pub.send ( "MyPartitionKey", msg1.toString () ); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); - - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/client/response/JUnitTestSuite.java b/src/test/java/com/att/nsa/mr/client/response/JUnitTestSuite.java deleted file mode 100644 index 90b10a9..0000000 --- a/src/test/java/com/att/nsa/mr/client/response/JUnitTestSuite.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client.response; - -import junit.framework.TestSuite; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.apache.log4j.Logger; - -@RunWith(Suite.class) -@SuiteClasses({ MRConsumerResponseTest.class, MRPublisherResponseTest.class,}) - -public class JUnitTestSuite { - private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); - - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/client/response/MRConsumerResponseTest.java b/src/test/java/com/att/nsa/mr/client/response/MRConsumerResponseTest.java deleted file mode 100644 index 036a216..0000000 --- a/src/test/java/com/att/nsa/mr/client/response/MRConsumerResponseTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client.response; - -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; - -public class MRConsumerResponseTest { - private MRConsumerResponse test = null; - - @Before - public void setUp() throws Exception { - test = new MRConsumerResponse(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetResponseCode() { - - test.getResponseCode(); - assertTrue(true); - - } - - @Test - public void testSetResponseCode() { - - test.setResponseCode("200"); - assertTrue(true); - - } - - @Test - public void testGetResponseMessage() { - - test.getResponseMessage(); - assertTrue(true); - - } - - @Test - public void testSetResponseMessage() { - - test.setResponseMessage("responseMessage"); - assertTrue(true); - - } - - @Test - public void testGetActualMessages() { - - test.getActualMessages(); - assertTrue(true); - - } - - @Test - public void testSetActualMessages() { - - test.setActualMessages(null); - assertTrue(true); - - } -} diff --git a/src/test/java/com/att/nsa/mr/client/response/MRPublisherResponseTest.java b/src/test/java/com/att/nsa/mr/client/response/MRPublisherResponseTest.java deleted file mode 100644 index 60e64ad..0000000 --- a/src/test/java/com/att/nsa/mr/client/response/MRPublisherResponseTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client.response; - -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; - -public class MRPublisherResponseTest { - private MRPublisherResponse response = null; - - @Before - public void setUp() throws Exception { - response = new MRPublisherResponse(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetResponseCode() { - - response.getResponseCode(); - assertTrue(true); - - } - - @Test - public void testSetResponseCode() { - - response.setResponseCode("200"); - assertTrue(true); - - } - - @Test - public void testGetResponseMessage() { - - response.getResponseMessage(); - assertTrue(true); - - } - - @Test - public void testSetResponseMessage() { - - response.setResponseMessage("responseMessage"); - assertTrue(true); - - } - - @Test - public void testGetPendingMsgs() { - - response.getPendingMsgs(); - assertTrue(true); - - } - - @Test - public void testSetPendingMsgs() { - - response.setPendingMsgs(5); - assertTrue(true); - - } - - @Test - public void testToString() { - - response.toString(); - assertTrue(true); - - } - - -} diff --git a/src/test/java/com/att/nsa/mr/client/response/TestRunner.java b/src/test/java/com/att/nsa/mr/client/response/TestRunner.java deleted file mode 100644 index f2abadc..0000000 --- a/src/test/java/com/att/nsa/mr/client/response/TestRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.client.response; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.apache.log4j.Logger; - -public class TestRunner { - private static final Logger LOGGER = Logger.getLogger(TestRunner.class); - - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(result.wasSuccessful()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java b/src/test/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java deleted file mode 100644 index 5f67f6d..0000000 --- a/src/test/java/com/att/nsa/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.dme.client; - -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Listener; - -public class DefaultLoggingFailoverFaultHandlerTest { - private DefaultLoggingFailoverFaultHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new DefaultLoggingFailoverFaultHandler(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testHandleEndpointFailover() { - - /* handler.handleEndpointFailover(null); - assertTrue(true);*/ - - } - - @Test - public void testHandleRouteOfferFailover() { - - /* handler.handleRouteOfferFailover(null); - assertTrue(true); -*/ - } - -} diff --git a/src/test/java/com/att/nsa/mr/dme/client/HeaderReplyHandlerTest.java b/src/test/java/com/att/nsa/mr/dme/client/HeaderReplyHandlerTest.java deleted file mode 100644 index bdcff83..0000000 --- a/src/test/java/com/att/nsa/mr/dme/client/HeaderReplyHandlerTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.dme.client; - -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Listener; - -public class HeaderReplyHandlerTest { - private HeaderReplyHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new HeaderReplyHandler(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testHandleFault() { - - handler.handleFault(null); - assertTrue(true); - - } - - @Test - public void testHandleEndpointFault() { - - handler.handleEndpointFault(null); - assertTrue(true); - - } - - @Test - public void testHandleReply() { - - handler.handleReply(null); - assertTrue(true); - - } - - - -} diff --git a/src/test/java/com/att/nsa/mr/dme/client/JUnitTestSuite.java b/src/test/java/com/att/nsa/mr/dme/client/JUnitTestSuite.java deleted file mode 100644 index 3ce48a4..0000000 --- a/src/test/java/com/att/nsa/mr/dme/client/JUnitTestSuite.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.dme.client; - -import junit.framework.TestSuite; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.apache.log4j.Logger; - -@RunWith(Suite.class) -@SuiteClasses({ DefaultLoggingFailoverFaultHandlerTest.class, HeaderReplyHandlerTest.class,PreferredRouteReplyHandlerTest.class, - PreferredRouteRequestHandlerTest.class,SimpleExamplePublisherTest.class }) - -public class JUnitTestSuite { - private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); - - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandlerTest.java b/src/test/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandlerTest.java deleted file mode 100644 index 28f138d..0000000 --- a/src/test/java/com/att/nsa/mr/dme/client/PreferredRouteReplyHandlerTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.dme.client; - -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Listener; - -public class PreferredRouteReplyHandlerTest { - private PreferredRouteReplyHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new PreferredRouteReplyHandler(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testHandleReply() { - -// handler.handleReply(null); -// assertTrue(true); - - } - - @Test - public void testHandleFault() { -/* - handler.handleFault(null); - assertTrue(true); -*/ - } - - @Test - public void testHandleEndpointFault() { - -/* handler.handleEndpointFault(null); - assertTrue(true);*/ - - } - - @Test - public void testRouteWriter() { -/* - handler.routeWriter("routeKey", "routeValue"); - assertTrue(true); -*/ - } - - - - -} diff --git a/src/test/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandlerTest.java b/src/test/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandlerTest.java deleted file mode 100644 index 86f220c..0000000 --- a/src/test/java/com/att/nsa/mr/dme/client/PreferredRouteRequestHandlerTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.dme.client; - -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Listener; - -public class PreferredRouteRequestHandlerTest { - private PreferredRouteRequestHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new PreferredRouteRequestHandler(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testHandleRequest() { - - /* handler.handleRequest(null); - assertTrue(true);*/ - - } - - @Test - public void testReadRoute() { - -// try { -// handler.readRoute("routeKey"); -// } catch (NullPointerException e) { -// assertTrue(true); -// } -// -// assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/dme/client/SimpleExamplePublisherTest.java b/src/test/java/com/att/nsa/mr/dme/client/SimpleExamplePublisherTest.java deleted file mode 100644 index 67051b1..0000000 --- a/src/test/java/com/att/nsa/mr/dme/client/SimpleExamplePublisherTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.dme.client; - -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Listener; - -public class SimpleExamplePublisherTest { - private SimpleExamplePublisher pub = null; - - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisher(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testPublishMessage() { - - try { - pub.publishMessage("/producer"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - - -} diff --git a/src/test/java/com/att/nsa/mr/dme/client/TestRunner.java b/src/test/java/com/att/nsa/mr/dme/client/TestRunner.java deleted file mode 100644 index 08be6da..0000000 --- a/src/test/java/com/att/nsa/mr/dme/client/TestRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.dme.client; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.apache.log4j.Logger; - -public class TestRunner { - private static final Logger LOGGER = Logger.getLogger(TestRunner.class); - - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(result.wasSuccessful()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/logging/JUnitTestSuite.java b/src/test/java/com/att/nsa/mr/logging/JUnitTestSuite.java deleted file mode 100644 index 43fe365..0000000 --- a/src/test/java/com/att/nsa/mr/logging/JUnitTestSuite.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.logging; - -import junit.framework.TestSuite; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.apache.log4j.Logger; - -@RunWith(Suite.class) -@SuiteClasses({ MRAppenderTest.class, }) - -public class JUnitTestSuite { - private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); - - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/logging/MRAppenderTest.java b/src/test/java/com/att/nsa/mr/logging/MRAppenderTest.java deleted file mode 100644 index 0a59d97..0000000 --- a/src/test/java/com/att/nsa/mr/logging/MRAppenderTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.logging; - -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; - -public class MRAppenderTest { - private MRAppender appender = null; - - @Before - public void setUp() throws Exception { - appender = new MRAppender(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testClose() { - try { - appender.close(); - } catch (NullPointerException e) { - assertTrue(true); - } - - assertTrue(true); - - } - - @Test - public void testRequiresLayout() { - - appender.requiresLayout(); - assertTrue(true); - - } - - @Test - public void testAppend() { - - try { - appender.append(null); - } catch (NullPointerException e) { - assertTrue(true); - } - - assertTrue(true); - - } - - @Test - public void testActivateOptions() { - - appender.activateOptions(); - assertTrue(true); - - } - - @Test - public void testGetTopic() { - - appender.getTopic(); - assertTrue(true); - - } - - @Test - public void testSetTopic() { - - appender.setTopic("testTopic"); - assertTrue(true); - - } - - @Test - public void testGetPartition() { - - appender.getPartition(); - assertTrue(true); - - } - - @Test - public void testSetPartition() { - - appender.setPartition("partition"); - assertTrue(true); - - } - - @Test - public void testGetHosts() { - - appender.getHosts(); - assertTrue(true); - - } - - @Test - public void testSetHosts() { - - appender.setHosts("hosts"); - assertTrue(true); - - } - - @Test - public void testGetMaxBatchSize() { - - appender.getMaxBatchSize(); - assertTrue(true); - - } - - @Test - public void testSetMaxBatchSize() { - - appender.setMaxBatchSize(20); - assertTrue(true); - - } - - @Test - public void testGetMaxAgeMs() { - - appender.getMaxAgeMs(); - assertTrue(true); - - } - - @Test - public void testSetMaxAgeMs() { - - appender.setMaxAgeMs(15); - assertTrue(true); - - } - - @Test - public void testIsCompress() { - - appender.isCompress(); - assertTrue(true); - - } - - @Test - public void testSetCompress() { - - appender.setCompress(true); - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/logging/TestRunner.java b/src/test/java/com/att/nsa/mr/logging/TestRunner.java deleted file mode 100644 index 415156f..0000000 --- a/src/test/java/com/att/nsa/mr/logging/TestRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.logging; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.apache.log4j.Logger; - -public class TestRunner { - private static final Logger LOGGER = Logger.getLogger(TestRunner.class); - - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(result.wasSuccessful()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/ConsolePublisherTest.java b/src/test/java/com/att/nsa/mr/test/clients/ConsolePublisherTest.java deleted file mode 100644 index 5ccd10c..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/ConsolePublisherTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ConsolePublisherTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testMain() { - - try { - ConsolePublisher.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/JUnitTestSuite.java b/src/test/java/com/att/nsa/mr/test/clients/JUnitTestSuite.java deleted file mode 100644 index 49e22de..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/JUnitTestSuite.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import junit.framework.TestSuite; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.apache.log4j.Logger; - -@RunWith(Suite.class) -@SuiteClasses({ SimpleExamplePublisherTest.class, ProtocolTypeConstantsTest.class, - SampleConsumerTest.class, SamplePublisherTest.class, SimpleExampleConsumerTest.class, ConsolePublisherTest.class, - SimpleExamplePublisherWithResponseTest.class, SimpleExampleConsumerWithReturnResponseTest.class,}) - -public class JUnitTestSuite { - private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); - - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/ProtocolTypeConstantsTest.java b/src/test/java/com/att/nsa/mr/test/clients/ProtocolTypeConstantsTest.java deleted file mode 100644 index ce4b72c..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/ProtocolTypeConstantsTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ProtocolTypeConstantsTest { - private ProtocolTypeConstants constants = null; - - @Before - public void setUp() throws Exception { - // constants = new ProtocolTypeConstants(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetValue() { - - try { - constants.getValue(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/SampleConsumerTest.java b/src/test/java/com/att/nsa/mr/test/clients/SampleConsumerTest.java deleted file mode 100644 index f950fc6..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/SampleConsumerTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SampleConsumerTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testMain() { - - try { - SampleConsumer.main( new String[0]); - } catch (Exception e) { - assertTrue(true); - } - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/SamplePublisherTest.java b/src/test/java/com/att/nsa/mr/test/clients/SamplePublisherTest.java deleted file mode 100644 index 5ad4407..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/SamplePublisherTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SamplePublisherTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testMain() { - - try { - SamplePublisher.main( new String[0]); - } catch (Exception e) { - // TODO Auto-generated catch block - assertTrue(true); - } - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerTest.java b/src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerTest.java deleted file mode 100644 index 1887ff9..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SimpleExampleConsumerTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testMain() { - - try { - SimpleExampleConsumer.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java b/src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java deleted file mode 100644 index f6f2deb..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SimpleExampleConsumerWithReturnResponseTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testMain() { - - try { - SimpleExampleConsumerWithReturnResponse.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block e.printStackTrace(); - } - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherTest.java b/src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherTest.java deleted file mode 100644 index b30d523..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SimpleExamplePublisherTest { - private SimpleExamplePublisher pub = null; - - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisher(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testPublishMessage() { - try { - pub.publishMessage("/producer"); - } catch (NullPointerException e) { - assertTrue(true); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testMain() { - - try { - SimpleExamplePublisher.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - - -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponseTest.java b/src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponseTest.java deleted file mode 100644 index d408a33..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/SimpleExamplePublisherWithResponseTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SimpleExamplePublisherWithResponseTest { - - private SimpleExamplePublisherWithResponse pub = null; - - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisherWithResponse(); - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testMain() { - - try { - SimpleExamplePublisherWithResponse.main( new String[0]); - } catch (Exception e) { - assertTrue(true); - } - assertTrue(true); - - } - - @Test - public void testPublishMessage() { - - try { - pub.publishMessage("/producer", 100); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } -} diff --git a/src/test/java/com/att/nsa/mr/test/clients/TestRunner.java b/src/test/java/com/att/nsa/mr/test/clients/TestRunner.java deleted file mode 100644 index 39bbbb3..0000000 --- a/src/test/java/com/att/nsa/mr/test/clients/TestRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.clients; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.apache.log4j.Logger; - -public class TestRunner { - private static final Logger LOGGER = Logger.getLogger(TestRunner.class); - - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(result.wasSuccessful()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/support/JUnitTestSuite.java b/src/test/java/com/att/nsa/mr/test/support/JUnitTestSuite.java deleted file mode 100644 index 8d18e1c..0000000 --- a/src/test/java/com/att/nsa/mr/test/support/JUnitTestSuite.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.support; - -import junit.framework.TestSuite; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.apache.log4j.Logger; - -@RunWith(Suite.class) -@SuiteClasses({ MRBatchingPublisherMockTest.class, MRConsumerMockTest.class,}) - -public class JUnitTestSuite { - private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); - - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/test/support/MRBatchingPublisherMockTest.java b/src/test/java/com/att/nsa/mr/test/support/MRBatchingPublisherMockTest.java deleted file mode 100644 index 3666c25..0000000 --- a/src/test/java/com/att/nsa/mr/test/support/MRBatchingPublisherMockTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.support; - -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Listener; - -public class MRBatchingPublisherMockTest { - private MRBatchingPublisherMock pub = null; - - private MRBatchingPublisherMock.Entry entry = null; - - @Before - public void setUp() throws Exception { - pub = new MRBatchingPublisherMock(); - entry = pub.new Entry("partition", "msg"); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testToString() { - - entry.toString(); - assertTrue(true); - - } - - @Test - public void testAddListener() { - - pub.addListener(null); - assertTrue(true); - - } - - @Test - public void testGetCaptures() { - - pub.getCaptures(); - assertTrue(true); - - } - - @Test - public void testGetCaptures2() { - - pub.getCaptures(null); - assertTrue(true); - - } - - @Test - public void testReceived() { - - pub.received(); - assertTrue(true); - - } - - @Test - public void testResend() { - - pub.reset(); - assertTrue(true); - - } - - @Test - public void testSend() { - - pub.send("partition", "msg"); - assertTrue(true); - - } - - @Test - public void testSend2() { - - pub.send("msg"); - assertTrue(true); - - } - - @Test - public void testSend3() { - //sending message m obj - pub.send(new ArrayList()); - assertTrue(true); - - } - - @Test - public void testSend4() { - //sending collection of message m objects - pub.send(new message("partition", "msg")); - assertTrue(true); - - } - - @Test - public void testSendBatchWithResponse() { - - pub.sendBatchWithResponse(); - assertTrue(true); - - } - - @Test - public void testLogTo() { - - pub.logTo(null); - assertTrue(true); - - } - - @Test - public void testClearApiCredentials() { - - pub.clearApiCredentials(); - assertTrue(true); - - } - - @Test - public void testSetApiCredentials() { - - pub.setApiCredentials("apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testClose() { - - pub.close(); - assertTrue(true); - - } - - @Test - public void testClose2() { - - pub.close(100, null); - assertTrue(true); - - } - - @Test - public void testGetPendingMessageCount() { - - pub.getPendingMessageCount(); - assertTrue(true); - - } -} diff --git a/src/test/java/com/att/nsa/mr/test/support/MRConsumerMockTest.java b/src/test/java/com/att/nsa/mr/test/support/MRConsumerMockTest.java deleted file mode 100644 index 2a4f50a..0000000 --- a/src/test/java/com/att/nsa/mr/test/support/MRConsumerMockTest.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.support; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Entry; - -public class MRConsumerMockTest { - private MRConsumerMock cons = null; - private MRConsumerMock.Entry entry = null; - - @Before - public void setUp() throws Exception { - cons = new MRConsumerMock(); - entry = cons.new Entry(100, 200, "statusMsg"); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testClose() { - - cons.close(); - assertTrue(true); - - } - - @Test - public void testRun() { - try { - entry.run(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testSetApiCredentials() { - cons.setApiCredentials("apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testClearApiCredentials() { - cons.clearApiCredentials(); - assertTrue(true); - - } - - @Test - public void testAdd() { - cons.add(entry); - assertTrue(true); - - } - - @Test - public void testAddImmediateMsg() { - cons.addImmediateMsg("ImmediateMsg"); - assertTrue(true); - - } - - @Test - public void testAddDelayedMsg() { - cons.addDelayedMsg(100, "msg"); - assertTrue(true); - - } - - @Test - public void testAddImmediateMsgGroup() { - cons.addImmediateMsgGroup(new ArrayList()); - assertTrue(true); - - } - - @Test - public void testAddDelayedMsgGroup() { - cons.addDelayedMsgGroup(100,new ArrayList()); - assertTrue(true); - - } - - @Test - public void testAddImmediateError() { - cons.addImmediateError(200, "OK"); - assertTrue(true); - - } - - @Test - public void testFetch() { - try { - cons.fetch(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testFetch2() { - try { - cons.fetch(100, 200); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testLogTo() { - cons.logTo(null); - assertTrue(true); - - } - - @Test - public void testFetchWithReturnConsumerResponse() { - cons.fetchWithReturnConsumerResponse(); - assertTrue(true); - - } - - @Test - public void testGetchWithReturnConsumerResponse() { - cons.fetchWithReturnConsumerResponse(100,200); - assertTrue(true); - - } -} diff --git a/src/test/java/com/att/nsa/mr/test/support/TestRunner.java b/src/test/java/com/att/nsa/mr/test/support/TestRunner.java deleted file mode 100644 index 4e8651c..0000000 --- a/src/test/java/com/att/nsa/mr/test/support/TestRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.test.support; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.apache.log4j.Logger; - -public class TestRunner { - private static final Logger LOGGER = Logger.getLogger(TestRunner.class); - - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(result.wasSuccessful()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/ApiKeyCommandTest.java b/src/test/java/com/att/nsa/mr/tools/ApiKeyCommandTest.java deleted file mode 100644 index e5bd722..0000000 --- a/src/test/java/com/att/nsa/mr/tools/ApiKeyCommandTest.java +++ /dev/null @@ -1,217 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.MRClient.MRApiException; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRIdentityManager; -import com.att.nsa.mr.client.MRIdentityManager.ApiKey; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ MRClientFactory.class }) -public class ApiKeyCommandTest { - - @InjectMocks - private ApiKeyCommand command; - @Mock - private MRIdentityManager tm; - @Mock - private ApiKey ti; - @Mock - private ApiKey key; - @Mock - private ApiCredential ac; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.when(MRClientFactory.createIdentityManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); - PowerMockito.when(tm.getApiKey("testtopic")).thenReturn(key); - PowerMockito.when(tm.createApiKey("testtopic", "1")).thenReturn(ac); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testExecute_error1() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new IOException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - } - - } - - @Test - public void testExecute_error2() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new MRApiException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(),printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testExecute_error3() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpException(500, "error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - } - - } - - @Test - public void testExecute_error4() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/AuthCommandTest.java b/src/test/java/com/att/nsa/mr/tools/AuthCommandTest.java deleted file mode 100644 index fdb7671..0000000 --- a/src/test/java/com/att/nsa/mr/tools/AuthCommandTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertTrue; - -import java.io.PrintStream; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.nsa.cmdtool.CommandNotReadyException; - -@RunWith(PowerMockRunner.class) -public class AuthCommandTest { - @InjectMocks - private AuthCommand command = null; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - try { - String[] parts = new String[5]; - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute1() { - - try { - String[] parts = { "userName", "password" }; - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/ClusterCommandTest.java b/src/test/java/com/att/nsa/mr/tools/ClusterCommandTest.java deleted file mode 100644 index cf9c1a7..0000000 --- a/src/test/java/com/att/nsa/mr/tools/ClusterCommandTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertTrue; - -import java.io.FileNotFoundException; -import java.io.PrintStream; -import java.util.Arrays; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.nsa.cmdtool.CommandNotReadyException; - -@RunWith(PowerMockRunner.class) -public class ClusterCommandTest { - @InjectMocks - private ClusterCommand command; - @Mock - private MRCommandContext context; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.when(context.getCluster()).thenReturn(Arrays.asList("localhost")); - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(context); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() throws FileNotFoundException, CommandNotReadyException { - String[] parts = { "create", "testtopic", "1", "1" }; - command.execute(parts, context, printStream); - assertTrue(true); - - } - - @Test - public void testExecute1() throws FileNotFoundException, CommandNotReadyException { - String[] parts = {}; - command.execute(parts, context, printStream); - assertTrue(true); - - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/JUnitTestSuite.java b/src/test/java/com/att/nsa/mr/tools/JUnitTestSuite.java deleted file mode 100644 index 6e882d4..0000000 --- a/src/test/java/com/att/nsa/mr/tools/JUnitTestSuite.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import junit.framework.TestSuite; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.apache.log4j.Logger; - -@RunWith(Suite.class) -@SuiteClasses({ ApiKeyCommandTest.class, AuthCommandTest.class, ClusterCommandTest.class, - MessageCommandTest.class, MRCommandContextTest.class, TopicCommandTest.class, TraceCommandTest.class,}) - -public class JUnitTestSuite { - private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); - - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/MRCommandContextTest.java b/src/test/java/com/att/nsa/mr/tools/MRCommandContextTest.java deleted file mode 100644 index 23ef0a1..0000000 --- a/src/test/java/com/att/nsa/mr/tools/MRCommandContextTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertTrue; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.att.nsa.apiClient.http.HttpTracer; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.HostSelector; -import com.att.nsa.mr.client.MRClient; -import com.att.nsa.mr.client.MRPublisher.message; -import com.att.nsa.mr.test.support.MRBatchingPublisherMock.Entry; - -public class MRCommandContextTest { - private MRCommandContext command = null; - private String[] parts = new String[5]; - - @Before - public void setUp() throws Exception { - command = new MRCommandContext(); - - for (int i = 0; i < parts.length; i++) { - parts[i] = "String" + (i + 1); - } - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testRequestShutdown() { - - command.requestShutdown(); - assertTrue(true); - - } - - @Test - public void testShouldContinue() { - - command.shouldContinue(); - assertTrue(true); - - } - - @Test - public void testSetAuth() { - - command.setAuth("key", "pwd"); - assertTrue(true); - - } - - @Test - public void testClearAuth() { - - command.clearAuth(); - assertTrue(true); - - } - - @Test - public void testCheckClusterReady() { - - command.checkClusterReady(); - assertTrue(true); - - } - - @Test - public void testGetCluster() { - - command.getCluster(); - assertTrue(true); - - } - - @Test - public void testClearCluster() { - - command.clearCluster(); - assertTrue(true); - - } - - @Test - public void testAddClusterHost() { - - command.addClusterHost("host"); - assertTrue(true); - - } - - @Test - public void testGetApiKey() { - - command.getApiKey(); - assertTrue(true); - - } - - @Test - public void testGetApiPwd() { - - command.getApiPwd(); - assertTrue(true); - - } - - @Test - public void testUseTracer() { - - command.useTracer(null); - assertTrue(true); - - } - - @Test - public void testNoTracer() { - - command.noTracer(); - assertTrue(true); - - } - - @Test - public void testApplyTracer() { - - command.applyTracer(null); - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/MessageCommandTest.java b/src/test/java/com/att/nsa/mr/tools/MessageCommandTest.java deleted file mode 100644 index 638d067..0000000 --- a/src/test/java/com/att/nsa/mr/tools/MessageCommandTest.java +++ /dev/null @@ -1,214 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.MRTopicManager.TopicInfo; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ MRClientFactory.class, ToolsUtil.class }) -public class MessageCommandTest { - @InjectMocks - private MessageCommand command; - @Mock - private MRConsumer tm; - @Mock - private TopicInfo ti; - @Mock - private MRBatchingPublisher pub; - @Mock - private MRConsumer cc; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.mockStatic(ToolsUtil.class); - PowerMockito.when(MRClientFactory.createConsumer(Arrays.asList("localhost"), "testtopic", "2", "3", -1, -1, - null, null, null)).thenReturn(cc); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - assertTrue(true); - } - } - assertTrue(true); - - } - - @Test - public void testExecute_error1() { - try { - PowerMockito.doThrow(new Exception()).when(cc).fetch(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - assertTrue(true); - - } - - @Test - public void testExecute_error2() { - try { - PowerMockito.doThrow(new IOException()).when(pub).close(500, TimeUnit.MILLISECONDS); - PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - assertTrue(true); - - } - - /* - * @Test public void testExecute_error3() { - * - * try { PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); - * PowerMockito.doThrow(new InterruptedException()).when(pub).close(500, - * TimeUnit.MILLISECONDS); } catch (IOException e) { // TODO Auto-generated - * catch block e.printStackTrace(); } catch (InterruptedException e) { // - * TODO Auto-generated catch block e.printStackTrace(); } String[] parts1 = - * { "read", "testtopic", "2", "3" }; String[] parts2 = { "write", - * "testtopic", "2", "3" }; List parts = Arrays.asList(parts1, - * parts2); for (Iterator iterator = parts.iterator(); iterator.hasNext();) - * { String[] part = (String[]) iterator.next(); PrintStream printStream = - * new PrintStream(System.out); - * - * MRCommandContext context = new MRCommandContext(); - * PowerMockito.when(ToolsUtil.createBatchPublisher(context, - * "testtopic")).thenReturn(pub); try { command.execute(part, context, - * printStream); } catch (CommandNotReadyException e) { // TODO - * Auto-generated catch block e.printStackTrace(); } } assertTrue(true); - * - * } - */ - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/TestRunner.java b/src/test/java/com/att/nsa/mr/tools/TestRunner.java deleted file mode 100644 index 728752b..0000000 --- a/src/test/java/com/att/nsa/mr/tools/TestRunner.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.apache.log4j.Logger; - -public class TestRunner { - private static final Logger LOGGER = Logger.getLogger(TestRunner.class); - - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(result.wasSuccessful()); - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/ToolsUtilTest.java b/src/test/java/com/att/nsa/mr/tools/ToolsUtilTest.java deleted file mode 100644 index 69bdd44..0000000 --- a/src/test/java/com/att/nsa/mr/tools/ToolsUtilTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 Nokia - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * @author marcin.migdal@nokia.com - */ -package com.att.nsa.mr.tools; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import java.util.Arrays; -import java.util.List; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; - -public class ToolsUtilTest { - - private final static List clusters = Arrays.asList("Cluster1", "Cluster2"); - private final static String apiKey = "apiKey"; - private final static String apiPassword = "apiPassword"; - private final static String topicName = "topicName"; - - @Test - public void createBatchPublisher() { - MRCommandContext mrCommandContext = Mockito.mock(MRCommandContext.class); - Mockito.when(mrCommandContext.getCluster()).thenReturn(clusters); - Mockito.when(mrCommandContext.getApiKey()).thenReturn(apiKey); - Mockito.when(mrCommandContext.getApiPwd()).thenReturn(apiPassword); - - MRBatchingPublisher mrBatchingPublisher = ToolsUtil.createBatchPublisher(mrCommandContext, topicName); - - Assert.assertNotNull(mrBatchingPublisher); - } -} diff --git a/src/test/java/com/att/nsa/mr/tools/TopicCommandTest.java b/src/test/java/com/att/nsa/mr/tools/TopicCommandTest.java deleted file mode 100644 index 6459e6a..0000000 --- a/src/test/java/com/att/nsa/mr/tools/TopicCommandTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRTopicManager.TopicInfo; -import com.att.nsa.mr.client.MRTopicManager; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ MRClientFactory.class }) -public class TopicCommandTest { - @InjectMocks - private TopicCommand command; - @Mock - private MRTopicManager tm; - @Mock - private TopicInfo ti; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.when(MRClientFactory.createTopicManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenReturn(ti); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error() { - - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_1() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new IOException("error")); - PowerMockito.doThrow(new IOException()).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new IOException()).when(tm).revokeProducer("read", "1"); - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "read", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_2() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).revokeConsumer("read", "1"); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowConsumer("read", "1"); - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "write", "1" }; - String[] parts3 = { "revoke", "read", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_3() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowProducer("read", "1"); - String[] parts1 = { "create", "testtopic", "1a", "1a" }; - String[] parts2 = { "grant", "write", "read", "1" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/TraceCommandTest.java b/src/test/java/com/att/nsa/mr/tools/TraceCommandTest.java deleted file mode 100644 index 6ac106a..0000000 --- a/src/test/java/com/att/nsa/mr/tools/TraceCommandTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertTrue; - -import java.io.PrintStream; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.nsa.cmdtool.CommandNotReadyException; - -@RunWith(PowerMockRunner.class) -public class TraceCommandTest { - @InjectMocks - private TraceCommand command; - private String[] parts = new String[5]; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - for (int i = 0; i < parts.length; i++) { - parts[i] = "String" + (i + 1); - } - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - try { - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } - -} diff --git a/src/test/java/com/att/nsa/mr/tools/ValidatorUtilTest.java b/src/test/java/com/att/nsa/mr/tools/ValidatorUtilTest.java deleted file mode 100644 index ec382f4..0000000 --- a/src/test/java/com/att/nsa/mr/tools/ValidatorUtilTest.java +++ /dev/null @@ -1,315 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2018 IBM Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package com.att.nsa.mr.tools; - -import static org.junit.Assert.assertEquals; - -import java.util.Properties; - -import org.junit.Test; - -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; - -public class ValidatorUtilTest { - - @Test - public void testValidateForDME2WithNullServiceName() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Servicename is needed"); - } - - } - - @Test - public void testValidateForDME2WithNullTopic() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); - props.setProperty("ServiceName", "ServiceName"); - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "topic is needed"); - } - - } - - @Test - public void testValidateForDME2WithNullUserName() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); - props.setProperty("ServiceName", "ServiceName"); - props.setProperty("topic", "topic"); - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "username is needed"); - } - - } - - @Test - public void testValidateForDME2WithNullPassword() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); - props.setProperty("ServiceName", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "password is needed"); - } - - } - - - - - @Test - public void testValidateForNonDME2WithNullServiceName() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Servicename is needed"); - } - - } - - @Test - public void testValidateForNonDME2WithNullTopic() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "topic is needed"); - } - - } - - @Test - public void testValidateForNonDME2WithNullContenttype() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "contenttype is needed"); - } - - } - - - @Test - public void testValidateForNonDME2WithNullUserName() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("contenttype", "contenttype"); - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "username is needed"); - } - - } - - @Test - public void testValidateForNonDME2WithNullPassword() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "password is needed"); - } - - } - - @Test - public void testValidateForNonDME2WithAuthKey() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "authKey is needed"); - } - - } - - @Test - public void testValidateForNonDME2WithOutAuthDate() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "authDate is needed"); - } - } - - @Test - public void testValidateForNonDME2WithAuthDate() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "maxBatchSize is needed"); - } - } - - - @Test - public void testValidateForNonDME2WithMaxAgeMs() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "maxAgeMs is needed"); - } - - - - } - - @Test - public void testValidateForNonDME2WithMessageSentThreadOccurance() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "MessageSentThreadOccurance is needed"); - } - - } - - - @Test - public void testValidateSubscriberWithoutGroup() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - - try{ - ValidatorUtil.validateSubscriber(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "group is needed"); - } - } - - @Test - public void testValidateSubscriberWithoutCustomer() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - props.setProperty("group", "group"); - - try{ - ValidatorUtil.validateSubscriber(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Consumer (Id) is needed"); - } - } - - - - - -} diff --git a/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java b/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java new file mode 100644 index 0000000..ecc4b51 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client; + +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; + +public class HostSelectorTest { + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + + + @Test + public void testSelectBaseHost() { + + HostSelector selector = new HostSelector("host"); + + selector.selectBaseHost(); + assertTrue(true); + + + } + + @Test + public void testReportReachabilityProblem() { + + HostSelector selector = new HostSelector("host"); + + selector.reportReachabilityProblem(100, null); + assertTrue(true); + + + } +} + diff --git a/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java new file mode 100644 index 0000000..b791b51 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client; + +import junit.framework.TestSuite; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.apache.log4j.Logger; + +@RunWith(Suite.class) +@SuiteClasses({ HostSelectorTest.class, MRClientBuildersTest.class, MRClientFactoryTest.class}) + +public class JUnitTestSuite { + private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + LOGGER.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java b/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java new file mode 100644 index 0000000..388a91c --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java @@ -0,0 +1,248 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRClient; +import org.onap.dmaap.mr.client.MRClientBuilders; + +public class MRClientBuildersTest { + + private Collection hostSet = new ArrayList(); + private MRClientBuilders.ConsumerBuilder builder = null; + private MRClientBuilders.PublisherBuilder pBuilder = null; + private String[] hostArray = new String[10]; + + @Before + public void setUp() throws Exception { + + for (int i = 0; i < 10; i++) { + hostSet.add("host" + (i + 1)); + hostArray[i] = "host" + (i + 1); + } + + builder = new MRClientBuilders.ConsumerBuilder(); + + pBuilder = new MRClientBuilders.PublisherBuilder(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testUsingHosts() { + + builder.usingHosts("hostList"); + assertTrue(true); + + } + + @Test + public void testUsingHosts2() { + + builder.usingHosts(hostSet); + assertTrue(true); + + } + + @Test + public void testOnTopic() { + + builder.onTopic("testTopic"); + assertTrue(true); + + } + + @Test + public void testKnownAs() { + + builder.knownAs("CG1", "23"); + assertTrue(true); + + } + + @Test + public void testAuthenticatedBy() { + + builder.authenticatedBy("apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testWaitAtServer() { + + builder.waitAtServer(100); + assertTrue(true); + + } + + @Test + public void testReceivingAtMost() { + + builder.receivingAtMost(100); + assertTrue(true); + + } + + @Test + public void testWithServerSideFilter() { + + builder.withServerSideFilter("filter"); + assertTrue(true); + + } + + @Test + public void testBuild() { + + try { + + builder.build(); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + } + + @Test + public void testUsingHosts3() { + + pBuilder.usingHosts("testTopic"); + assertTrue(true); + + } + + @Test + public void testUsingHosts4() { + + pBuilder.usingHosts(hostArray); + assertTrue(true); + + } + + @Test + public void testUsingHosts5() { + + pBuilder.usingHosts(hostSet); + assertTrue(true); + + } + + @Test + public void testOnTopic2() { + + pBuilder.onTopic("testTopic"); + assertTrue(true); + + } + + @Test + public void testLimitBatch() { + + pBuilder.limitBatch(100, 10); + assertTrue(true); + + } + + @Test + public void testWithCompresion() { + + pBuilder.withCompresion(); + assertTrue(true); + + } + + @Test + public void testWithoutCompresion() { + + pBuilder.withoutCompresion(); + assertTrue(true); + + } + + @Test + public void testEnableCompresion() { + + pBuilder.enableCompresion(true); + assertTrue(true); + + } + + @Test + public void testAuthenticatedBy2() { + + pBuilder.authenticatedBy("apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testBuild2() { + + try { + + pBuilder.build(); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + } + + @Test + public void test$testInject() { + + try { + + MRClientBuilders.$testInject(builder.build()); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + } + + @Test + public void test$testInject2() { + + try { + + MRClientBuilders.$testInject(pBuilder.build()); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + } +} diff --git a/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java b/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java new file mode 100644 index 0000000..0d151b9 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java @@ -0,0 +1,252 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRClient; +import org.onap.dmaap.mr.client.MRClientBuilders; +import org.onap.dmaap.mr.client.MRClientFactory; + +public class MRClientFactoryTest { + + private Collection hostSet = new ArrayList(); + + private String[] hostArray = new String[10]; + + @Before + public void setUp() throws Exception { + + for (int i = 0; i < 10; i++) { + hostSet.add("host" + (i + 1)); + hostArray[i] = "host" + (i + 1); + } + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testCreateConsumer() { + + MRClientFactory.createConsumer("hostList hostList2", "testTopic"); + assertTrue(true); + + } + + @Test + public void testCreateConsumer2() { + + MRClientFactory.createConsumer(hostSet, "testTopic"); + assertTrue(true); + + } + + @Test + public void testCreateConsumer3() { + + MRClientFactory.createConsumer(hostSet, "testTopic", "filter"); + assertTrue(true); + + } + + @Test + public void testCreateConsumer4() { + + MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22"); + assertTrue(true); + + } + + @Test + public void testCreateConsumer5() { + + MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100); + assertTrue(true); + + } + + @Test + public void testCreateConsumer6() { + + MRClientFactory.createConsumer("hostList", "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testCreateConsumer7() { + + MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testCreateSimplePublisher() { + + MRClientFactory.createSimplePublisher("hostList", "testTopic"); + assertTrue(true); + + } + + @Test + public void testCreateBatchingPublisher1() { + + MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10); + assertTrue(true); + + } + + @Test + public void testCreateBatchingPublisher2() { + + MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10, true); + assertTrue(true); + + } + + @Test + public void testCreateBatchingPublisher3() { + + MRClientFactory.createBatchingPublisher(hostArray, "testTopic", 100, 10, true); + assertTrue(true); + + } + + @Test + public void testCreateBatchingPublisher4() { + + MRClientFactory.createBatchingPublisher(hostSet, "testTopic", 100, 10, true); + assertTrue(true); + + } + + @Test + public void testCreateBatchingPublisher5() { + + MRClientFactory.createBatchingPublisher("host", "testTopic", "username", "password", 100, 10, true, + "protocolFlag"); + assertTrue(true); + + } + + @Test + public void testCreateBatchingPublisher6() { + + try { + MRClientFactory.createBatchingPublisher("/producer"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testCreateBatchingPublisher7() { + + try { + MRClientFactory.createBatchingPublisher("/producer", true); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testCreateIdentityManager() { + + MRClientFactory.createIdentityManager(hostSet, "apikey", "apisecret"); + + assertTrue(true); + + } + + @Test + public void testCreateTopicManager() { + + MRClientFactory.createTopicManager(hostSet, "apikey", "apisecret"); + + assertTrue(true); + + } + + @Test + public void testCreateConsumer8() { + + try { + MRClientFactory.createConsumer("/consumer"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testCreateConsumer9() { + + MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", "protocolFlag", + "/consumer", 1, 2); + + assertTrue(true); + + } + + @Test + public void testCreateConsumer10() { + + MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", 1, 2, "protocolFlag", + "/consumer"); + + assertTrue(true); + + } + + @Test + public void test$testInject() { + + MRClientFactory.$testInject(null); + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/mr/client/TestRunner.java b/src/test/java/org/onap/dmaap/mr/client/TestRunner.java new file mode 100644 index 0000000..f9b8a86 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.apache.log4j.Logger; + +public class TestRunner { + private static final Logger LOGGER = Logger.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + LOGGER.info(failure.toString()); + + } + LOGGER.info(result.wasSuccessful()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java new file mode 100644 index 0000000..6fb31a6 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2018 IBM Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.Invocation.Builder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.att.aft.dme2.internal.jersey.core.spi.factory.ResponseImpl; + +public class DMaapClientUtilTest { + + Builder builder; + + Response response; + + WebTarget target; + + @Before + public void setup(){ + Mockito.mock(HttpServletRequest.class); + builder = Mockito.mock(Invocation.Builder.class); + response = Mockito.mock(Response.class); + target = Mockito.mock(WebTarget.class); + + } + + @Test + public void testGetTarget() throws IOException{ + WebTarget actual = DmaapClientUtil.getTarget("testpath"); + + assertEquals("testpath", actual.getUri().getPath()); + } + + @Test + public void testGetTargetWithParams() throws IOException{ + WebTarget actual = DmaapClientUtil.getTarget("testpath", "testuser", "testpassword"); + + assertEquals("testpath", actual.getUri().getPath()); + } + + @Test + public void testGetResponsewtCambriaAuth() { + Mockito.when(target.request()).thenReturn(builder); + Mockito.when(builder.header("X-CambriaAuth", "testuser")).thenReturn(builder); + Mockito.when(builder.header("X-CambriaDate", "testpassword")).thenReturn(builder); + Mockito.when(builder.get()).thenReturn(response); + + Response actual = DmaapClientUtil.getResponsewtCambriaAuth(target, "testuser", "testpassword"); + + assertEquals(response, actual); + } + + + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java new file mode 100644 index 0000000..6fe0e70 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java @@ -0,0 +1,471 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.MalformedURLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; + +import org.apache.http.HttpException; +import org.glassfish.jersey.internal.util.Base64; +import org.glassfish.jersey.internal.util.collection.StringKeyIgnoreCaseMultivaluedMap; +import org.json.JSONException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("org.apache.http.conn.ssl.*") +@PrepareForTest({ DmaapClientUtil.class }) +public class MRBaseClientTest { + + // @InjectMocks + private MRBaseClient mrBaseClient; + private Collection hosts = new HashSet<>(Arrays.asList("localhost:8080")); + private String clientSignature = "topic" + "::" + "cg" + "::" + "cid"; + + @Before + public void setup() throws MalformedURLException { + mrBaseClient = new MRBaseClient(hosts, clientSignature); + PowerMockito.mockStatic(DmaapClientUtil.class); + } + + @Test + public void testGet() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) + .thenReturn(response); + + mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testGet_403() throws JSONException, HttpException { + ResponseBuilder responseBuilder = Response.status(403); + PowerMockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testGet_basicauth() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), + Base64.encodeAsString("username:password"))).thenReturn(response); + + mrBaseClient.get("/path", "username", "password", "HTTPAAF"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testGet_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.get("/path", null, null, "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testGet_wrongjson() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("[["); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) + .thenReturn(response); + + mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); + } + + @Test + public void testGetResponse() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) + .thenReturn(response); + + mrBaseClient.getResponse("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testGetResponse_aaf() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), + Base64.encodeAsString("username:password"))).thenReturn(response); + + mrBaseClient.getResponse("/path", "username", "password", "HTTPAAF"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testGetResponse_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.getResponse("/path", null, null, "HTTPAUTH"); + + } + + @Test + public void testAuthResponse() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) + .thenReturn(response); + + mrBaseClient.getAuthResponse("/path", "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testAuthResponsee_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.getAuthResponse("/path", null, null, null, null, "HTTPAUTH"); + + } + + @Test + public void testPostAuth() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn(response); + + mrBaseClient.postAuth("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", "username", + "password", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testPostAuth_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.postAuth("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, null, + null, null, "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testGetNoAuthResponse() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget("/path"))).thenReturn(response); + + mrBaseClient.getNoAuthResponse("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testPost() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), + Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); + + mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", "username", + "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testPost_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), + Base64.encodeAsString("username:password"))) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, null, + "HTTPAUTH"); + + } + + @Test + public void testPostAuthwithResponse() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn(response); + + mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", + "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testPostAuthwithResponse_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", + null, null, null, null, "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testPostWithResponse() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), + Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); + + mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", + "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testPostWithResponse_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget("/path"), + Base64.encodeAsString("username:password"))) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, + null, "HTTPAUTH"); + + } + + @Test + public void testGetAuth() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", "password")) + .thenReturn(response); + mrBaseClient.getAuth("/path", "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testGetAuth_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + PowerMockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget("/path"), "username", + "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.getAuth("/path", null, null, null, null, "HTTPAUTH"); + assertTrue(true); + + } + + @Test + public void testGetNoAuth() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + PowerMockito.when(response.getStatus()).thenReturn(200); + PowerMockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + PowerMockito.when(response.getHeaders()).thenReturn(map); + + PowerMockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget("/path"))).thenReturn(response); + mrBaseClient.getNoAuth("/path"); + assertTrue(true); + + } + + + @Test + public void testGetHTTPErrorResponseMessage() { + + assertEquals(mrBaseClient.getHTTPErrorResponseMessage("testtest"), "testtest"); + + } + + @Test + public void getGTTPErrorResponseCode() { + + assertEquals(mrBaseClient.getHTTPErrorResponseMessage("testtest"), "testtest"); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java new file mode 100644 index 0000000..f13e7fa --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; + +import org.junit.Before; +import org.junit.Test; + +public class MRBatchPublisherTest { + + private Collection hosts=new HashSet<>(Arrays.asList("/test")); + private MRBatchPublisher mrBatchPublisher=new MRBatchPublisher(hosts, "topic", 2, 20, true); + + + @Before + public void setup(){ + + + } + + @Test + public void testSend() throws IOException{ + mrBatchPublisher.send("testmessage"); + } + + @Test + public void testClose() throws IOException{ + mrBatchPublisher.close(); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java new file mode 100644 index 0000000..3a427e0 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java @@ -0,0 +1,143 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import junit.framework.TestCase; + +import org.apache.http.HttpHost; +import org.junit.Test; + +import org.onap.dmaap.mr.client.impl.MRConstants; + +public class MRConstantsTest extends TestCase +{ + @Test + public void testPlainHost () throws IOException + { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl ( rawTopic ); + assertEquals ( "/events/" + "bar", result ); + } + + @Test + public void testHostWithProtocol () throws IOException + { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl ( rawTopic ); + assertEquals ( "/events/" + "bar", result ); + } + + @Test + public void testHostWithProtocolAndPort () throws IOException + { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl ( rawTopic ); + assertEquals ( "/events/" + "bar", result ); + } + + @Test + public void testHostWithPort () throws IOException + { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl ( rawTopic ); + assertEquals ( "/events/" + "bar", result ); + } + + @Test + public void testHostWithPortAndEscapedTopic () throws IOException + { + final String rawTopic = "bar?bell"; + final String result = MRConstants.makeUrl ( rawTopic ); + assertEquals ( "/events/" + "bar%3Fbell", result ); + } + + @Test + public void testConsumerPlainHost () throws IOException + { + final String rawTopic = "bar"; + final String rawGroup = "group"; + final String rawId = "id"; + final String result = MRConstants.makeConsumerUrl ( rawTopic, rawGroup, rawId ); + assertEquals ( "/events/" + "bar/group/id", result ); + } + + @Test + public void testCreateHostList () + { + final ArrayList in = new ArrayList (); + in.add ( "foo" ); + in.add ( "bar" ); + in.add ( "baz:80" ); + + final Collection hosts = MRConstants.createHostsList ( in ); + assertEquals ( 3, hosts.size () ); + + final Iterator it = hosts.iterator (); + final HttpHost first = it.next (); + assertEquals ( MRConstants.kStdMRServicePort, first.getPort () ); + assertEquals ( "foo", first.getHostName () ); + + final HttpHost second = it.next (); + assertEquals ( MRConstants.kStdMRServicePort, second.getPort () ); + assertEquals ( "bar", second.getHostName () ); + + final HttpHost third = it.next (); + assertEquals ( 80, third.getPort () ); + assertEquals ( "baz", third.getHostName () ); + } + + private static final String[][] hostTests = + { + { "host", "host", "" + MRConstants.kStdMRServicePort }, + { ":oops", null, "-1" }, + { "host:1.3", null, "-1" }, + { "host:13", "host", "13" }, + { "host:", "host", "" + MRConstants.kStdMRServicePort }, + }; + + @Test + public void testHostParse () + { + for ( String[] test : hostTests ) + { + final String hostIn = test[0]; + final String hostOut = test[1]; + final int portOut = Integer.parseInt ( test[2] ); + + try + { + final HttpHost hh = MRConstants.hostForString ( hostIn ); + assertEquals ( hostOut, hh.getHostName () ); + assertEquals ( portOut, hh.getPort () ); + } + catch ( IllegalArgumentException x ) + { + assertEquals ( -1, portOut ); + } + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java new file mode 100644 index 0000000..5d8dccd --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java @@ -0,0 +1,112 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.Properties; + +import junit.framework.TestCase; + +import org.junit.Test; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.impl.MRConstants; +import org.onap.dmaap.mr.client.impl.MRConsumerImpl; + +public class MRConsumerImplTest extends TestCase +{ + @Test + public void testNullFilter () throws IOException + { + final LinkedList hosts = new LinkedList (); + hosts.add ( "localhost:8080" ); + final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, null, null, null ); + final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), -1, -1 ); + assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); + } + + @Test + public void testFilterWithNoTimeoutOrLimit () throws IOException + { + final LinkedList hosts = new LinkedList (); + hosts.add ( "localhost:8080" ); + final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, "filter", null, null ); + final String url = c.createUrlPath ( MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid" ,"http"),-1, -1 ); + assertEquals ("http://localhost:8080/events/" + "topic/cg/cid?filter=filter", url ); + } + + @Test + public void testTimeoutNoLimitNoFilter () throws IOException + { + final LinkedList hosts = new LinkedList (); + hosts.add ( "localhost:8080" ); + final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", 30000, -1, null, null, null ); + final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), 30000, -1 ); + assertEquals ( "http://localhost:8080/events/" + "topic/cg/cid?timeout=30000", url ); + } + + @Test + public void testNoTimeoutWithLimitNoFilter () throws IOException + { + final LinkedList hosts = new LinkedList (); + hosts.add ( "localhost:8080" ); + final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, 100, null, null, null ); + final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), -1, 100 ); + assertEquals ( "http://localhost:8080/events/" + "topic/cg/cid?limit=100", url ); + } + + @Test + public void testWithTimeoutWithLimitWithFilter () throws IOException + { + final LinkedList hosts = new LinkedList (); + hosts.add ( "localhost:8080" ); + final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", 1000, 400, "f", null, null ); + final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid" ,"http"), 1000, 400 ); + assertEquals ("http://localhost:8080/events/" + "topic/cg/cid?timeout=1000&limit=400&filter=f", url ); + } + + @Test + public void testFilterEncoding () throws IOException + { + final LinkedList hosts = new LinkedList (); + hosts.add ( "localhost:8080" ); + final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, "{ \"foo\"=\"bar\"bar\" }", null, null ); + final String url = c.createUrlPath (MRConstants.makeConsumerUrl ( "localhost:8080", "topic", "cg", "cid","http" ), -1, -1 ); + assertEquals ( "http://localhost:8080/events/" + "topic/cg/cid?filter=%7B+%22foo%22%3D%22bar%22bar%22+%7D", url ); + } + + @Test + public void testFetchWithReturnConsumerResponse () throws IOException + { + final LinkedList hosts = new LinkedList (); + hosts.add ( "localhost:8080" ); + Properties properties = new Properties(); + properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + final MRConsumerImpl c = new MRConsumerImpl ( hosts, "topic", "cg", "cid", -1, -1, "{ \"foo\"=\"bar\"bar\" }", null, null ); + c.fetchWithReturnConsumerResponse(); + c.setProtocolFlag("HTTPAAF"); + c.fetchWithReturnConsumerResponse(); + assertTrue(true); + } +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java new file mode 100644 index 0000000..6c2b219 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.client.impl; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Set; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.Assert.assertTrue; + +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import org.onap.dmaap.mr.client.MRClient.MRApiException; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + + +public class MRMetaClientTest { + + @Rule public WireMockRule wireMock = new WireMockRule(); + + @Before + public void setUp(){ + wireMock.stubFor(get(urlEqualTo("/topics")) + .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); + wireMock.stubFor(get(urlEqualTo("/topics/topic1")) + .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); + wireMock.stubFor(post(urlEqualTo("/topics/create")) + .willReturn(aResponse().withStatus(200))); + } + + @Test + public void getTopicsTest() + { + final Collection hosts = new LinkedList (); + hosts.add ( "localhost:" + wireMock.port() ); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + Set setString=c.getTopics(); + } catch (IOException e) { + e.printStackTrace(); + } + + + // assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); + + } + + @Test + public void getTopicMetadataTest() { + final Collection hosts = new LinkedList (); + hosts.add ( "localhost:" + wireMock.port() ); + + final String topic ="topic1"; + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + TopicInfo topicInfo=c.getTopicMetadata(topic); + } catch (IOException | HttpObjectNotFoundException e) { + e.printStackTrace(); + } + + } + + @Test + public void testcreateTopic(){ + final Collection hosts = new LinkedList (); + hosts.add ( "localhost:" + wireMock.port() ); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + c.createTopic("topic1", "testTopic", 1, 1); + } catch (IOException | HttpException e) { + e.printStackTrace(); + } + } + @Test + public void testupdateApiKey(){ + final Collection hosts = new LinkedList (); + hosts.add ( "localhost:" + wireMock.port() ); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + c.updateCurrentApiKey("test@onap.com", "test email"); + }catch (HttpException e) { + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + catch (NullPointerException e) { + assertTrue(true); + } + + } + + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java new file mode 100644 index 0000000..af02c2f --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.client.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; + +public class MRSimplerBatchConsumerTest { + + File outFile; + @Before + public void setUp() throws Exception { + Properties properties = new Properties(); + properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + String routeFilePath="dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("DME2preferredRouterFilePath", MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + outFile = new File(file.getParent() + "/consumer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + } + + @Test + public void testSend() throws IOException, InterruptedException { + + final MRConsumer cc = MRClientFactory.createConsumer(outFile.getPath()); + + try { + for(String msg : cc.fetch()){ + System.out.println(msg); + } + } catch (Exception e) { + System.err.println ( e.getClass().getName () + ": " + e.getMessage () ); + } + + } + + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java new file mode 100644 index 0000000..2f9b519 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.client.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; + +public class MRSimplerBatchPublisherTest { + + File outFile; + @Before + public void setUp() throws Exception { + Properties properties = new Properties(); + properties.load(MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/producer.properties")); + + String routeFilePath="dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("DME2preferredRouterFilePath", MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + outFile = new File(file.getParent() + "/producer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + } + + @Test + public void testSend() throws IOException, InterruptedException { + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher)MRClientFactory.createBatchingPublisher(outFile.getPath()); + + //publish some messages + final JSONObject msg1 = new JSONObject (); + pub.send ( "MyPartitionKey", msg1.toString () ); + + final List stuck = pub.close ( 1, TimeUnit.SECONDS ); + if ( stuck.size () > 0 ) { + System.out.println( stuck.size() + " messages unsent" ); + } + else + { + System.out.println ( "Clean exit; all messages sent." ); + } + + + } + + @Test + public void testSendBatchWithResponse() throws IOException, InterruptedException { + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher)MRClientFactory.createBatchingPublisher(outFile.getPath(), true); + + //publish some messages + final JSONObject msg1 = new JSONObject (); + pub.send ( "MyPartitionKey", msg1.toString () ); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); + + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java new file mode 100644 index 0000000..1cfaef4 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client.response; + +import junit.framework.TestSuite; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.apache.log4j.Logger; + +@RunWith(Suite.class) +@SuiteClasses({ MRConsumerResponseTest.class, MRPublisherResponseTest.class,}) + +public class JUnitTestSuite { + private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + LOGGER.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java b/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java new file mode 100644 index 0000000..3f727a4 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client.response; + +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; + +public class MRConsumerResponseTest { + private MRConsumerResponse test = null; + + @Before + public void setUp() throws Exception { + test = new MRConsumerResponse(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetResponseCode() { + + test.getResponseCode(); + assertTrue(true); + + } + + @Test + public void testSetResponseCode() { + + test.setResponseCode("200"); + assertTrue(true); + + } + + @Test + public void testGetResponseMessage() { + + test.getResponseMessage(); + assertTrue(true); + + } + + @Test + public void testSetResponseMessage() { + + test.setResponseMessage("responseMessage"); + assertTrue(true); + + } + + @Test + public void testGetActualMessages() { + + test.getActualMessages(); + assertTrue(true); + + } + + @Test + public void testSetActualMessages() { + + test.setActualMessages(null); + assertTrue(true); + + } +} diff --git a/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java b/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java new file mode 100644 index 0000000..f4957db --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client.response; + +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; + +public class MRPublisherResponseTest { + private MRPublisherResponse response = null; + + @Before + public void setUp() throws Exception { + response = new MRPublisherResponse(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetResponseCode() { + + response.getResponseCode(); + assertTrue(true); + + } + + @Test + public void testSetResponseCode() { + + response.setResponseCode("200"); + assertTrue(true); + + } + + @Test + public void testGetResponseMessage() { + + response.getResponseMessage(); + assertTrue(true); + + } + + @Test + public void testSetResponseMessage() { + + response.setResponseMessage("responseMessage"); + assertTrue(true); + + } + + @Test + public void testGetPendingMsgs() { + + response.getPendingMsgs(); + assertTrue(true); + + } + + @Test + public void testSetPendingMsgs() { + + response.setPendingMsgs(5); + assertTrue(true); + + } + + @Test + public void testToString() { + + response.toString(); + assertTrue(true); + + } + + +} diff --git a/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java b/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java new file mode 100644 index 0000000..9bf5880 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.client.response; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.apache.log4j.Logger; + +public class TestRunner { + private static final Logger LOGGER = Logger.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + LOGGER.info(failure.toString()); + + } + LOGGER.info(result.wasSuccessful()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java new file mode 100644 index 0000000..b1c7e15 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.dme.client; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Listener; + +public class DefaultLoggingFailoverFaultHandlerTest { + private DefaultLoggingFailoverFaultHandler handler = null; + + @Before + public void setUp() throws Exception { + handler = new DefaultLoggingFailoverFaultHandler(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testHandleEndpointFailover() { + + /* handler.handleEndpointFailover(null); + assertTrue(true);*/ + + } + + @Test + public void testHandleRouteOfferFailover() { + + /* handler.handleRouteOfferFailover(null); + assertTrue(true); +*/ + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java new file mode 100644 index 0000000..df236c9 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.dme.client; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Listener; + +public class HeaderReplyHandlerTest { + private HeaderReplyHandler handler = null; + + @Before + public void setUp() throws Exception { + handler = new HeaderReplyHandler(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testHandleFault() { + + handler.handleFault(null); + assertTrue(true); + + } + + @Test + public void testHandleEndpointFault() { + + handler.handleEndpointFault(null); + assertTrue(true); + + } + + @Test + public void testHandleReply() { + + handler.handleReply(null); + assertTrue(true); + + } + + + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java new file mode 100644 index 0000000..0d4c69a --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.dme.client; + +import junit.framework.TestSuite; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.apache.log4j.Logger; + +@RunWith(Suite.class) +@SuiteClasses({ DefaultLoggingFailoverFaultHandlerTest.class, HeaderReplyHandlerTest.class,PreferredRouteReplyHandlerTest.class, + PreferredRouteRequestHandlerTest.class,SimpleExamplePublisherTest.class }) + +public class JUnitTestSuite { + private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + LOGGER.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java new file mode 100644 index 0000000..5aa3018 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.dme.client; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Listener; + +public class PreferredRouteReplyHandlerTest { + private PreferredRouteReplyHandler handler = null; + + @Before + public void setUp() throws Exception { + handler = new PreferredRouteReplyHandler(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testHandleReply() { + +// handler.handleReply(null); +// assertTrue(true); + + } + + @Test + public void testHandleFault() { +/* + handler.handleFault(null); + assertTrue(true); +*/ + } + + @Test + public void testHandleEndpointFault() { + +/* handler.handleEndpointFault(null); + assertTrue(true);*/ + + } + + @Test + public void testRouteWriter() { +/* + handler.routeWriter("routeKey", "routeValue"); + assertTrue(true); +*/ + } + + + + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java new file mode 100644 index 0000000..cf5b607 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.dme.client; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Listener; + +public class PreferredRouteRequestHandlerTest { + private PreferredRouteRequestHandler handler = null; + + @Before + public void setUp() throws Exception { + handler = new PreferredRouteRequestHandler(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testHandleRequest() { + + /* handler.handleRequest(null); + assertTrue(true);*/ + + } + + @Test + public void testReadRoute() { + +// try { +// handler.readRoute("routeKey"); +// } catch (NullPointerException e) { +// assertTrue(true); +// } +// +// assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java new file mode 100644 index 0000000..1240d8b --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.dme.client; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Listener; + +public class SimpleExamplePublisherTest { + private SimpleExamplePublisher pub = null; + + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisher(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testPublishMessage() { + + try { + pub.publishMessage("/producer"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java b/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java new file mode 100644 index 0000000..74928c9 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.dme.client; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.apache.log4j.Logger; + +public class TestRunner { + private static final Logger LOGGER = Logger.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + LOGGER.info(failure.toString()); + + } + LOGGER.info(result.wasSuccessful()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/logging/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/logging/JUnitTestSuite.java new file mode 100644 index 0000000..8828d1c --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/logging/JUnitTestSuite.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.logging; + +import junit.framework.TestSuite; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.apache.log4j.Logger; + +@RunWith(Suite.class) +@SuiteClasses({ MRAppenderTest.class, }) + +public class JUnitTestSuite { + private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + LOGGER.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/logging/MRAppenderTest.java b/src/test/java/org/onap/dmaap/mr/logging/MRAppenderTest.java new file mode 100644 index 0000000..8332606 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/logging/MRAppenderTest.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.logging; + +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; + +public class MRAppenderTest { + private MRAppender appender = null; + + @Before + public void setUp() throws Exception { + appender = new MRAppender(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testClose() { + try { + appender.close(); + } catch (NullPointerException e) { + assertTrue(true); + } + + assertTrue(true); + + } + + @Test + public void testRequiresLayout() { + + appender.requiresLayout(); + assertTrue(true); + + } + + @Test + public void testAppend() { + + try { + appender.append(null); + } catch (NullPointerException e) { + assertTrue(true); + } + + assertTrue(true); + + } + + @Test + public void testActivateOptions() { + + appender.activateOptions(); + assertTrue(true); + + } + + @Test + public void testGetTopic() { + + appender.getTopic(); + assertTrue(true); + + } + + @Test + public void testSetTopic() { + + appender.setTopic("testTopic"); + assertTrue(true); + + } + + @Test + public void testGetPartition() { + + appender.getPartition(); + assertTrue(true); + + } + + @Test + public void testSetPartition() { + + appender.setPartition("partition"); + assertTrue(true); + + } + + @Test + public void testGetHosts() { + + appender.getHosts(); + assertTrue(true); + + } + + @Test + public void testSetHosts() { + + appender.setHosts("hosts"); + assertTrue(true); + + } + + @Test + public void testGetMaxBatchSize() { + + appender.getMaxBatchSize(); + assertTrue(true); + + } + + @Test + public void testSetMaxBatchSize() { + + appender.setMaxBatchSize(20); + assertTrue(true); + + } + + @Test + public void testGetMaxAgeMs() { + + appender.getMaxAgeMs(); + assertTrue(true); + + } + + @Test + public void testSetMaxAgeMs() { + + appender.setMaxAgeMs(15); + assertTrue(true); + + } + + @Test + public void testIsCompress() { + + appender.isCompress(); + assertTrue(true); + + } + + @Test + public void testSetCompress() { + + appender.setCompress(true); + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/logging/TestRunner.java b/src/test/java/org/onap/dmaap/mr/logging/TestRunner.java new file mode 100644 index 0000000..8e77136 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/logging/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.logging; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.apache.log4j.Logger; + +public class TestRunner { + private static final Logger LOGGER = Logger.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + LOGGER.info(failure.toString()); + + } + LOGGER.info(result.wasSuccessful()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java new file mode 100644 index 0000000..218e6c8 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ConsolePublisherTest { + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testMain() { + + try { + ConsolePublisher.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java new file mode 100644 index 0000000..eb0ca3d --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import junit.framework.TestSuite; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.apache.log4j.Logger; + +@RunWith(Suite.class) +@SuiteClasses({ SimpleExamplePublisherTest.class, ProtocolTypeConstantsTest.class, + SampleConsumerTest.class, SamplePublisherTest.class, SimpleExampleConsumerTest.class, ConsolePublisherTest.class, + SimpleExamplePublisherWithResponseTest.class, SimpleExampleConsumerWithReturnResponseTest.class,}) + +public class JUnitTestSuite { + private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + LOGGER.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java new file mode 100644 index 0000000..52310bf --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ProtocolTypeConstantsTest { + private ProtocolTypeConstants constants = null; + + @Before + public void setUp() throws Exception { + // constants = new ProtocolTypeConstants(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetValue() { + + try { + constants.getValue(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java new file mode 100644 index 0000000..6c5d93f --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SampleConsumerTest { + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testMain() { + + try { + SampleConsumer.main( new String[0]); + } catch (Exception e) { + assertTrue(true); + } + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java new file mode 100644 index 0000000..3a012a7 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SamplePublisherTest { + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testMain() { + + try { + SamplePublisher.main( new String[0]); + } catch (Exception e) { + // TODO Auto-generated catch block + assertTrue(true); + } + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java new file mode 100644 index 0000000..310ea45 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SimpleExampleConsumerTest { + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testMain() { + + try { + SimpleExampleConsumer.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java new file mode 100644 index 0000000..3c3b3d7 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SimpleExampleConsumerWithReturnResponseTest { + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testMain() { + + try { + SimpleExampleConsumerWithReturnResponse.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block e.printStackTrace(); + } + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java new file mode 100644 index 0000000..43faf5e --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SimpleExamplePublisherTest { + private SimpleExamplePublisher pub = null; + + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisher(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testPublishMessage() { + try { + pub.publishMessage("/producer"); + } catch (NullPointerException e) { + assertTrue(true); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testMain() { + + try { + SimpleExamplePublisher.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java new file mode 100644 index 0000000..44dd7cf --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SimpleExamplePublisherWithResponseTest { + + private SimpleExamplePublisherWithResponse pub = null; + + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisherWithResponse(); + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testMain() { + + try { + SimpleExamplePublisherWithResponse.main( new String[0]); + } catch (Exception e) { + assertTrue(true); + } + assertTrue(true); + + } + + @Test + public void testPublishMessage() { + + try { + pub.publishMessage("/producer", 100); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java b/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java new file mode 100644 index 0000000..7e3d724 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.clients; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.apache.log4j.Logger; + +public class TestRunner { + private static final Logger LOGGER = Logger.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + LOGGER.info(failure.toString()); + + } + LOGGER.info(result.wasSuccessful()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java new file mode 100644 index 0000000..6c2e0fc --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.support; + +import junit.framework.TestSuite; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.apache.log4j.Logger; + +@RunWith(Suite.class) +@SuiteClasses({ MRBatchingPublisherMockTest.class, MRConsumerMockTest.class,}) + +public class JUnitTestSuite { + private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + LOGGER.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java new file mode 100644 index 0000000..1d6bd7c --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.support; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Listener; + +public class MRBatchingPublisherMockTest { + private MRBatchingPublisherMock pub = null; + + private MRBatchingPublisherMock.Entry entry = null; + + @Before + public void setUp() throws Exception { + pub = new MRBatchingPublisherMock(); + entry = pub.new Entry("partition", "msg"); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testToString() { + + entry.toString(); + assertTrue(true); + + } + + @Test + public void testAddListener() { + + pub.addListener(null); + assertTrue(true); + + } + + @Test + public void testGetCaptures() { + + pub.getCaptures(); + assertTrue(true); + + } + + @Test + public void testGetCaptures2() { + + pub.getCaptures(null); + assertTrue(true); + + } + + @Test + public void testReceived() { + + pub.received(); + assertTrue(true); + + } + + @Test + public void testResend() { + + pub.reset(); + assertTrue(true); + + } + + @Test + public void testSend() { + + pub.send("partition", "msg"); + assertTrue(true); + + } + + @Test + public void testSend2() { + + pub.send("msg"); + assertTrue(true); + + } + + @Test + public void testSend3() { + //sending message m obj + pub.send(new ArrayList()); + assertTrue(true); + + } + + @Test + public void testSend4() { + //sending collection of message m objects + pub.send(new message("partition", "msg")); + assertTrue(true); + + } + + @Test + public void testSendBatchWithResponse() { + + pub.sendBatchWithResponse(); + assertTrue(true); + + } + + @Test + public void testLogTo() { + + pub.logTo(null); + assertTrue(true); + + } + + @Test + public void testClearApiCredentials() { + + pub.clearApiCredentials(); + assertTrue(true); + + } + + @Test + public void testSetApiCredentials() { + + pub.setApiCredentials("apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testClose() { + + pub.close(); + assertTrue(true); + + } + + @Test + public void testClose2() { + + pub.close(100, null); + assertTrue(true); + + } + + @Test + public void testGetPendingMessageCount() { + + pub.getPendingMessageCount(); + assertTrue(true); + + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java new file mode 100644 index 0000000..9ae49e0 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.support; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Entry; + +public class MRConsumerMockTest { + private MRConsumerMock cons = null; + private MRConsumerMock.Entry entry = null; + + @Before + public void setUp() throws Exception { + cons = new MRConsumerMock(); + entry = cons.new Entry(100, 200, "statusMsg"); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testClose() { + + cons.close(); + assertTrue(true); + + } + + @Test + public void testRun() { + try { + entry.run(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testSetApiCredentials() { + cons.setApiCredentials("apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testClearApiCredentials() { + cons.clearApiCredentials(); + assertTrue(true); + + } + + @Test + public void testAdd() { + cons.add(entry); + assertTrue(true); + + } + + @Test + public void testAddImmediateMsg() { + cons.addImmediateMsg("ImmediateMsg"); + assertTrue(true); + + } + + @Test + public void testAddDelayedMsg() { + cons.addDelayedMsg(100, "msg"); + assertTrue(true); + + } + + @Test + public void testAddImmediateMsgGroup() { + cons.addImmediateMsgGroup(new ArrayList()); + assertTrue(true); + + } + + @Test + public void testAddDelayedMsgGroup() { + cons.addDelayedMsgGroup(100,new ArrayList()); + assertTrue(true); + + } + + @Test + public void testAddImmediateError() { + cons.addImmediateError(200, "OK"); + assertTrue(true); + + } + + @Test + public void testFetch() { + try { + cons.fetch(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testFetch2() { + try { + cons.fetch(100, 200); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testLogTo() { + cons.logTo(null); + assertTrue(true); + + } + + @Test + public void testFetchWithReturnConsumerResponse() { + cons.fetchWithReturnConsumerResponse(); + assertTrue(true); + + } + + @Test + public void testGetchWithReturnConsumerResponse() { + cons.fetchWithReturnConsumerResponse(100,200); + assertTrue(true); + + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java b/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java new file mode 100644 index 0000000..0a09a14 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.test.support; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.apache.log4j.Logger; + +public class TestRunner { + private static final Logger LOGGER = Logger.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + LOGGER.info(failure.toString()); + + } + LOGGER.info(result.wasSuccessful()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java new file mode 100644 index 0000000..e022bf5 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java @@ -0,0 +1,217 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.MRClient.MRApiException; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRIdentityManager; +import org.onap.dmaap.mr.client.MRIdentityManager.ApiKey; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ MRClientFactory.class }) +public class ApiKeyCommandTest { + + @InjectMocks + private ApiKeyCommand command; + @Mock + private MRIdentityManager tm; + @Mock + private ApiKey ti; + @Mock + private ApiKey key; + @Mock + private ApiCredential ac; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.when(MRClientFactory.createIdentityManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); + PowerMockito.when(tm.getApiKey("testtopic")).thenReturn(key); + PowerMockito.when(tm.createApiKey("testtopic", "1")).thenReturn(ac); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = { "create", "testtopic", "1" }; + String[] parts2 = { "list", "testtopic", "1" }; + String[] parts3 = { "revoke", "write", "read" }; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testExecute_error1() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new IOException("error")); + String[] parts1 = { "create", "testtopic", "1" }; + String[] parts2 = { "list", "testtopic", "1" }; + String[] parts3 = { "revoke", "write", "read" }; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + } + + } + + @Test + public void testExecute_error2() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new MRApiException("error")); + String[] parts1 = { "create", "testtopic", "1" }; + String[] parts2 = { "list", "testtopic", "1" }; + String[] parts3 = { "revoke", "write", "read" }; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(),printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testExecute_error3() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpException(500, "error")); + String[] parts1 = { "create", "testtopic", "1" }; + String[] parts2 = { "list", "testtopic", "1" }; + String[] parts3 = { "revoke", "write", "read" }; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + } + + } + + @Test + public void testExecute_error4() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); + String[] parts1 = { "create", "testtopic", "1" }; + String[] parts2 = { "list", "testtopic", "1" }; + String[] parts3 = { "revoke", "write", "read" }; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java new file mode 100644 index 0000000..9f9011a --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertTrue; + +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.cmdtool.CommandNotReadyException; + +@RunWith(PowerMockRunner.class) +public class AuthCommandTest { + @InjectMocks + private AuthCommand command = null; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + try { + String[] parts = new String[5]; + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute1() { + + try { + String[] parts = { "userName", "password" }; + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java new file mode 100644 index 0000000..0dc2f64 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertTrue; + +import java.io.FileNotFoundException; +import java.io.PrintStream; +import java.util.Arrays; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.cmdtool.CommandNotReadyException; + +@RunWith(PowerMockRunner.class) +public class ClusterCommandTest { + @InjectMocks + private ClusterCommand command; + @Mock + private MRCommandContext context; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.when(context.getCluster()).thenReturn(Arrays.asList("localhost")); + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(context); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() throws FileNotFoundException, CommandNotReadyException { + String[] parts = { "create", "testtopic", "1", "1" }; + command.execute(parts, context, printStream); + assertTrue(true); + + } + + @Test + public void testExecute1() throws FileNotFoundException, CommandNotReadyException { + String[] parts = {}; + command.execute(parts, context, printStream); + assertTrue(true); + + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java new file mode 100644 index 0000000..ca79f9b --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import junit.framework.TestSuite; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.apache.log4j.Logger; + +@RunWith(Suite.class) +@SuiteClasses({ ApiKeyCommandTest.class, AuthCommandTest.class, ClusterCommandTest.class, + MessageCommandTest.class, MRCommandContextTest.class, TopicCommandTest.class, TraceCommandTest.class,}) + +public class JUnitTestSuite { + private static final Logger LOGGER = Logger.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + LOGGER.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java b/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java new file mode 100644 index 0000000..038e321 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertTrue; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.att.nsa.apiClient.http.HttpTracer; +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRClient; +import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.test.support.MRBatchingPublisherMock.Entry; + +public class MRCommandContextTest { + private MRCommandContext command = null; + private String[] parts = new String[5]; + + @Before + public void setUp() throws Exception { + command = new MRCommandContext(); + + for (int i = 0; i < parts.length; i++) { + parts[i] = "String" + (i + 1); + } + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testRequestShutdown() { + + command.requestShutdown(); + assertTrue(true); + + } + + @Test + public void testShouldContinue() { + + command.shouldContinue(); + assertTrue(true); + + } + + @Test + public void testSetAuth() { + + command.setAuth("key", "pwd"); + assertTrue(true); + + } + + @Test + public void testClearAuth() { + + command.clearAuth(); + assertTrue(true); + + } + + @Test + public void testCheckClusterReady() { + + command.checkClusterReady(); + assertTrue(true); + + } + + @Test + public void testGetCluster() { + + command.getCluster(); + assertTrue(true); + + } + + @Test + public void testClearCluster() { + + command.clearCluster(); + assertTrue(true); + + } + + @Test + public void testAddClusterHost() { + + command.addClusterHost("host"); + assertTrue(true); + + } + + @Test + public void testGetApiKey() { + + command.getApiKey(); + assertTrue(true); + + } + + @Test + public void testGetApiPwd() { + + command.getApiPwd(); + assertTrue(true); + + } + + @Test + public void testUseTracer() { + + command.useTracer(null); + assertTrue(true); + + } + + @Test + public void testNoTracer() { + + command.noTracer(); + assertTrue(true); + + } + + @Test + public void testApplyTracer() { + + command.applyTracer(null); + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java new file mode 100644 index 0000000..f32cb43 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java @@ -0,0 +1,214 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ MRClientFactory.class, ToolsUtil.class }) +public class MessageCommandTest { + @InjectMocks + private MessageCommand command; + @Mock + private MRConsumer tm; + @Mock + private TopicInfo ti; + @Mock + private MRBatchingPublisher pub; + @Mock + private MRConsumer cc; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.mockStatic(ToolsUtil.class); + PowerMockito.when(MRClientFactory.createConsumer(Arrays.asList("localhost"), "testtopic", "2", "3", -1, -1, + null, null, null)).thenReturn(cc); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = { "read", "testtopic", "2", "3" }; + String[] parts2 = { "write", "testtopic", "2", "3" }; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + assertTrue(true); + } + } + assertTrue(true); + + } + + @Test + public void testExecute_error1() { + try { + PowerMockito.doThrow(new Exception()).when(cc).fetch(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String[] parts1 = { "read", "testtopic", "2", "3" }; + String[] parts2 = { "write", "testtopic", "2", "3" }; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + assertTrue(true); + + } + + @Test + public void testExecute_error2() { + try { + PowerMockito.doThrow(new IOException()).when(pub).close(500, TimeUnit.MILLISECONDS); + PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String[] parts1 = { "read", "testtopic", "2", "3" }; + String[] parts2 = { "write", "testtopic", "2", "3" }; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + assertTrue(true); + + } + + /* + * @Test public void testExecute_error3() { + * + * try { PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); + * PowerMockito.doThrow(new InterruptedException()).when(pub).close(500, + * TimeUnit.MILLISECONDS); } catch (IOException e) { // TODO Auto-generated + * catch block e.printStackTrace(); } catch (InterruptedException e) { // + * TODO Auto-generated catch block e.printStackTrace(); } String[] parts1 = + * { "read", "testtopic", "2", "3" }; String[] parts2 = { "write", + * "testtopic", "2", "3" }; List parts = Arrays.asList(parts1, + * parts2); for (Iterator iterator = parts.iterator(); iterator.hasNext();) + * { String[] part = (String[]) iterator.next(); PrintStream printStream = + * new PrintStream(System.out); + * + * MRCommandContext context = new MRCommandContext(); + * PowerMockito.when(ToolsUtil.createBatchPublisher(context, + * "testtopic")).thenReturn(pub); try { command.execute(part, context, + * printStream); } catch (CommandNotReadyException e) { // TODO + * Auto-generated catch block e.printStackTrace(); } } assertTrue(true); + * + * } + */ + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java b/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java new file mode 100644 index 0000000..fff3bd7 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.apache.log4j.Logger; + +public class TestRunner { + private static final Logger LOGGER = Logger.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + LOGGER.info(failure.toString()); + + } + LOGGER.info(result.wasSuccessful()); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java b/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java new file mode 100644 index 0000000..080d6d5 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/** + * @author marcin.migdal@nokia.com + */ +package org.onap.dmaap.mr.tools; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +public class ToolsUtilTest { + + private final static List clusters = Arrays.asList("Cluster1", "Cluster2"); + private final static String apiKey = "apiKey"; + private final static String apiPassword = "apiPassword"; + private final static String topicName = "topicName"; + + @Test + public void createBatchPublisher() { + MRCommandContext mrCommandContext = Mockito.mock(MRCommandContext.class); + Mockito.when(mrCommandContext.getCluster()).thenReturn(clusters); + Mockito.when(mrCommandContext.getApiKey()).thenReturn(apiKey); + Mockito.when(mrCommandContext.getApiPwd()).thenReturn(apiPassword); + + MRBatchingPublisher mrBatchingPublisher = ToolsUtil.createBatchPublisher(mrCommandContext, topicName); + + Assert.assertNotNull(mrBatchingPublisher); + } +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java new file mode 100644 index 0000000..e8dd073 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.CommandNotReadyException; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; +import org.onap.dmaap.mr.client.MRTopicManager; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ MRClientFactory.class }) +public class TopicCommandTest { + @InjectMocks + private TopicCommand command; + @Mock + private MRTopicManager tm; + @Mock + private TopicInfo ti; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.when(MRClientFactory.createTopicManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenReturn(ti); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = { "create", "testtopic", "1", "1" }; + String[] parts2 = { "grant", "write", "read", "1" }; + String[] parts3 = { "revoke", "write", "read", "1" }; + String[] parts4 = { "list", "testtopic", "1", "1" }; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error() { + + String[] parts1 = { "create", "testtopic", "1", "1" }; + String[] parts2 = { "grant", "write", "read", "1" }; + String[] parts3 = { "revoke", "write", "read", "1" }; + String[] parts4 = { "list", "testtopic", "1", "1" }; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_1() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new IOException("error")); + PowerMockito.doThrow(new IOException()).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new IOException()).when(tm).revokeProducer("read", "1"); + String[] parts1 = { "create", "testtopic", "1", "1" }; + String[] parts2 = { "grant", "read", "read", "1" }; + String[] parts3 = { "revoke", "write", "read", "1" }; + String[] parts4 = { "list", "testtopic", "1", "1" }; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_2() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).revokeConsumer("read", "1"); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowConsumer("read", "1"); + String[] parts1 = { "create", "testtopic", "1", "1" }; + String[] parts2 = { "grant", "write", "write", "1" }; + String[] parts3 = { "revoke", "read", "read", "1" }; + String[] parts4 = { "list", "testtopic", "1", "1" }; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_3() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowProducer("read", "1"); + String[] parts1 = { "create", "testtopic", "1a", "1a" }; + String[] parts2 = { "grant", "write", "read", "1" }; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext();) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java new file mode 100644 index 0000000..de76acd --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertTrue; + +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.cmdtool.CommandNotReadyException; + +@RunWith(PowerMockRunner.class) +public class TraceCommandTest { + @InjectMocks + private TraceCommand command; + private String[] parts = new String[5]; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + for (int i = 0; i < parts.length; i++) { + parts[i] = "String" + (i + 1); + } + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + try { + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java b/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java new file mode 100644 index 0000000..1306a30 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java @@ -0,0 +1,315 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2018 IBM Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.tools; + +import static org.junit.Assert.assertEquals; + +import java.util.Properties; + +import org.junit.Test; + +import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; + +public class ValidatorUtilTest { + + @Test + public void testValidateForDME2WithNullServiceName() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "Servicename is needed"); + } + + } + + @Test + public void testValidateForDME2WithNullTopic() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("ServiceName", "ServiceName"); + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "topic is needed"); + } + + } + + @Test + public void testValidateForDME2WithNullUserName() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("ServiceName", "ServiceName"); + props.setProperty("topic", "topic"); + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "username is needed"); + } + + } + + @Test + public void testValidateForDME2WithNullPassword() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("ServiceName", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "password is needed"); + } + + } + + + + + @Test + public void testValidateForNonDME2WithNullServiceName() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "Servicename is needed"); + } + + } + + @Test + public void testValidateForNonDME2WithNullTopic() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "topic is needed"); + } + + } + + @Test + public void testValidateForNonDME2WithNullContenttype() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "contenttype is needed"); + } + + } + + + @Test + public void testValidateForNonDME2WithNullUserName() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("contenttype", "contenttype"); + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "username is needed"); + } + + } + + @Test + public void testValidateForNonDME2WithNullPassword() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "password is needed"); + } + + } + + @Test + public void testValidateForNonDME2WithAuthKey() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "authKey is needed"); + } + + } + + @Test + public void testValidateForNonDME2WithOutAuthDate() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + + + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "authDate is needed"); + } + } + + @Test + public void testValidateForNonDME2WithAuthDate() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "maxBatchSize is needed"); + } + } + + + @Test + public void testValidateForNonDME2WithMaxAgeMs() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "maxAgeMs is needed"); + } + + + + } + + @Test + public void testValidateForNonDME2WithMessageSentThreadOccurance() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + + try{ + ValidatorUtil.validatePublisher(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "MessageSentThreadOccurance is needed"); + } + + } + + + @Test + public void testValidateSubscriberWithoutGroup() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + + try{ + ValidatorUtil.validateSubscriber(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "group is needed"); + } + } + + @Test + public void testValidateSubscriberWithoutCustomer() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + props.setProperty("group", "group"); + + try{ + ValidatorUtil.validateSubscriber(props); + } catch(IllegalArgumentException e) { + assertEquals(e.getMessage(), "Consumer (Id) is needed"); + } + } + + + + + +} diff --git a/version.properties b/version.properties index c31717c..ad77b29 100644 --- a/version.properties +++ b/version.properties @@ -27,7 +27,7 @@ major=1 minor=1 -patch=8 +patch=9 base_version=${major}.${minor}.${patch} -- cgit 1.2.3-korg