From 357b7483c755ad7e5d67d48c9f6013a64ee3fdd3 Mon Sep 17 00:00:00 2001 From: sunil unnava Date: Wed, 24 Oct 2018 15:20:01 -0400 Subject: update the package name Issue-ID: DMAAP-858 Change-Id: I59c824c2c913de32e59a7300e88fdffcdd7b32ed Signed-off-by: sunil unnava --- ajsc-shared-config/etc/logback.xml | 46 +- .../dmaap_v1/dmaap/v1/conf/FileMonitorBeans.xml | 6 +- .../dmaap_v1/dmaap/v1/conf/HelloWorldBeans.xml | 2 +- .../ajsc/dmaap_v1/dmaap/v1/conf/jaxrsBeans.groovy | 20 +- .../ajsc/dmaap_v1/dmaap/v1/conf/serviceBeans.xml | 42 +- .../dmaap_v1/dmaap/v1/routes/topicService.route | 4 +- src/main/config/runner-web.xml | 2 +- .../att/nsa/dmaap/DMaaPCambriaExceptionMapper.java | 143 --- .../com/att/nsa/dmaap/DMaaPWebExceptionMapper.java | 202 ---- src/main/java/com/att/nsa/dmaap/HelloWorld.java | 42 - .../java/com/att/nsa/dmaap/JaxrsEchoService.java | 91 -- .../java/com/att/nsa/dmaap/JaxrsUserService.java | 59 - .../filemonitor/ServicePropertiesListener.java | 42 - .../dmaap/filemonitor/ServicePropertiesMap.java | 120 -- .../dmaap/filemonitor/ServicePropertyService.java | 164 --- .../att/nsa/dmaap/mmagent/CreateMirrorMaker.java | 76 -- .../com/att/nsa/dmaap/mmagent/MMAgentUtil.java | 430 ------- .../com/att/nsa/dmaap/mmagent/MirrorMaker.java | 88 -- .../att/nsa/dmaap/mmagent/UpdateMirrorMaker.java | 83 -- .../com/att/nsa/dmaap/mmagent/UpdateWhiteList.java | 44 - .../att/nsa/dmaap/service/AdminRestService.java | 282 ----- .../att/nsa/dmaap/service/ApiKeysRestService.java | 254 ---- .../att/nsa/dmaap/service/EventsRestService.java | 378 ------ .../com/att/nsa/dmaap/service/MMRestService.java | 1259 -------------------- .../att/nsa/dmaap/service/MetricsRestService.java | 152 --- .../com/att/nsa/dmaap/service/ServiceUtil.java | 39 - .../att/nsa/dmaap/service/TopicRestService.java | 696 ----------- .../nsa/dmaap/service/TransactionRestService.java | 176 --- .../com/att/nsa/dmaap/service/UIRestServices.java | 198 --- .../java/com/att/nsa/dmaap/tools/ConfigTool.java | 818 ------------- .../com/att/nsa/dmaap/tools/ConfigToolContext.java | 69 -- .../nsa/dmaap/util/ContentLengthInterceptor.java | 138 --- .../com/att/nsa/dmaap/util/DMaaPAuthFilter.java | 90 -- .../nsa/dmaap/util/ServicePropertiesMapBean.java | 41 - .../onap/dmaap/DMaaPCambriaExceptionMapper.java | 143 +++ .../org/onap/dmaap/DMaaPWebExceptionMapper.java | 202 ++++ src/main/java/org/onap/dmaap/HelloWorld.java | 42 + src/main/java/org/onap/dmaap/JaxrsEchoService.java | 91 ++ src/main/java/org/onap/dmaap/JaxrsUserService.java | 59 + .../filemonitor/ServicePropertiesListener.java | 42 + .../dmaap/filemonitor/ServicePropertiesMap.java | 120 ++ .../dmaap/filemonitor/ServicePropertyService.java | 164 +++ .../org/onap/dmaap/mmagent/CreateMirrorMaker.java | 76 ++ .../java/org/onap/dmaap/mmagent/MMAgentUtil.java | 430 +++++++ .../java/org/onap/dmaap/mmagent/MirrorMaker.java | 88 ++ .../org/onap/dmaap/mmagent/UpdateMirrorMaker.java | 83 ++ .../org/onap/dmaap/mmagent/UpdateWhiteList.java | 44 + .../org/onap/dmaap/service/AdminRestService.java | 282 +++++ .../org/onap/dmaap/service/ApiKeysRestService.java | 254 ++++ .../org/onap/dmaap/service/EventsRestService.java | 378 ++++++ .../java/org/onap/dmaap/service/MMRestService.java | 1259 ++++++++++++++++++++ .../org/onap/dmaap/service/MetricsRestService.java | 152 +++ .../java/org/onap/dmaap/service/ServiceUtil.java | 39 + .../org/onap/dmaap/service/TopicRestService.java | 696 +++++++++++ .../onap/dmaap/service/TransactionRestService.java | 176 +++ .../org/onap/dmaap/service/UIRestServices.java | 198 +++ src/main/java/org/onap/dmaap/tools/ConfigTool.java | 818 +++++++++++++ .../org/onap/dmaap/tools/ConfigToolContext.java | 69 ++ .../onap/dmaap/util/ContentLengthInterceptor.java | 138 +++ .../java/org/onap/dmaap/util/DMaaPAuthFilter.java | 90 ++ .../onap/dmaap/util/ServicePropertiesMapBean.java | 41 + src/main/test/com/att/nsa/dmaap/DummyTest.java | 2 +- .../nsa/dmaap/DMaaPCambriaExceptionMapperTest.java | 86 -- .../att/nsa/dmaap/DMaaPWebExceptionMapperTest.java | 142 --- src/test/java/com/att/nsa/dmaap/DummyTest.java | 45 - .../java/com/att/nsa/dmaap/HelloWorldTest.java | 52 - .../java/com/att/nsa/dmaap/JUnitTestSuite.java | 43 - .../com/att/nsa/dmaap/JaxrsEchoServiceTest.java | 60 - .../com/att/nsa/dmaap/JaxrsUserServiceTest.java | 50 - src/test/java/com/att/nsa/dmaap/TestRunner.java | 41 - .../att/nsa/dmaap/filemonitor/JUnitTestSuite.java | 43 - .../filemonitor/ServicePropertiesListenerTest.java | 57 - .../filemonitor/ServicePropertiesMapTest.java | 128 -- .../filemonitor/ServicePropertyServiceTest.java | 153 --- .../com/att/nsa/dmaap/filemonitor/TestRunner.java | 41 - .../nsa/dmaap/mmagent/CreateMirrorMakerTest.java | 82 -- .../com/att/nsa/dmaap/mmagent/JUnitTestSuite.java | 43 - .../com/att/nsa/dmaap/mmagent/MirrorMakerTest.java | 142 --- .../java/com/att/nsa/dmaap/mmagent/TestRunner.java | 41 - .../nsa/dmaap/mmagent/UpdateMirrorMakerTest.java | 81 -- .../att/nsa/dmaap/mmagent/UpdateWhiteListTest.java | 85 -- .../nsa/dmaap/service/AdminRestServiceTest.java | 295 ----- .../nsa/dmaap/service/ApiKeysRestServiceTest.java | 232 ---- .../nsa/dmaap/service/EventsRestServiceTest.java | 328 ----- .../com/att/nsa/dmaap/service/JUnitTestSuite.java | 44 - .../att/nsa/dmaap/service/MMRestServiceTest.java | 384 ------ .../nsa/dmaap/service/MetricsRestServiceTest.java | 74 -- .../java/com/att/nsa/dmaap/service/TestRunner.java | 41 - .../nsa/dmaap/service/TopicRestServiceTest.java | 838 ------------- .../dmaap/service/TransactionRestServiceTest.java | 123 -- .../att/nsa/dmaap/service/UIRestServicesTest.java | 142 --- .../att/nsa/dmaap/tools/ConfigToolContextTest.java | 86 -- .../com/att/nsa/dmaap/tools/ConfigToolTest.java | 523 -------- .../com/att/nsa/dmaap/tools/JUnitTestSuite.java | 42 - .../java/com/att/nsa/dmaap/tools/TestRunner.java | 41 - .../dmaap/util/ContentLengthInterceptorTest.java | 93 -- .../att/nsa/dmaap/util/DMaaPAuthFilterTest.java | 100 -- .../com/att/nsa/dmaap/util/JUnitTestSuite.java | 42 - .../dmaap/util/ServicePropertiesMapBeanTest.java | 53 - .../java/com/att/nsa/dmaap/util/TestRunner.java | 41 - .../dmaap/DMaaPCambriaExceptionMapperTest.java | 86 ++ .../onap/dmaap/DMaaPWebExceptionMapperTest.java | 142 +++ src/test/java/org/onap/dmaap/DummyTest.java | 45 + src/test/java/org/onap/dmaap/HelloWorldTest.java | 52 + src/test/java/org/onap/dmaap/JUnitTestSuite.java | 43 + .../java/org/onap/dmaap/JaxrsEchoServiceTest.java | 60 + .../java/org/onap/dmaap/JaxrsUserServiceTest.java | 50 + src/test/java/org/onap/dmaap/TestRunner.java | 41 + .../org/onap/dmaap/filemonitor/JUnitTestSuite.java | 43 + .../filemonitor/ServicePropertiesListenerTest.java | 57 + .../filemonitor/ServicePropertiesMapTest.java | 128 ++ .../filemonitor/ServicePropertyServiceTest.java | 153 +++ .../org/onap/dmaap/filemonitor/TestRunner.java | 41 + .../onap/dmaap/mmagent/CreateMirrorMakerTest.java | 82 ++ .../org/onap/dmaap/mmagent/JUnitTestSuite.java | 43 + .../org/onap/dmaap/mmagent/MirrorMakerTest.java | 142 +++ .../java/org/onap/dmaap/mmagent/TestRunner.java | 41 + .../onap/dmaap/mmagent/UpdateMirrorMakerTest.java | 81 ++ .../onap/dmaap/mmagent/UpdateWhiteListTest.java | 85 ++ .../onap/dmaap/service/AdminRestServiceTest.java | 295 +++++ .../onap/dmaap/service/ApiKeysRestServiceTest.java | 232 ++++ .../onap/dmaap/service/EventsRestServiceTest.java | 328 +++++ .../org/onap/dmaap/service/JUnitTestSuite.java | 44 + .../org/onap/dmaap/service/MMRestServiceTest.java | 384 ++++++ .../onap/dmaap/service/MetricsRestServiceTest.java | 74 ++ .../java/org/onap/dmaap/service/TestRunner.java | 41 + .../onap/dmaap/service/TopicRestServiceTest.java | 838 +++++++++++++ .../dmaap/service/TransactionRestServiceTest.java | 123 ++ .../org/onap/dmaap/service/UIRestServicesTest.java | 142 +++ .../onap/dmaap/tools/ConfigToolContextTest.java | 86 ++ .../java/org/onap/dmaap/tools/ConfigToolTest.java | 523 ++++++++ .../java/org/onap/dmaap/tools/JUnitTestSuite.java | 42 + src/test/java/org/onap/dmaap/tools/TestRunner.java | 41 + .../dmaap/util/ContentLengthInterceptorTest.java | 93 ++ .../org/onap/dmaap/util/DMaaPAuthFilterTest.java | 100 ++ .../java/org/onap/dmaap/util/JUnitTestSuite.java | 42 + .../dmaap/util/ServicePropertiesMapBeanTest.java | 53 + src/test/java/org/onap/dmaap/util/TestRunner.java | 41 + 138 files changed, 11175 insertions(+), 11171 deletions(-) delete mode 100644 src/main/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapper.java delete mode 100644 src/main/java/com/att/nsa/dmaap/DMaaPWebExceptionMapper.java delete mode 100644 src/main/java/com/att/nsa/dmaap/HelloWorld.java delete mode 100644 src/main/java/com/att/nsa/dmaap/JaxrsEchoService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/JaxrsUserService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesListener.java delete mode 100644 src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMap.java delete mode 100644 src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertyService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/mmagent/CreateMirrorMaker.java delete mode 100644 src/main/java/com/att/nsa/dmaap/mmagent/MMAgentUtil.java delete mode 100644 src/main/java/com/att/nsa/dmaap/mmagent/MirrorMaker.java delete mode 100644 src/main/java/com/att/nsa/dmaap/mmagent/UpdateMirrorMaker.java delete mode 100644 src/main/java/com/att/nsa/dmaap/mmagent/UpdateWhiteList.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/AdminRestService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/ApiKeysRestService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/EventsRestService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/MMRestService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/MetricsRestService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/ServiceUtil.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/TopicRestService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/TransactionRestService.java delete mode 100644 src/main/java/com/att/nsa/dmaap/service/UIRestServices.java delete mode 100644 src/main/java/com/att/nsa/dmaap/tools/ConfigTool.java delete mode 100644 src/main/java/com/att/nsa/dmaap/tools/ConfigToolContext.java delete mode 100644 src/main/java/com/att/nsa/dmaap/util/ContentLengthInterceptor.java delete mode 100644 src/main/java/com/att/nsa/dmaap/util/DMaaPAuthFilter.java delete mode 100644 src/main/java/com/att/nsa/dmaap/util/ServicePropertiesMapBean.java create mode 100644 src/main/java/org/onap/dmaap/DMaaPCambriaExceptionMapper.java create mode 100644 src/main/java/org/onap/dmaap/DMaaPWebExceptionMapper.java create mode 100644 src/main/java/org/onap/dmaap/HelloWorld.java create mode 100644 src/main/java/org/onap/dmaap/JaxrsEchoService.java create mode 100644 src/main/java/org/onap/dmaap/JaxrsUserService.java create mode 100644 src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesListener.java create mode 100644 src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesMap.java create mode 100644 src/main/java/org/onap/dmaap/filemonitor/ServicePropertyService.java create mode 100644 src/main/java/org/onap/dmaap/mmagent/CreateMirrorMaker.java create mode 100644 src/main/java/org/onap/dmaap/mmagent/MMAgentUtil.java create mode 100644 src/main/java/org/onap/dmaap/mmagent/MirrorMaker.java create mode 100644 src/main/java/org/onap/dmaap/mmagent/UpdateMirrorMaker.java create mode 100644 src/main/java/org/onap/dmaap/mmagent/UpdateWhiteList.java create mode 100644 src/main/java/org/onap/dmaap/service/AdminRestService.java create mode 100644 src/main/java/org/onap/dmaap/service/ApiKeysRestService.java create mode 100644 src/main/java/org/onap/dmaap/service/EventsRestService.java create mode 100644 src/main/java/org/onap/dmaap/service/MMRestService.java create mode 100644 src/main/java/org/onap/dmaap/service/MetricsRestService.java create mode 100644 src/main/java/org/onap/dmaap/service/ServiceUtil.java create mode 100644 src/main/java/org/onap/dmaap/service/TopicRestService.java create mode 100644 src/main/java/org/onap/dmaap/service/TransactionRestService.java create mode 100644 src/main/java/org/onap/dmaap/service/UIRestServices.java create mode 100644 src/main/java/org/onap/dmaap/tools/ConfigTool.java create mode 100644 src/main/java/org/onap/dmaap/tools/ConfigToolContext.java create mode 100644 src/main/java/org/onap/dmaap/util/ContentLengthInterceptor.java create mode 100644 src/main/java/org/onap/dmaap/util/DMaaPAuthFilter.java create mode 100644 src/main/java/org/onap/dmaap/util/ServicePropertiesMapBean.java delete mode 100644 src/test/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapperTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/DMaaPWebExceptionMapperTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/DummyTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/HelloWorldTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/dmaap/JaxrsEchoServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/JaxrsUserServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/dmaap/filemonitor/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesListenerTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMapTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertyServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/filemonitor/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/dmaap/mmagent/CreateMirrorMakerTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/mmagent/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/dmaap/mmagent/MirrorMakerTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/mmagent/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/dmaap/mmagent/UpdateMirrorMakerTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/mmagent/UpdateWhiteListTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/AdminRestServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/ApiKeysRestServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/EventsRestServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/MMRestServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/MetricsRestServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/TopicRestServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/TransactionRestServiceTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/service/UIRestServicesTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/tools/ConfigToolContextTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/tools/ConfigToolTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/tools/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/dmaap/tools/TestRunner.java delete mode 100644 src/test/java/com/att/nsa/dmaap/util/ContentLengthInterceptorTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/util/DMaaPAuthFilterTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/util/JUnitTestSuite.java delete mode 100644 src/test/java/com/att/nsa/dmaap/util/ServicePropertiesMapBeanTest.java delete mode 100644 src/test/java/com/att/nsa/dmaap/util/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/DMaaPCambriaExceptionMapperTest.java create mode 100644 src/test/java/org/onap/dmaap/DMaaPWebExceptionMapperTest.java create mode 100644 src/test/java/org/onap/dmaap/DummyTest.java create mode 100644 src/test/java/org/onap/dmaap/HelloWorldTest.java create mode 100644 src/test/java/org/onap/dmaap/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/JaxrsEchoServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/JaxrsUserServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/filemonitor/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/filemonitor/ServicePropertiesListenerTest.java create mode 100644 src/test/java/org/onap/dmaap/filemonitor/ServicePropertiesMapTest.java create mode 100644 src/test/java/org/onap/dmaap/filemonitor/ServicePropertyServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/filemonitor/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mmagent/CreateMirrorMakerTest.java create mode 100644 src/test/java/org/onap/dmaap/mmagent/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/mmagent/MirrorMakerTest.java create mode 100644 src/test/java/org/onap/dmaap/mmagent/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/mmagent/UpdateMirrorMakerTest.java create mode 100644 src/test/java/org/onap/dmaap/mmagent/UpdateWhiteListTest.java create mode 100644 src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/service/ApiKeysRestServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/service/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/service/MMRestServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/service/MetricsRestServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/service/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/service/TopicRestServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/service/TransactionRestServiceTest.java create mode 100644 src/test/java/org/onap/dmaap/service/UIRestServicesTest.java create mode 100644 src/test/java/org/onap/dmaap/tools/ConfigToolContextTest.java create mode 100644 src/test/java/org/onap/dmaap/tools/ConfigToolTest.java create mode 100644 src/test/java/org/onap/dmaap/tools/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/tools/TestRunner.java create mode 100644 src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java create mode 100644 src/test/java/org/onap/dmaap/util/DMaaPAuthFilterTest.java create mode 100644 src/test/java/org/onap/dmaap/util/JUnitTestSuite.java create mode 100644 src/test/java/org/onap/dmaap/util/ServicePropertiesMapBeanTest.java create mode 100644 src/test/java/org/onap/dmaap/util/TestRunner.java diff --git a/ajsc-shared-config/etc/logback.xml b/ajsc-shared-config/etc/logback.xml index 4ea6385..ffedde7 100644 --- a/ajsc-shared-config/etc/logback.xml +++ b/ajsc-shared-config/etc/logback.xml @@ -109,48 +109,48 @@ - - + + - - + + - - - + + + - + - + - + - + - + - - + + - - + + - + - - + + - - + + - - + + diff --git a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/FileMonitorBeans.xml b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/FileMonitorBeans.xml index a2c393c..cf25ab5 100644 --- a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/FileMonitorBeans.xml +++ b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/FileMonitorBeans.xml @@ -5,11 +5,11 @@ - + - + - + diff --git a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/HelloWorldBeans.xml b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/HelloWorldBeans.xml index 9cb67d4..04db236 100644 --- a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/HelloWorldBeans.xml +++ b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/HelloWorldBeans.xml @@ -4,5 +4,5 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> + class="org.onap.dmaap.HelloWorld" /> diff --git a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/jaxrsBeans.groovy b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/jaxrsBeans.groovy index 430e723..b019fbc 100644 --- a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/jaxrsBeans.groovy +++ b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/jaxrsBeans.groovy @@ -3,16 +3,16 @@ xmlns jaxrs: "http://cxf.apache.org/jaxrs" xmlns util: "http://www.springframework.org/schema/util" - echoService(com.att.nsa.dmaap.JaxrsEchoService) - userService(com.att.nsa.dmaap.JaxrsUserService) - topicService(com.att.nsa.dmaap.service.TopicRestService) - eventService(com.att.nsa.dmaap.service.EventsRestService) - adminService(com.att.nsa.dmaap.service.AdminRestService) - apiKeyService(com.att.nsa.dmaap.service.ApiKeysRestService) - metricsService(com.att.nsa.dmaap.service.MetricsRestService) - transactionService(com.att.nsa.dmaap.service.TransactionRestService) - UIService(com.att.nsa.dmaap.service.UIRestServices) - mirrorService(com.att.nsa.dmaap.service.MMRestService) + echoService(org.onap.dmaap.JaxrsEchoService) + userService(org.onap.dmaap.JaxrsUserService) + topicService(org.onap.dmaap.service.TopicRestService) + eventService(org.onap.dmaap.service.EventsRestService) + adminServiceorg.onap.dmaap.service.AdminRestService) + apiKeyService(org.onap.dmaap.service.ApiKeysRestService) + metricsService(org.onap.dmaap.service.MetricsRestService) + transactionService(org.onap.dmaap.service.TransactionRestService) + UIService(org.onap.dmaap.service.UIRestServices) + mirrorService(org.onap.dmaap.service.MMRestService) util.list(id: 'jaxrsServices') { ref(bean:'echoService') diff --git a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/serviceBeans.xml b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/serviceBeans.xml index 0210d06..090a76b 100644 --- a/src/main/ajsc/dmaap_v1/dmaap/v1/conf/serviceBeans.xml +++ b/src/main/ajsc/dmaap_v1/dmaap/v1/conf/serviceBeans.xml @@ -13,7 +13,11 @@ location="classpath:msgRtrApi.properties,classpath:DMaaPErrorMesaages.properties" /> --> - + - + + class="org.onap.dmaap.util.ServicePropertiesMapBean" /> - + + value="org.onap.dmaap.dmf.mr.beans.DMaaPKafkaConsumerFactory.populateKafkaInternalDefaultsMap" /> - + - - + - + - + - @@ -115,14 +119,14 @@ factory-method="buildTransactionDb"> --> - + - + - + diff --git a/src/main/ajsc/dmaap_v1/dmaap/v1/routes/topicService.route b/src/main/ajsc/dmaap_v1/dmaap/v1/routes/topicService.route index 57a8a70..b1073d8 100644 --- a/src/main/ajsc/dmaap_v1/dmaap/v1/routes/topicService.route +++ b/src/main/ajsc/dmaap_v1/dmaap/v1/routes/topicService.route @@ -10,8 +10,8 @@ - - + + diff --git a/src/main/config/runner-web.xml b/src/main/config/runner-web.xml index 2bcf11d..d86fa5e 100644 --- a/src/main/config/runner-web.xml +++ b/src/main/config/runner-web.xml @@ -69,7 +69,7 @@ DMaaPAuthFilter DMaaPAuthFilter - com.att.nsa.dmaap.util.DMaaPAuthFilter + org.onap.dmaap.util.DMaaPAuthFilter cadi_prop_files /appl/dmaapMR1/etc/cadi.properties diff --git a/src/main/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapper.java b/src/main/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapper.java deleted file mode 100644 index 5408d62..0000000 --- a/src/main/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapper.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.dmaap; - - -import javax.inject.Singleton; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.springframework.beans.factory.annotation.Autowired; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; - -/** - * Exception Mapper class to handle - * CambriaApiException - * @author rajashree.khare - * - */ -@Provider -@Singleton -public class DMaaPCambriaExceptionMapper implements ExceptionMapper{ - -/** - * Error response obj - */ - private ErrorResponse errRes; - -/** - * Logger obj - */ - - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DMaaPCambriaExceptionMapper.class); - - - /** - * Error msg obj - */ - @Autowired - private DMaaPErrorMessages msgs; - - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest req; - - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse res; - - /** - * Contructor for DMaaPCambriaExceptionMapper - */ - public DMaaPCambriaExceptionMapper() { - super(); - LOGGER.info("Cambria Exception Mapper Created.."); - } - - /** - * The toResponse method is called when - * an exception of type CambriaApiException - * is thrown.This method will send a custom error - * response to the client. - */ - @Override - public Response toResponse(CambriaApiException ex) { - - LOGGER.info("Reached Cambria Exception Mapper.."); - - /** - * Cambria Generic Exception - */ - /*if(ex instanceof CambriaApiException) - {*/ - - errRes = ex.getErrRes(); - if(errRes!=null) { - - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - } - else - { - - Response response = Response.status(ex.getStatus()).header("exception", - ex.getMessage()).build(); - - return response; - } - - - /*} - else - { - errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(), msgs.getServerUnav()); - - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - }*/ - - } - - - -} diff --git a/src/main/java/com/att/nsa/dmaap/DMaaPWebExceptionMapper.java b/src/main/java/com/att/nsa/dmaap/DMaaPWebExceptionMapper.java deleted file mode 100644 index a59f8ca..0000000 --- a/src/main/java/com/att/nsa/dmaap/DMaaPWebExceptionMapper.java +++ /dev/null @@ -1,202 +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.dmaap; - - -import javax.inject.Singleton; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.NotAllowedException; -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.ServiceUnavailableException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.springframework.beans.factory.annotation.Autowired; - -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; - -/** - * Exception Mapper class to handle - * Web Exceptions - * @author rajashree.khare - * - */ -@Provider -@Singleton -public class DMaaPWebExceptionMapper implements ExceptionMapper{ - - /** - * Logger obj - */ - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DMaaPWebExceptionMapper.class); - /** - * Error response obj - */ - private ErrorResponse errRes; - /** - * Error msg obj - */ - @Autowired - private DMaaPErrorMessages msgs; - - /** - * Contructor for DMaaPWebExceptionMapper - */ - public DMaaPWebExceptionMapper() { - super(); - LOGGER.info("WebException Mapper Created.."); - } - - /** - * The toResponse method is called when - * an exception of type WebApplicationException - * is thrown.This method will send a custom error - * response to the client - */ - @Override - public Response toResponse(WebApplicationException ex) { - //System.out.println("--------------------------------------------------"+ex); - LOGGER.info("Reached WebException Mapper"); - - /** - * Resource Not Found - */ - if(ex instanceof NotFoundException) - { - errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND,DMaaPResponseCode.RESOURCE_NOT_FOUND. - getResponseCode(),msgs.getNotFound()); - - LOGGER.info(errRes.toString()); - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - - } - /** - * Internal Server Error - */ - if(ex instanceof InternalServerErrorException) - { - - int errCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; - int dmaapErrCode = DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(); - String errMsg = msgs.getServerUnav(); - - - if(ex.getCause().toString().contains("Json")) { - errCode = HttpStatus.SC_BAD_REQUEST; - dmaapErrCode = DMaaPResponseCode.INCORRECT_JSON.getResponseCode(); - errMsg = ex.getCause().getMessage().substring(0, ex.getCause().getMessage().indexOf("[Source")-3); - } - else if (ex.getCause().toString().contains("UnrecognizedPropertyException")) { - errCode = HttpStatus.SC_BAD_REQUEST; - dmaapErrCode = DMaaPResponseCode.INCORRECT_JSON.getResponseCode(); - errMsg = ex.getCause().getMessage().substring(0, ex.getCause().getMessage().indexOf("[Source")-3); - } - errRes = new ErrorResponse(errCode,dmaapErrCode,errMsg); - - LOGGER.info(errRes.toString()); - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - - } - /** - * UnAuthorized - */ - if(ex instanceof NotAuthorizedException) - { - errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED,DMaaPResponseCode.ACCESS_NOT_PERMITTED. - getResponseCode(),msgs.getAuthFailure()); - - LOGGER.info(errRes.toString()); - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - } - /** - * Malformed request - */ - if(ex instanceof BadRequestException) - { - errRes = new ErrorResponse(HttpStatus.SC_BAD_REQUEST,DMaaPResponseCode.INCORRECT_JSON. - getResponseCode(),msgs.getBadRequest()); - - LOGGER.info(errRes.toString()); - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - } - /** - * HTTP Method not allowed - */ - if(ex instanceof NotAllowedException) - { - errRes = new ErrorResponse(HttpStatus.SC_METHOD_NOT_ALLOWED,DMaaPResponseCode.METHOD_NOT_ALLOWED. - getResponseCode(),msgs.getMethodNotAllowed()); - - LOGGER.info(errRes.toString()); - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - } - - /** - * Server unavailable - */ - if(ex instanceof ServiceUnavailableException) - { - errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE,DMaaPResponseCode.SERVER_UNAVAILABLE. - getResponseCode(),msgs.getServerUnav()); - - LOGGER.info(errRes.toString()); - Response response = Response.status(errRes.getHttpStatusCode()).header("exception", - errRes.getErrMapperStr()).build(); - - return response; - } - - - - return Response.serverError().build(); - } - - - - -} - diff --git a/src/main/java/com/att/nsa/dmaap/HelloWorld.java b/src/main/java/com/att/nsa/dmaap/HelloWorld.java deleted file mode 100644 index a4cccba..0000000 --- a/src/main/java/com/att/nsa/dmaap/HelloWorld.java +++ /dev/null @@ -1,42 +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.dmaap; - -import org.apache.camel.Exchange; - -/** - * Hello World Sample Camel Service - * @author rajashree.khare - * - */ -public class HelloWorld { - public HelloWorld () { - } - /** - * speak method - * @param e exchange - */ - public final void speak(Exchange e) { - e.setOut(e.getIn()); - e.getOut().setBody("Hello World!"); - } -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/JaxrsEchoService.java b/src/main/java/com/att/nsa/dmaap/JaxrsEchoService.java deleted file mode 100644 index 72416da..0000000 --- a/src/main/java/com/att/nsa/dmaap/JaxrsEchoService.java +++ /dev/null @@ -1,91 +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.dmaap; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -import com.att.ajsc.beans.PropertiesMapBean; -import com.att.nsa.dmaap.filemonitor.ServicePropertiesMap; - -/** - * Example JAX-RS Service - * @author rajashree.khare - * - */ -@Path("/jaxrs-services") -public class JaxrsEchoService { - - /** - * Logger obj - */ - /*private static final Logger LOGGER = Logger - .getLogger(JaxrsEchoService.class);*/ - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(JaxrsEchoService.class); - - /** - * Method ping - * @param input input - * @return str - */ - @GET - @Path("/echo/{input}") - @Produces("text/plain") - public String ping(@PathParam("input") String input) { - return "Hello, " + input + "."; - } - - /** - * Method to fetch property - * @param fileName file - * @param input input - * @return prop - */ - @GET - @Path("/property/{fileName}/{input:.*}") - @Produces("text/plain") - public String getProperty(@PathParam("fileName") String fileName, @PathParam("input") String input) { - String val=null; - try { - val = ServicePropertiesMap.getProperty(fileName, input); - if(val == null || val.isEmpty() || val.length() < 1){ - val = PropertiesMapBean.getProperty(fileName, input); - } - } - catch(Exception ex) { - LOGGER.info("*** Error retrieving property "+input+": "+ex); - - } - if (val ==null) { - return "Property is not available"; - } - return "Property value is, " + val +"."; - } - -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/JaxrsUserService.java b/src/main/java/com/att/nsa/dmaap/JaxrsUserService.java deleted file mode 100644 index 0631a13..0000000 --- a/src/main/java/com/att/nsa/dmaap/JaxrsUserService.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.dmaap; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import java.util.Map; -import java.util.HashMap; - -/** - * Example JAX-RS User Service - * @author rajashree.khare - * - */ -@Path("/user") -public class JaxrsUserService { - - private static final Map userIdToNameMap; - static { - userIdToNameMap = new HashMap(); - userIdToNameMap.put("dw113c","Doug Wait"); - userIdToNameMap.put("so401q","Stuart O'Day"); - } - - /** - * Method to fetch user details - * @param userId user - * @return userDetails - */ - @GET - @Path("/{userId}") - @Produces("text/plain") - public String lookupUser(@PathParam("userId") String userId) { - String name = userIdToNameMap.get(userId); - return name != null ? name : "unknown id"; - } - -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesListener.java b/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesListener.java deleted file mode 100644 index edbdadf..0000000 --- a/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesListener.java +++ /dev/null @@ -1,42 +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.dmaap.filemonitor; - -import java.io.File; - -//import com.att.ssf.filemonitor.FileChangedListener; -/** - * Class ServicePropertiesListener - * @author rajashree.khare - * - */ -public class ServicePropertiesListener/* implements FileChangedListener*/ { - - /** - * Update method - */ - //@Override - /*public void update(File file) throws Exception - { - ServicePropertiesMap.refresh(file); - }*/ -} diff --git a/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMap.java b/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMap.java deleted file mode 100644 index 219a601..0000000 --- a/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMap.java +++ /dev/null @@ -1,120 +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.dmaap.filemonitor; - -import java.util.HashMap; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * ServicePropertiesMap class - * @author rajashree.khare - * - */ -@SuppressWarnings("squid:S1118") -public class ServicePropertiesMap -{ - private static HashMap> mapOfMaps = - new HashMap>(); -// static final Logger logger = LoggerFactory.getLogger(ServicePropertiesMap.class); - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ServicePropertiesMap.class); - /** - * refresh method - * @param file file - * @throws Exception ex - */ - /*public static void refresh(File file) throws Exception - { - try - { - logger.info("Loading properties - " + (file != null?file.getName():"")); - - //Store .json & .properties files into map of maps - String filePath = file.getPath(); - - if(filePath.lastIndexOf(".json")>0){ - - ObjectMapper om = new ObjectMapper(); - TypeReference> typeRef = - new TypeReference>() {}; - HashMap propMap = om.readValue(file, typeRef); - HashMap lcasePropMap = new HashMap(); - for (String key : propMap.keySet() ) - { - String lcaseKey = ifNullThenEmpty(key); - lcasePropMap.put(lcaseKey, propMap.get(key)); - } - - mapOfMaps.put(file.getName(), lcasePropMap); - - - }else if(filePath.lastIndexOf(".properties")>0){ - Properties prop = new Properties(); - FileInputStream fis = new FileInputStream(file); - prop.load(fis); - - @SuppressWarnings("unchecked") - HashMap propMap = new HashMap((Map)prop); - - mapOfMaps.put(file.getName(), propMap); - } - - logger.info("File - " + file.getName() + " is loaded into the map and the " - + "corresponding system properties have been refreshed"); - } - catch (Exception e) - { - logger.error("File " + (file != null?file.getName():"") + " cannot be loaded into the map ", e); - throw new Exception("Error reading map file " + (file != null?file.getName():""), e); - } - }*/ - /** - * Get property - * @param fileName fileName - * @param propertyKey propertyKey - * @return str - */ - public static String getProperty(String fileName, String propertyKey) - { - HashMap propMap = mapOfMaps.get(fileName); - return propMap!=null?propMap.get(ifNullThenEmpty(propertyKey)):""; - } - /** - * get properties - * @param fileName fileName - * @return mapProp - */ - public static HashMap getProperties(String fileName){ - return mapOfMaps.get(fileName); - } - - private static String ifNullThenEmpty(String key) { - if (key == null) { - return ""; - } else { - return key; - } - } - -} diff --git a/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertyService.java b/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertyService.java deleted file mode 100644 index 55c1661..0000000 --- a/src/main/java/com/att/nsa/dmaap/filemonitor/ServicePropertyService.java +++ /dev/null @@ -1,164 +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.dmaap.filemonitor; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.annotation.PostConstruct; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -//import com.att.ssf.filemonitor.FileChangedListener; -//import com.att.ssf.filemonitor.FileMonitor; - -/** - * ServicePropertyService class - * @author rajashree.khare - * - */ -public class ServicePropertyService { - private boolean loadOnStartup; - private ServicePropertiesListener fileChangedListener; - private ServicePropertiesMap filePropertiesMap; - private String ssfFileMonitorPollingInterval; - private String ssfFileMonitorThreadpoolSize; - private List fileList; - private static final String FILE_CHANGE_LISTENER_LOC = System - .getProperty("AJSC_CONF_HOME") + "/etc"; - private static final String USER_CONFIG_FILE = "service-file-monitor.properties"; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ServicePropertyService.class); - - // do not remove the postConstruct annotation, init method will not be - // called after constructor - /** - * Init method - * @throws Exception ex - */ - @PostConstruct - public void init() { - - try { - getFileList(FILE_CHANGE_LISTENER_LOC); - - /*for (File file : fileList) { - FileChangedListener fileChangedListener = this.fileChangedListener; - Object filePropertiesMap = this.filePropertiesMap; - Method m = filePropertiesMap.getClass().getMethod( - "refresh", File.class); - m.invoke(filePropertiesMap, file); - FileMonitor fm = FileMonitor.getInstance(); - fm.addFileChangedListener(file, fileChangedListener, - loadOnStartup); - - }*/ - } catch (Exception ex) { - logger.error("Error creating property map ", ex); - } - - } - - private void getFileList(String dirName) throws IOException { - File directory = new File(dirName); - FileInputStream fis = null; - - if (fileList == null) - fileList = new ArrayList(); - - // get all the files that are ".json" or ".properties", from a directory - // & it's sub-directories - File[] fList = directory.listFiles(); - - for (File file : fList) { - // read service property files from the configuration file - if (file.isFile() && file.getPath().endsWith(USER_CONFIG_FILE)) { - try { - fis = new FileInputStream(file); - Properties prop = new Properties(); - prop.load(fis); - - for (String filePath : prop.stringPropertyNames()) { - fileList.add(new File(prop.getProperty(filePath))); - } - } catch (Exception ioe) { - logger.error("Error reading the file stream ", ioe); - } finally { - fis.close(); - } - } else if (file.isDirectory()) { - getFileList(file.getPath()); - } - } - - } - - public void setLoadOnStartup(boolean loadOnStartup) { - this.loadOnStartup = loadOnStartup; - } - - public void setSsfFileMonitorPollingInterval( - String ssfFileMonitorPollingInterval) { - this.ssfFileMonitorPollingInterval = ssfFileMonitorPollingInterval; - } - - public void setSsfFileMonitorThreadpoolSize( - String ssfFileMonitorThreadpoolSize) { - this.ssfFileMonitorThreadpoolSize = ssfFileMonitorThreadpoolSize; - } - - public boolean isLoadOnStartup() { - return loadOnStartup; - } - - public String getSsfFileMonitorPollingInterval() { - return ssfFileMonitorPollingInterval; - } - - public String getSsfFileMonitorThreadpoolSize() { - return ssfFileMonitorThreadpoolSize; - } - - public ServicePropertiesListener getFileChangedListener() { - return fileChangedListener; - } - - public void setFileChangedListener( - ServicePropertiesListener fileChangedListener) { - this.fileChangedListener = fileChangedListener; - } - - public ServicePropertiesMap getFilePropertiesMap() { - return filePropertiesMap; - } - - public void setFilePropertiesMap(ServicePropertiesMap filePropertiesMap) { - this.filePropertiesMap = filePropertiesMap; - } -} diff --git a/src/main/java/com/att/nsa/dmaap/mmagent/CreateMirrorMaker.java b/src/main/java/com/att/nsa/dmaap/mmagent/CreateMirrorMaker.java deleted file mode 100644 index 35b4f03..0000000 --- a/src/main/java/com/att/nsa/dmaap/mmagent/CreateMirrorMaker.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.dmaap.mmagent; - -import java.util.Date; - -import org.apache.http.HttpStatus; -import org.json.JSONObject; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.utils.Utils; - -public class CreateMirrorMaker { - String messageID; - MirrorMaker createMirrorMaker; - - public MirrorMaker getCreateMirrorMaker() { - return createMirrorMaker; - } - - public void setCreateMirrorMaker(MirrorMaker createMirrorMaker) throws CambriaApiException { - this.createMirrorMaker = createMirrorMaker; - } - - public String getMessageID() { - return messageID; - } - - public void setMessageID(String messageID) { - this.messageID = messageID; - } - public void validateJSON() throws CambriaApiException - { - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, - DMaaPResponseCode.INCORRECT_JSON.getResponseCode(), "", null, Utils.getFormattedDate(new Date()), null, null, null, - null, - ""); - if(null==this.createMirrorMaker.getConsumer()) - { - errRes.setErrorMessage("Please provide Consumer host:port details"); - throw new CambriaApiException(errRes); - } - if(null==this.createMirrorMaker.getProducer()) - { - errRes.setErrorMessage("Please provide Producer host:port details"); - throw new CambriaApiException(errRes); - } - if(this.createMirrorMaker.getNumStreams()<=0) - { - errRes.setErrorMessage("Please provide numStreams value"); - throw new CambriaApiException(errRes); - } - - } -} diff --git a/src/main/java/com/att/nsa/dmaap/mmagent/MMAgentUtil.java b/src/main/java/com/att/nsa/dmaap/mmagent/MMAgentUtil.java deleted file mode 100644 index 8b1ec3f..0000000 --- a/src/main/java/com/att/nsa/dmaap/mmagent/MMAgentUtil.java +++ /dev/null @@ -1,430 +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.dmaap.mmagent; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Context; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpStatus; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import com.att.ajsc.filemonitor.AJSCPropertiesMap; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.constants.CambriaConstants; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; -import org.onap.dmaap.dmf.mr.service.MMService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; -import org.onap.dmaap.dmf.mr.utils.Utils; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * @author rajashree.khare - *Util class for MM Rest Service - */ -@Component -public class MMAgentUtil {/* - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - @Context - private HttpServletRequest request; - - @Context - private HttpServletResponse response; - - @Autowired - private MMService mirrorService; - - private String topic; - private int timeout; - private String consumergroup; - private String consumerid; - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMAgentUtil.class); - - public JSONObject callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream, String name, boolean listAll) throws Exception { - loadProperty(); - JSONObject jsonObj = new JSONObject(); - JSONObject finalJsonObj = new JSONObject(); - JSONArray jsonArray = null; - try { - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - mirrorService.pushEvents(ctx, topic, inStream, null, null); - long startTime = System.currentTimeMillis(); - - while (!isListMirrorMaker(msgFrmSubscribe, randomstr) - && ((System.currentTimeMillis() - startTime) < timeout)) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - - } - - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomstr)) { - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - - jsonArray = new JSONArray(msgFrmSubscribe); - jsonObj = jsonArray.getJSONObject(0); - if(jsonObj.has("listMirrorMaker")) - { - jsonArray = (JSONArray) jsonObj.get("listMirrorMaker"); - if(true==listAll) - { - return jsonObj; - } - else - { - for (int i = 0; i < jsonArray.length(); i++) - { - jsonObj = jsonArray.getJSONObject(i); - if(null!=name && !name.isEmpty()) - { - if(jsonObj.getString("name").equals(name)) - { - finalJsonObj.put("listMirrorMaker", jsonObj); - break; - } - } - else - { - finalJsonObj.put("listMirrorMaker", jsonObj); - } - - } - } - } - return finalJsonObj; - - } else { - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, - DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(), - "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null, - Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - - } catch (Exception e) { - - throw e; - } - } - - public void sendErrResponse(DMaaPContext ctx, String errMsg) { - JSONObject err = new JSONObject(); - err.append("Error", errMsg); - - try { - DMaaPResponseBuilder.respondOk(ctx, err); - LOGGER.error(errMsg.toString()); - - } catch (JSONException | IOException e) { - LOGGER.error(errMsg.toString()); - } - } - public boolean isListMirrorMaker(String msg, String messageID) { - String topicmsg = msg; - topicmsg = removeExtraChar(topicmsg); - JSONObject jObj = new JSONObject(); - JSONArray jArray = null; - boolean exist = false; - - if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) { - jArray = new JSONArray(topicmsg); - - for (int i = 0; i < jArray.length(); i++) { - jObj = jArray.getJSONObject(i); - - - if (jObj.has("messageID") && jObj.get("messageID").equals(messageID) && jObj.has("listMirrorMaker")) { - exist = true; - break; - } - } - } - return exist; - } - - public void loadProperty() { - - this.timeout = Integer.parseInt( - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim()); - this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim(); - this.consumergroup = AJSCPropertiesMap - .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim(); - this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid") - .trim(); - - - } - - public String removeExtraChar(String message) { - String str = message; - str = checkJsonFormate(str); - - if (str != null && str.length() > 0) { - str = str.replace("\\", ""); - str = str.replace("\"{", "{"); - str = str.replace("}\"", "}"); - } - return str; - } - - public String getRandomNum() { - long random = Math.round(Math.random() * 89999) + 10000; - String strLong = Long.toString(random); - return strLong; - } - - public boolean isAlphaNumeric(String name) { - String pattern = "^[a-zA-Z0-9]*$"; - if (name.matches(pattern)) { - return true; - } - return false; - } - - // This method validate IPv4 - public boolean validateIPPort(String ipPort) { - String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):" - + "([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; - if (ipPort.matches(pattern)) { - return true; - } - return false; - } - - public String checkJsonFormate(String jsonStr) { - - String json = jsonStr; - if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) { - json = json + "]"; - } - return json; - } - - public boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) { - - boolean hasPermission = false; - - DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); - - if (aaf.aafAuthentication(ctx.getRequest(), permission)) { - hasPermission = true; - } - return hasPermission; - } - - public String getNamespace(String topic) { - return topic.substring(0, topic.lastIndexOf(".")); - } - - public String removeTopic(String whitelist, String topicToRemove) { - List topicList = new ArrayList(); - List newTopicList = new ArrayList(); - - if (whitelist.contains(",")) { - topicList = Arrays.asList(whitelist.split(",")); - - } - - if (topicList.contains(topicToRemove)) { - for (String topic : topicList) { - if (!topic.equals(topicToRemove)) { - newTopicList.add(topic); - } - } - } - - String newWhitelist = StringUtils.join(newTopicList, ","); - - return newWhitelist; - } - - public void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, JSONObject jsonOb) { - - loadProperty(); - try { - String namespace = jsonOb.getString("namespace"); - String mmName = jsonOb.getString("name"); - - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - mirrorService.pushEvents(ctx, topic, inStream, null, null); - long startTime = System.currentTimeMillis(); - - while (!isListMirrorMaker(msgFrmSubscribe, randomStr) - && (System.currentTimeMillis() - startTime) < timeout) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - - JSONObject jsonObj = new JSONObject(); - JSONArray jsonArray = null; - JSONArray jsonArrayNamespace = null; - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomStr)) { - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); - - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); - - - if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) { - jsonArrayNamespace = jsonObj.getJSONArray("listMirrorMaker"); - } - } - JSONObject finalJasonObj = new JSONObject(); - JSONArray finalJsonArray = new JSONArray(); - - for (int i = 0; i < jsonArrayNamespace.length(); i++) { - - JSONObject mmObj = new JSONObject(); - mmObj = jsonArrayNamespace.getJSONObject(i); - if(mmObj.has("name")&& mmName.equals(mmObj.getString("name"))) - { - - finalJsonArray.put(mmObj); - } - - } - finalJasonObj.put("listMirrorMaker", finalJsonArray); - - DMaaPResponseBuilder.respondOk(ctx, finalJasonObj); - - } else { - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, - DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(), - "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null, - Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - - public String getWhitelistByNamespace(String originalWhitelist, String namespace) { - - String whitelist = null; - List resultList = new ArrayList(); - List whitelistList = new ArrayList(); - whitelistList = Arrays.asList(originalWhitelist.split(",")); - - for (String topic : whitelistList) { - if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) { - resultList.add(topic); - } - } - if (resultList.size() > 0) { - whitelist = StringUtils.join(resultList, ","); - } - - return whitelist; - } - - public JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) { - JSONObject jsonObj = new JSONObject(); - JSONArray jsonArray = new JSONArray(); - JSONArray listMirrorMaker = new JSONArray(); - - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); - jsonObj = jsonArray.getJSONObject(0); - - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); - - if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) { - listMirrorMaker = jsonObj.getJSONArray("listMirrorMaker"); - break; - } - } - return listMirrorMaker; - } - - public JSONObject validateMMExists(DMaaPContext ctx,String name) throws Exception - { - // Create a listAllMirrorMaker Json object - JSONObject listAll = new JSONObject(); - try { - listAll.put("listAllMirrorMaker", new JSONObject()); - - } catch (JSONException e) { - - e.printStackTrace(); - } - - // set a random number as messageID - String randomStr = getRandomNum(); - listAll.put("messageID", randomStr); - InputStream inStream = null; - - // convert listAll Json object to InputStream object - try { - inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8"); - - } catch (IOException ioe) { - ioe.printStackTrace(); - } - JSONObject listMirrorMaker =new JSONObject(); - listMirrorMaker = callPubSub(randomStr, ctx, inStream, name, false); - if (null!=listMirrorMaker && listMirrorMaker.length()>0){ - listMirrorMaker.put("exists", true); - return listMirrorMaker; - - } - listMirrorMaker.put("exists", false); - return listMirrorMaker; - - } -*/} diff --git a/src/main/java/com/att/nsa/dmaap/mmagent/MirrorMaker.java b/src/main/java/com/att/nsa/dmaap/mmagent/MirrorMaker.java deleted file mode 100644 index e3f688e..0000000 --- a/src/main/java/com/att/nsa/dmaap/mmagent/MirrorMaker.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.dmaap.mmagent; - -public class MirrorMaker { - public String name; - public String consumer; - public String producer; - public String whitelist; - public String status; - private int numStreams =1; - private boolean enablelogCheck = false; - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getConsumer() { - return consumer; - } - - public void setConsumer(String consumer) { - this.consumer = consumer; - } - - public String getProducer() { - return producer; - } - - public void setProducer(String producer) { - this.producer = producer; - } - - public String getWhitelist() { - return whitelist; - } - - public void setWhitelist(String whitelist) { - this.whitelist = whitelist; - } - - public int getNumStreams() { - return numStreams; - } - - public void setNumStreams(int numStreams) { - this.numStreams = numStreams; - } - - public boolean isEnablelogCheck() { - return enablelogCheck; - } - - public void setEnablelogCheck(boolean enablelogCheck) { - this.enablelogCheck = enablelogCheck; - } -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/mmagent/UpdateMirrorMaker.java b/src/main/java/com/att/nsa/dmaap/mmagent/UpdateMirrorMaker.java deleted file mode 100644 index 6e7a0f3..0000000 --- a/src/main/java/com/att/nsa/dmaap/mmagent/UpdateMirrorMaker.java +++ /dev/null @@ -1,83 +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.dmaap.mmagent; - -import java.util.Date; - -import org.apache.http.HttpStatus; -import org.json.JSONObject; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.utils.Utils; - -public class UpdateMirrorMaker { - String messageID; - MirrorMaker updateMirrorMaker; - - public MirrorMaker getUpdateMirrorMaker() { - return updateMirrorMaker; - } - - public void setUpdateMirrorMaker(MirrorMaker updateMirrorMaker) { - this.updateMirrorMaker = updateMirrorMaker; - } - - public String getMessageID() { - return messageID; - } - - public void setMessageID(String messageID) { - this.messageID = messageID; - } - public void validateJSON(JSONObject jsonObj) throws CambriaApiException - { - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, - DMaaPResponseCode.INCORRECT_JSON.getResponseCode(), "", null, Utils.getFormattedDate(new Date()), null, null, null, - null, - ""); - - - if(jsonObj.has("consumer")&& null==this.updateMirrorMaker.getConsumer()) - { - errRes.setErrorMessage("Please provide Consumer host:port details"); - throw new CambriaApiException(errRes); - } - if(jsonObj.has("producer")&& null==this.updateMirrorMaker.getProducer()) - { - errRes.setErrorMessage("Please provide Producer host:port details"); - throw new CambriaApiException(errRes); - } - if(jsonObj.has("numStreams")&& this.updateMirrorMaker.getNumStreams()<=0) - { - errRes.setErrorMessage("Please provide numStreams value"); - throw new CambriaApiException(errRes); - } - if(jsonObj.has("whitelist")) - { - errRes.setErrorMessage("Please use Create Whitelist API to add whitelist topics"); - throw new CambriaApiException(errRes); - } - - } -} diff --git a/src/main/java/com/att/nsa/dmaap/mmagent/UpdateWhiteList.java b/src/main/java/com/att/nsa/dmaap/mmagent/UpdateWhiteList.java deleted file mode 100644 index a1064a4..0000000 --- a/src/main/java/com/att/nsa/dmaap/mmagent/UpdateWhiteList.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.dmaap.mmagent; - -public class UpdateWhiteList { - - String messageID; - MirrorMaker updateWhiteList; - - public MirrorMaker getUpdateWhiteList() { - return updateWhiteList; - } - - public void setUpdateWhiteList(MirrorMaker updateWhiteList) { - this.updateWhiteList = updateWhiteList; - } - - public String getMessageID() { - return messageID; - } - - public void setMessageID(String messageID) { - this.messageID = messageID; - } -} diff --git a/src/main/java/com/att/nsa/dmaap/service/AdminRestService.java b/src/main/java/com/att/nsa/dmaap/service/AdminRestService.java deleted file mode 100644 index d2bf081..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/AdminRestService.java +++ /dev/null @@ -1,282 +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.dmaap.service; - -import java.io.IOException; -import java.util.Enumeration; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -import org.apache.http.HttpStatus; -//import org.apache.log4j.Logger; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.json.JSONException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.service.AdminService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; - -/** - * Rest Service class - * for Admin Services - * @author Ramkumar - * - */ -@Component -@Path("/") -public class AdminRestService { - - /** - * Logger obj - */ - //private static final Logger LOGGER = Logger - // .getLogger(AdminRestService.class); - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AdminRestService.class); - /** - * Config Reader - */ - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest request; - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse response; - /** - * AdminService obj - */ - @Autowired - private AdminService adminService; - - /** - * Fetches a list of all the registered consumers along with their created - * time and last accessed details - * - * @return consumer list in json string format - * @throws CambriaApiException - * @throws AccessDeniedException - * @throws IOException - * */ - @GET - @Path("/consumerCache") - //@Produces(MediaType.TEXT_PLAIN) - public void getConsumerCache() throws CambriaApiException, AccessDeniedException { - LOGGER.info("Fetching list of registered consumers."); - try { - adminService.showConsumerCache(ServiceUtil.getDMaaPContext(configReader, request, response)); - LOGGER.info("Fetching Consumer Cache Successfully"); - } catch (IOException e) { - LOGGER.error("Error while Fetching list of registered consumers : " - + e.getMessage(), e); - - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GET_CONSUMER_CACHE.getResponseCode(), - "Error while Fetching list of registered consumers " + e.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - /** - * Clears consumer cache - * @throws CambriaApiException ex - * @throws AccessDeniedException - * - * @throws IOException ex - * @throws JSONException ex - * */ - @POST - @Path("/dropConsumerCache") - //@Produces(MediaType.TEXT_PLAIN) - public void dropConsumerCache() throws CambriaApiException, AccessDeniedException { - LOGGER.info("Dropping consumer cache"); - try { - adminService.dropConsumerCache(ServiceUtil.getDMaaPContext(configReader, request, response)); - LOGGER.info("Dropping Consumer Cache successfully"); - } catch ( AccessDeniedException excp) { - LOGGER.error("Error while dropConsumerCache : " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), - "Error while Fetching list of blacklist ips " + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } catch (JSONException | IOException e) { - LOGGER.error( - "Error while Dropping consumer cache : " + e.getMessage(), - e); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.DROP_CONSUMER_CACHE.getResponseCode(), - "Error while Dropping consumer cache " + e.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - /** - * Get list of blacklisted ips - * @throws CambriaApiException excp - */ - @GET - @Path("/blacklist") - //@Produces(MediaType.TEXT_PLAIN) - public void getBlacklist() throws CambriaApiException { - LOGGER.info("Fetching list of blacklist ips."); - try { - Enumeration headerNames =ServiceUtil.getDMaaPContext(configReader, request, response).getRequest().getHeaderNames(); - while (headerNames.hasMoreElements()) { - String key = (String) headerNames.nextElement(); - String value = request.getHeader(key); - - } - - adminService.getBlacklist(ServiceUtil.getDMaaPContext(configReader, request, response)); - LOGGER.info("Fetching list of blacklist ips Successfully"); - }catch ( AccessDeniedException excp) { - LOGGER.error("Error while Fetching list of blacklist ips : " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), - "Error while Fetching list of blacklist ips " + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } catch ( IOException excp) { - LOGGER.error("Error while Fetching list of blacklist ips : " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), - "Error while Fetching list of blacklist ips " + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - - } - - /** - * Add ip to list of blacklist ips - * @param ip ip - * @throws CambriaApiException excp - */ - @POST - @Path("/blacklist/{ip}") - //@Produces(MediaType.TEXT_PLAIN) - public void addToBlacklist (@PathParam("ip") String ip ) throws CambriaApiException - { - LOGGER.info("Adding ip to list of blacklist ips."); - try { - adminService.addToBlacklist(ServiceUtil.getDMaaPContext(configReader, request, response), ip); - LOGGER.info("Fetching list of blacklist ips Successfully"); - } catch ( AccessDeniedException excp) { - LOGGER.error("Error while blacklist : " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), - "Error while Fetching list of blacklist ips " + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } catch (IOException | ConfigDbException excp) { - LOGGER.error("Error while adding ip to list of blacklist ips : " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.ADD_BLACKLIST.getResponseCode(), - "Error while adding ip to list of blacklist ips " + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - - } - /** - * Remove ip from blacklist - * @param ip ip - * @throws CambriaApiException excp - * @throws AccessDeniedException excp - * @throws ConfigDbException excp - */ - @DELETE - @Path("/blacklist/{ip}") - //@Produces(MediaType.TEXT_PLAIN) - public void removeFromBlacklist(@PathParam("ip") String ip) throws CambriaApiException, AccessDeniedException, ConfigDbException { - LOGGER.info("Fetching list of blacklist ips."); - try { - adminService.removeFromBlacklist(ServiceUtil.getDMaaPContext(configReader, request, response), ip); - LOGGER.info("Fetching list of blacklist ips Successfully"); - }catch ( AccessDeniedException excp) { - LOGGER.error("Error while blacklist : " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), - "Error while removeFromBlacklist list of blacklist ips " + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } catch (IOException | ConfigDbException excp) { - LOGGER.error("Error while removing ip from list of blacklist ips : " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.REMOVE_BLACKLIST.getResponseCode(), - "Error while removing ip from list of blacklist ips " + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - -} diff --git a/src/main/java/com/att/nsa/dmaap/service/ApiKeysRestService.java b/src/main/java/com/att/nsa/dmaap/service/ApiKeysRestService.java deleted file mode 100644 index d44d259..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/ApiKeysRestService.java +++ /dev/null @@ -1,254 +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.dmaap.service; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.json.JSONException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.ApiKeyBean; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.service.ApiKeysService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.db.NsaApiDb.KeyExistsException; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; - -/** - * This class is a CXF REST service - * which acts as gateway for Cambria Api - * Keys. - * @author rajashree.khare - * - */ -@Component -@Path("/") -public class ApiKeysRestService { - - /** - * Logger obj - */ - //private Logger log = Logger.getLogger(ApiKeysRestService.class.toString()); - private static final EELFLogger log = EELFManager.getInstance().getLogger(ApiKeysRestService.class); - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest request; - - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse response; - - /** - * Config Reader - */ - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - /** - * ApiKeysService obj - */ - @Autowired - private ApiKeysService apiKeyService; - - /** - * Returns a list of all the existing Api keys - * @throws CambriaApiException - * - * @throws IOException - * */ - @GET - public void getAllApiKeys() throws CambriaApiException { - - log.info("Inside ApiKeysRestService.getAllApiKeys"); - - try { - apiKeyService.getAllApiKeys(getDmaapContext()); - log.info("Fetching all API keys is Successful"); - } catch (ConfigDbException | IOException e) { - log.error("Error while retrieving API keys: " + e); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), - "Error while retrieving API keys: "+ e.getMessage()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - - } - - /** - * Returns details of a particular api key whose name is passed - * as a parameter - * - * @param apiKeyName - * - name of the api key - * @throws CambriaApiException - * @throws IOException - * */ - @GET - @Path("/{apiKey}") - public void getApiKey(@PathParam("apiKey") String apiKeyName) throws CambriaApiException { - log.info("Fetching details of api key: " + apiKeyName); - - try { - apiKeyService.getApiKey(getDmaapContext(), apiKeyName); - log.info("Fetching specific API key is Successful"); - } catch (ConfigDbException | IOException e) { - log.error("Error while retrieving API key details: " + e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), - "Error while retrieving API key details: "+ e.getMessage()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - - - /** - * Creates api key using the email and description - * - * @param nsaApiKey - * @throws CambriaApiException - * @throws JSONException - * */ - @POST - @Path("/create") - @Consumes(MediaType.APPLICATION_JSON) - public void createApiKey(ApiKeyBean nsaApiKey) throws CambriaApiException, JSONException { - log.info("Creating Api Key."); - - try { - apiKeyService.createApiKey(getDmaapContext(), nsaApiKey); - log.info("Creating API key is Successful"); - } catch (KeyExistsException | ConfigDbException | IOException e) { - log.error("Error while Creating API key : " + e.getMessage(), e); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), - "Error while Creating API key : "+ e.getMessage()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - - } - - /** - * Updates an existing apiKey using the key name passed a parameter and the - * details passed. - * - * @param apiKeyName - * - name of the api key to be updated - * @param nsaApiKey - * @throws CambriaApiException - * @throws JSONException - * @throws IOException - * @throws AccessDeniedException - * */ - @PUT - @Path("/{apiKey}") - public void updateApiKey(@PathParam("apiKey") String apiKeyName, - ApiKeyBean nsaApiKey) throws CambriaApiException, JSONException { - log.info("Updating Api Key."); - - try { - - apiKeyService - .updateApiKey(getDmaapContext(), apiKeyName, nsaApiKey); - log.error("API key updated sucessfully"); - } catch (ConfigDbException | IOException | AccessDeniedException e) { - log.error("Error while Updating API key : " + apiKeyName, e); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), - "Error while Updating API key : "+ e.getMessage()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * Deletes an existing apiKey using the key name passed as a parameter. - * - * @param apiKeyName - * - name of the api key to be updated - * @throws CambriaApiException - * @throws IOException - * @throws AccessDeniedException - * */ - @DELETE - @Path("/{apiKey}") - public void deleteApiKey(@PathParam("apiKey") String apiKeyName) throws CambriaApiException { - log.info("Deleting Api Key: " + apiKeyName); - try { - apiKeyService.deleteApiKey(getDmaapContext(), apiKeyName); - log.info("Api Key deleted successfully: " + apiKeyName); - } catch (ConfigDbException | IOException | AccessDeniedException e) { - log.error("Error while deleting API key : " + apiKeyName, e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), - "Error while deleting API key : "+ e.getMessage()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * Create a dmaap context - * @return DMaaPContext - */ - private DMaaPContext getDmaapContext() { - DMaaPContext dmaapContext = new DMaaPContext(); - dmaapContext.setConfigReader(configReader); - dmaapContext.setRequest(request); - dmaapContext.setResponse(response); - return dmaapContext; - } - -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/service/EventsRestService.java b/src/main/java/com/att/nsa/dmaap/service/EventsRestService.java deleted file mode 100644 index cd28967..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/EventsRestService.java +++ /dev/null @@ -1,378 +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.dmaap.service; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; - -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; -import org.onap.dmaap.dmf.mr.service.EventsService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.onap.dmaap.dmf.mr.utils.Utils; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; -import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; -/** - * This class is a CXF REST service which acts - * as gateway for MR Event Service. - * @author rajashree.khare - * - */ -@Component -@Path("/") -public class EventsRestService { - - /** - * Logger obj - */ - //private Logger log = Logger.getLogger(EventsRestService.class.toString()); - private static final EELFLogger log = EELFManager.getInstance().getLogger(EventsRestService.class); - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest request; - - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse response; - - - /** - * Config Reader - */ - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - @Autowired - private EventsService eventsService; - - @Autowired - private DMaaPErrorMessages errorMessages; - - /** - * This method is used to consume messages.Taking three parameter - * topic,consumerGroup and consumerId .Consumer decide to which topic they - * want to consume messages.In on consumer Group there might be many - * consumer may be present. - * - * @param topic - * specify- the topic name - * @param consumergroup - * - specify the consumer group - * @param consumerid - * -specify the consumer id - * - * handles CambriaApiException | ConfigDbException | - * TopicExistsException | AccessDeniedException | - * UnavailableException | IOException in try catch block - * @throws CambriaApiException - * - */ - @GET - @Path("/{topic}/{consumergroup}/{consumerid}") - public void getEvents(@PathParam("topic") String topic, @PathParam("consumergroup") - String consumergroup, - @PathParam("consumerid") String consumerid) throws CambriaApiException { - // log.info("Consuming message from topic " + topic ); - DMaaPContext dMaaPContext = getDmaapContext(); - dMaaPContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); - - try { - - eventsService.getEvents(dMaaPContext, topic, consumergroup, consumerid); - } - catch (TopicExistsException e) { - log.error("Error while reading data from topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, - DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), errorMessages.getConsumeMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, null, null, - consumerid, - request.getRemoteHost()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - catch (DMaaPAccessDeniedException | AccessDeniedException e) { - log.error("Error while reading data from topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), errorMessages.getConsumeMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, null, null, - consumerid, - request.getRemoteHost()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - - catch (ConfigDbException | UnavailableException | IOException e) { - log.error("Error while reading data from topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), errorMessages.getConsumeMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, null, null, - consumerid, - request.getRemoteHost()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - - /** - * This method is used to throw an exception back to the client app if CG/CID is not passed - * while consuming messages - */ - @GET - @Path("/{topic}") - public void getEventsToException(@PathParam("topic") String topic) throws CambriaApiException { - // log.info("Consuming message from topic " + topic ); - DMaaPContext dMaaPContext = getDmaapContext(); - dMaaPContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); - - try { - - throw new TopicExistsException("Incorrect URL"); - } - catch (TopicExistsException e) { - log.error("Error while reading data from topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), "Incorrect url - Expects consumer Group and ID in " + request.getRequestURI() + " from "+request.getRemoteHost() - ); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - - } - - /** - * This method is used to throw an exception back to the client app if CG/CID is not passed - * while consuming messages - */ - @GET - @Path("/{topic}/{consumergroup}") - public void getEventsToException(@PathParam("topic") String topic, @PathParam("consumergroup") - String consumergroup - ) throws CambriaApiException { - // log.info("Consuming message from topic " + topic ); - DMaaPContext dMaaPContext = getDmaapContext(); - dMaaPContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); - - try { - - throw new TopicExistsException("Incorrect URL"); - } - catch (TopicExistsException e) { - log.error("Error while reading data from topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), "Incorrect url - Expects consumer ID in " + request.getRequestURI() + " from "+request.getRemoteHost() - ); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - - } - - - - - - - - /** - * This method is used to publish messages.Taking two parameter topic and - * partition.Publisher decide to which topic they want to publish message - * and kafka decide to which partition of topic message will send, - * - * @param topic - * @param msg - * @param partitionKey - * - * handles CambriaApiException | ConfigDbException | - * TopicExistsException | AccessDeniedException | IOException in - * try catch block - * @throws CambriaApiException - */ - - @POST - @Produces("application/json") - @Path("/{topic}") - public void pushEvents(@PathParam("topic") String topic, InputStream msg, - @QueryParam("partitionKey") String partitionKey) throws CambriaApiException { - log.info("Publishing message to topic " + topic); - - try { - eventsService.pushEvents(getDmaapContext(), topic, msg, partitionKey, null); - } - catch ( TopicExistsException e) { - log.error("Error while publishing to topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, - DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, - Utils.getUserApiKey(request), request.getRemoteHost(), null, null); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - catch ( DMaaPAccessDeniedException | AccessDeniedException e) { - log.error("Error while publishing to topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, - Utils.getUserApiKey(request), request.getRemoteHost(), null, null); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - - - catch (ConfigDbException | IOException | missingReqdSetting e) { - log.error("Error while publishing to topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, - Utils.getUserApiKey(request), request.getRemoteHost(), null, null); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - /** - * This method is used to publish messages by passing an optional header - * called 'transactionId'. If the 'transactionId' is not provided in the - * input then a new transaction object will be created. Else the existing - * transaction object will be updated with the counter details. - * - * @param topic - * @param partitionKey - * - * handles CambriaApiException | ConfigDbException | - * TopicExistsException | AccessDeniedException | IOException in - * try catch block - * @throws CambriaApiException - */ - @POST - @Produces("application/json") - @Path("/transaction/{topic}") - public void pushEventsWithTransaction(@PathParam("topic") String topic, - @QueryParam("partitionKey") String partitionKey) throws CambriaApiException { - // log.info("Publishing message with transaction id for topic " + topic - // ); - - try { - eventsService.pushEvents(getDmaapContext(), topic, request.getInputStream(), - partitionKey, - Utils.getFormattedDate(new Date())); - } - - catch ( TopicExistsException e) { - log.error("Error while publishing to topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, - DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, - Utils.getUserApiKey(request), request.getRemoteHost(), null, null); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - catch ( DMaaPAccessDeniedException| AccessDeniedException e) { - log.error("Error while publishing to topic [" + topic + "].", e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() - + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, - Utils.getUserApiKey(request), request.getRemoteHost(), null, null); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - - catch (ConfigDbException | IOException | missingReqdSetting e) { - log.error("Error while publishing to topic : " + topic, e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), "Transaction-" - + errorMessages.getPublishMsgError() + e.getMessage(), null, - Utils.getFormattedDate(new Date()), topic, Utils.getUserApiKey(request), - request.getRemoteHost(), - null, null); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * This method is used for taking Configuration Object,HttpServletRequest - * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession - * Object. - * - * @return DMaaPContext object from where user can get Configuration - * Object,HttpServlet Object - * - */ - private DMaaPContext getDmaapContext() { - - DMaaPContext dmaapContext = new DMaaPContext(); - dmaapContext.setRequest(request); - dmaapContext.setResponse(response); - dmaapContext.setConfigReader(configReader); - - return dmaapContext; - } - -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/service/MMRestService.java b/src/main/java/com/att/nsa/dmaap/service/MMRestService.java deleted file mode 100644 index 853c9ba..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/MMRestService.java +++ /dev/null @@ -1,1259 +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.dmaap.service; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import org.json.JSONObject; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; -import org.onap.dmaap.dmf.mr.utils.Utils; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.dmaap.mmagent.*; -import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; - -import edu.emory.mathcs.backport.java.util.Arrays; - -import com.att.ajsc.filemonitor.AJSCPropertiesMap; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException; - -import org.json.JSONArray; -import org.json.JSONException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.constants.CambriaConstants; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; -import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticatorImpl; -import org.onap.dmaap.dmf.mr.service.MMService; - -/** - * Rest Service class for Mirror Maker proxy Rest Services - * - * @author - * - * @since May 25, 2016 - */ - -@Component -public class MMRestService { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMRestService.class); - private static final String NO_ADMIN_PERMISSION = "No Mirror Maker Admin permission."; - private static final String NO_USER_PERMISSION = "No Mirror Maker User permission."; - private static final String NO_USER_CREATE_PERMISSION = "No Mirror Maker User Create permission."; - private static final String NAME_DOES_NOT_MEET_REQUIREMENT = "Mirror Maker name can only contain alpha numeric"; - private static final String INVALID_IPPORT = "This is not a valid IP:Port"; - private static final String MIRROR_MAKERADMIN = "msgRtr.mirrormakeradmin.aaf"; - private static final String MIRROR_MAKERUSER = "msgRtr.mirrormakeruser.aaf"; - private static final String UTF_8 = "UTF-8"; - private static final String MESSAGE = "message"; - private static final String LISTMIRRORMAKER = "listMirrorMaker"; - private static final String ERROR = "error"; - private static final String NAMESPACE = "namespace"; - - private String topic; - private int timeout; - private String consumergroup; - private String consumerid; - - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - @Context - private HttpServletRequest request; - - @Context - private HttpServletResponse response; - - @Autowired - private MMService mirrorService; - - @Autowired - private DMaaPErrorMessages errorMessages; - - private DMaaPAAFAuthenticator dmaapAAFauthenticator = new DMaaPAAFAuthenticatorImpl(); - - /** - * This method is used for taking Configuration Object,HttpServletRequest - * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession - * Object. - * - * @return DMaaPContext object from where user can get Configuration - * Object,HttpServlet Object - * - */ - private DMaaPContext getDmaapContext() { - DMaaPContext dmaapContext = new DMaaPContext(); - dmaapContext.setRequest(request); - dmaapContext.setResponse(response); - dmaapContext.setConfigReader(configReader); - dmaapContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); - - return dmaapContext; - } - - @POST - @Produces("application/json") - @Path("/create") - public void callCreateMirrorMaker(InputStream msg) { - - DMaaPContext ctx = getDmaapContext(); - if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { - - loadProperty(); - String input = null; - String randomStr = getRandomNum(); - - InputStream inStream = null; - Gson gson = new Gson(); - CreateMirrorMaker createMirrorMaker = new CreateMirrorMaker(); - - try { - input = IOUtils.toString(msg, UTF_8); - - if (input != null && input.length() > 0) { - input = removeExtraChar(input); - } - - // Check if the request has CreateMirrorMaker - try { - createMirrorMaker = gson.fromJson(input, CreateMirrorMaker.class); - - } catch (JsonSyntaxException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JsonSyntaxException: ", ex); - } - String name = createMirrorMaker.getCreateMirrorMaker()==null? "":createMirrorMaker.getCreateMirrorMaker().getName(); - // send error message if it is not a CreateMirrorMaker request. - if (createMirrorMaker.getCreateMirrorMaker() == null) { - sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again."); - } - - // MirrorMaker whitelist and status should not be passed - else if (createMirrorMaker.getCreateMirrorMaker().getWhitelist() != null - || createMirrorMaker.getCreateMirrorMaker().getStatus() != null) { - sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again."); - } - - // if empty, blank name is entered - else if (StringUtils.isBlank(name)) { - sendErrResponse(ctx, "Name can not be empty or blank."); - } - - // Check if the name contains only Alpha Numeric - else if (!isAlphaNumeric(name)) { - sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT); - - } - - // Validate the IP and Port - else if (!StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getConsumer()) - && !StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getProducer()) - && !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer()) - || !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) { - sendErrResponse(ctx, INVALID_IPPORT); - - } - // Set a random number as messageID, convert Json Object to - // InputStream and finally call publisher and subscriber - else if (isAlphaNumeric(name) && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer()) - && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) { - - createMirrorMaker.setMessageID(randomStr); - inStream = IOUtils.toInputStream(gson.toJson(createMirrorMaker), UTF_8); - callPubSub(randomStr, ctx, inStream); - } - - } catch (IOException e) { - - LOGGER.error("IOException: ", e); - } - } - // Send error response if user does not provide Authorization - else { - sendErrResponse(ctx, NO_ADMIN_PERMISSION); - } - } - - @POST - @Produces("application/json") - @Path("/listall") - public void callListAllMirrorMaker(InputStream msg) { - DMaaPContext ctx = getDmaapContext(); - - if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { - - loadProperty(); - - String input = null; - - try { - input = IOUtils.toString(msg, UTF_8); - - if (input != null && input.length() > 0) { - input = removeExtraChar(input); - } - - String randomStr = getRandomNum(); - JSONObject jsonOb = null; - - try { - jsonOb = new JSONObject(input); - - } catch (JSONException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); - } - - // Check if request has listAllMirrorMaker and - // listAllMirrorMaker is empty - if ((jsonOb != null) && (jsonOb.has("listAllMirrorMaker") - && jsonOb.getJSONObject("listAllMirrorMaker").length() == 0)) { - jsonOb.put("messageID", randomStr); - InputStream inStream = null; - - try { - inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8); - - } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); - } - - callPubSub(randomStr, ctx, inStream); - - } else { - - sendErrResponse(ctx, "This is not a ListAllMirrorMaker request. Please try again."); - } - - } catch (IOException ioe) { - - LOGGER.error("IOException: ", ioe); - } - - } else { - - sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION); - } - } - - @POST - @Produces("application/json") - @Path("/update") - public void callUpdateMirrorMaker(InputStream msg) { - - DMaaPContext ctx = getDmaapContext(); - if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { - - loadProperty(); - String input = null; - String randomStr = getRandomNum(); - - InputStream inStream = null; - Gson gson = new Gson(); - UpdateMirrorMaker updateMirrorMaker = new UpdateMirrorMaker(); - - try { - input = IOUtils.toString(msg, UTF_8); - - if (input != null && input.length() > 0) { - input = removeExtraChar(input); - } - - // Check if the request has UpdateMirrorMaker - try { - updateMirrorMaker = gson.fromJson(input, UpdateMirrorMaker.class); - - } catch (JsonSyntaxException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JsonSyntaxException: ", ex); - - } - String name = updateMirrorMaker.getUpdateMirrorMaker()==null? "":updateMirrorMaker.getUpdateMirrorMaker().getName(); - // send error message if it is not a UpdateMirrorMaker request. - if (updateMirrorMaker.getUpdateMirrorMaker() == null) { - sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again."); - } - - // MirrorMaker whitelist and status should not be passed - else if (updateMirrorMaker.getUpdateMirrorMaker().getWhitelist() != null - || updateMirrorMaker.getUpdateMirrorMaker().getStatus() != null) { - sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again."); - } - - // if empty, blank name is entered - else if (StringUtils.isBlank(name)) { - sendErrResponse(ctx, "Name can not be empty or blank."); - } - - // Check if the name contains only Alpha Numeric - else if (!isAlphaNumeric(name)) { - sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT); - - } - - // Validate the IP and Port - else if (!StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) - && !StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getProducer()) - && !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) - || !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) { - sendErrResponse(ctx, INVALID_IPPORT); - - } - // Set a random number as messageID, convert Json Object to - // InputStream and finally call publisher and subscriber - else if (isAlphaNumeric(name) && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) - && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) { - - updateMirrorMaker.setMessageID(randomStr); - inStream = IOUtils.toInputStream(gson.toJson(updateMirrorMaker), UTF_8); - callPubSub(randomStr, ctx, inStream); - } - - } catch (IOException e) { - - LOGGER.error("IOException: ", e); - } - } - // Send error response if user does not provide Authorization - else { - sendErrResponse(ctx, NO_ADMIN_PERMISSION); - } - } - - @POST - @Produces("application/json") - @Path("/delete") - public void callDeleteMirrorMaker(InputStream msg) { - DMaaPContext ctx = getDmaapContext(); - - if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { - - loadProperty(); - - String input = null; - - try { - input = IOUtils.toString(msg, UTF_8); - - if (input != null && input.length() > 0) { - input = removeExtraChar(input); - } - - String randomStr = getRandomNum(); - JSONObject jsonOb = null; - - try { - jsonOb = new JSONObject(input); - - } catch (JSONException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); - } - - // Check if request has DeleteMirrorMaker and - // DeleteMirrorMaker has MirrorMaker object with name variable - // and check if the name contain only alpha numeric - if ((jsonOb != null) - && (jsonOb.has("deleteMirrorMaker") && jsonOb.getJSONObject("deleteMirrorMaker").length() == 1 - && jsonOb.getJSONObject("deleteMirrorMaker").has("name") - && !StringUtils.isBlank(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")) - && isAlphaNumeric(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")))) { - - jsonOb.put("messageID", randomStr); - InputStream inStream = null; - - try { - inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8); - - } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); - } - - callPubSub(randomStr, ctx, inStream); - - } else { - - sendErrResponse(ctx, "This is not a DeleteMirrorMaker request. Please try again."); - } - - } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); - } - - } else { - - sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION); - } - } - - private boolean isListMirrorMaker(String msg, String messageID) { - String topicmsg = msg; - topicmsg = removeExtraChar(topicmsg); - - JSONObject jObj; - JSONArray jArray; - boolean exist = false; - - if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) { - jArray = new JSONArray(topicmsg); - - for (int i = 0; i < jArray.length(); i++) { - jObj = jArray.getJSONObject(i); - - JSONObject obj = new JSONObject(); - if (jObj.has(MESSAGE)) { - obj = jObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(messageID) && obj.has(LISTMIRRORMAKER)) { - exist = true; - break; - } - } - } - return exist; - } - - private void loadProperty() { - - this.timeout = Integer.parseInt( - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim()); - this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim(); - this.consumergroup = AJSCPropertiesMap - .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim(); - this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid") - .trim(); - } - - private String removeExtraChar(String message) { - String str = message; - str = checkJsonFormate(str); - - if (str != null && str.length() > 0) { - str = str.replace("\\", ""); - str = str.replace("\"{", "{"); - str = str.replace("}\"", "}"); - } - return str; - } - - private String getRandomNum() { - long random = Math.round(Math.random() * 89999) + 10000; - String strLong = Long.toString(random); - return strLong; - } - - private boolean isAlphaNumeric(String name) { - String pattern = "^[a-zA-Z0-9]*$"; - if (name.matches(pattern)) { - return true; - } - return false; - } - - // This method validate IPv4 - private boolean validateIPPort(String ipPort) { - String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):" - + "([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; - if (ipPort.matches(pattern)) { - return true; - } - return false; - } - - private String checkJsonFormate(String jsonStr) { - - String json = jsonStr; - if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) { - json = json + "]"; - } - return json; - } - - private boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) { - - boolean hasPermission = false; - - if (dmaapAAFauthenticator.aafAuthentication(ctx.getRequest(), permission)) { - hasPermission = true; - } - return hasPermission; - } - - private void callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream) { - try { - mirrorService.pushEvents(ctx, topic, inStream, null, null); - long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - - while (!isListMirrorMaker(msgFrmSubscribe, randomstr) - && (System.currentTimeMillis() - startTime) < timeout) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - - JSONObject jsonObj; - JSONObject finalJsonObj = new JSONObject(); - JSONArray jsonArray; - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomstr)) { - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); - - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); - - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomstr) && obj.has(LISTMIRRORMAKER)) { - finalJsonObj.put(LISTMIRRORMAKER, obj.get(LISTMIRRORMAKER)); - break; - } - } - - DMaaPResponseBuilder.respondOk(ctx, finalJsonObj); - - } else { - - JSONObject err = new JSONObject(); - err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); - } - - } catch (Exception e) { - LOGGER.error("Exception: ", e); - } - } - - private void sendErrResponse(DMaaPContext ctx, String errMsg) { - JSONObject err = new JSONObject(); - err.append(ERROR, errMsg); - - try { - DMaaPResponseBuilder.respondOk(ctx, err); - LOGGER.error(errMsg); - - } catch (JSONException | IOException e) { - LOGGER.error("Error at sendErrResponse method:" + errMsg + "Exception name:" + e); - } - } - - @SuppressWarnings("unchecked") - @POST - @Produces("application/json") - @Path("/listallwhitelist") - public void listWhiteList(InputStream msg) { - - DMaaPContext ctx = getDmaapContext(); - if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { - - loadProperty(); - String input = null; - - try { - input = IOUtils.toString(msg, UTF_8); - - if (input != null && input.length() > 0) { - input = removeExtraChar(input); - } - - // Check if it is correct Json object - JSONObject jsonOb = null; - - try { - jsonOb = new JSONObject(input); - - } catch (JSONException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); - } - - // Check if the request has name and name contains only alpha - // numeric - // and check if the request has namespace and namespace contains - // only alpha numeric - if (jsonOb != null && jsonOb.length() == 2 && jsonOb.has("name") - && !StringUtils.isBlank(jsonOb.getString("name")) && isAlphaNumeric(jsonOb.getString("name")) - && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE))) { - - String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, - "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; - - // Check if the user have create permission for the - // namespace - if (checkMirrorMakerPermission(ctx, permission)) { - - JSONObject listAll = new JSONObject(); - JSONObject emptyObject = new JSONObject(); - - // Create a listAllMirrorMaker Json object - try { - listAll.put("listAllMirrorMaker", emptyObject); - - } catch (JSONException e) { - - LOGGER.error("JSONException: ", e); - } - - // set a random number as messageID - String randomStr = getRandomNum(); - listAll.put("messageID", randomStr); - InputStream inStream = null; - - // convert listAll Json object to InputStream object - try { - inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); - - } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); - } - // call listAllMirrorMaker - mirrorService.pushEvents(ctx, topic, inStream, null, null); - - // subscribe for listMirrorMaker - long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - - while (!isListMirrorMaker(msgFrmSubscribe, randomStr) - && (System.currentTimeMillis() - startTime) < timeout) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomStr)) { - - JSONArray listMirrorMaker; - listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr); - - String whitelist = null; - for (int i = 0; i < listMirrorMaker.length(); i++) { - - JSONObject mm; - mm = listMirrorMaker.getJSONObject(i); - String name = mm.getString("name"); - - if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { - whitelist = mm.getString("whitelist"); - break; - } - } - - if (!StringUtils.isBlank(whitelist)) { - - List topicList = new ArrayList<>(); - List finalTopicList = new ArrayList<>(); - topicList = Arrays.asList(whitelist.split(",")); - - for (String topic : topicList) { - if (topic != null && !topic.equals("null") - && getNamespace(topic).equals(jsonOb.getString(NAMESPACE))) { - - finalTopicList.add(topic); - } - } - - String topicNames = ""; - - if (!finalTopicList.isEmpty()) { - topicNames = StringUtils.join(finalTopicList, ","); - } - - JSONObject listAllWhiteList = new JSONObject(); - listAllWhiteList.put("name", jsonOb.getString("name")); - listAllWhiteList.put("whitelist", topicNames); - - DMaaPResponseBuilder.respondOk(ctx, listAllWhiteList); - } - - } else { - - JSONObject err = new JSONObject(); - err.append(ERROR, - "listWhiteList is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); - } - - } else { - sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); - } - - } else { - - sendErrResponse(ctx, "This is not a ListAllWhitelist request. Please try again."); - } - - } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException - | TopicExistsException | missingReqdSetting | UnavailableException e) { - - LOGGER.error("IOException: ", e); - } - } else { - sendErrResponse(ctx, NO_USER_PERMISSION); - } - } - - @SuppressWarnings("unchecked") - @POST - @Produces("application/json") - @Path("/createwhitelist") - public void createWhiteList(InputStream msg) { - - DMaaPContext ctx = getDmaapContext(); - if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { - - loadProperty(); - String input = null; - - try { - input = IOUtils.toString(msg, UTF_8); - - if (input != null && input.length() > 0) { - input = removeExtraChar(input); - } - - // Check if it is correct Json object - JSONObject jsonOb = null; - - try { - jsonOb = new JSONObject(input); - - } catch (JSONException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); - } - - // Check if the request has name and name contains only alpha - // numeric, - // check if the request has namespace and - // check if the request has whitelistTopicName - // check if the topic name contains only alpha numeric - if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") - && !StringUtils.isBlank(jsonOb.getString("name")) && isAlphaNumeric(jsonOb.getString("name")) - && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE)) - && jsonOb.has("whitelistTopicName") - && !StringUtils.isBlank(jsonOb.getString("whitelistTopicName")) - && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring( - jsonOb.getString("whitelistTopicName").lastIndexOf(".") + 1, - jsonOb.getString("whitelistTopicName").length()))) { - - String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, - "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; - - // Check if the user have create permission for the - // namespace - if (checkMirrorMakerPermission(ctx, permission)) { - - JSONObject listAll = new JSONObject(); - JSONObject emptyObject = new JSONObject(); - - // Create a listAllMirrorMaker Json object - try { - listAll.put("listAllMirrorMaker", emptyObject); - - } catch (JSONException e) { - - LOGGER.error("JSONException: ", e); - } - - // set a random number as messageID - String randomStr = getRandomNum(); - listAll.put("messageID", randomStr); - InputStream inStream = null; - - // convert listAll Json object to InputStream object - try { - inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); - - } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); - } - // call listAllMirrorMaker - mirrorService.pushEvents(ctx, topic, inStream, null, null); - - // subscribe for listMirrorMaker - long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - - while (!isListMirrorMaker(msgFrmSubscribe, randomStr) - && (System.currentTimeMillis() - startTime) < timeout) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - - JSONArray listMirrorMaker; - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomStr)) { - - listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr); - String whitelist = null; - - for (int i = 0; i < listMirrorMaker.length(); i++) { - JSONObject mm; - mm = listMirrorMaker.getJSONObject(i); - String name = mm.getString("name"); - - if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { - whitelist = mm.getString("whitelist"); - break; - } - } - - List topicList = new ArrayList<>(); - List finalTopicList = new ArrayList<>(); - - if (whitelist != null) { - topicList = Arrays.asList(whitelist.split(",")); - } - - for (String st : topicList) { - if (!StringUtils.isBlank(st)) { - finalTopicList.add(st); - } - } - - String newTopic = jsonOb.getString("whitelistTopicName"); - - if (!topicList.contains(newTopic) - && getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) { - - UpdateWhiteList updateWhiteList = new UpdateWhiteList(); - MirrorMaker mirrorMaker = new MirrorMaker(); - mirrorMaker.setName(jsonOb.getString("name")); - finalTopicList.add(newTopic); - String newWhitelist = ""; - - if (!finalTopicList.isEmpty()) { - newWhitelist = StringUtils.join(finalTopicList, ","); - } - - mirrorMaker.setWhitelist(newWhitelist); - - String newRandom = getRandomNum(); - updateWhiteList.setMessageID(newRandom); - updateWhiteList.setUpdateWhiteList(mirrorMaker); - - Gson g = new Gson(); - g.toJson(updateWhiteList); - InputStream inputStream; - inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8); - // callPubSub(newRandom, ctx, inputStream); - callPubSubForWhitelist(newRandom, ctx, inputStream, jsonOb.getString(NAMESPACE)); - - } else if (topicList.contains(newTopic)) { - sendErrResponse(ctx, "The topic already exist."); - - } else if (!getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) { - sendErrResponse(ctx, - "The namespace of the topic does not match with the namespace you provided."); - } - } else { - - JSONObject err = new JSONObject(); - err.append(ERROR, - "listWhiteList is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); - } - - } else { - sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); - } - - } else { - - sendErrResponse(ctx, "This is not a createWhitelist request. Please try again."); - } - - } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException - | TopicExistsException | missingReqdSetting | UnavailableException e) { - - LOGGER.error("IOException: ", e); - } - } - // Send error response if user does not provide Authorization - else { - sendErrResponse(ctx, NO_USER_PERMISSION); - } - } - - @SuppressWarnings("unchecked") - @POST - @Produces("application/json") - @Path("/deletewhitelist") - public void deleteWhiteList(InputStream msg) { - - DMaaPContext ctx = getDmaapContext(); - if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { - - loadProperty(); - String input = null; - - try { - input = IOUtils.toString(msg, UTF_8); - - if (input != null && input.length() > 0) { - input = removeExtraChar(input); - } - - // Check if it is correct Json object - JSONObject jsonOb = null; - - try { - jsonOb = new JSONObject(input); - - } catch (JSONException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); - } - - // Check if the request has name and name contains only alpha - // numeric, - // check if the request has namespace and - // check if the request has whitelistTopicName - if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") - && isAlphaNumeric(jsonOb.getString("name")) && jsonOb.has(NAMESPACE) - && jsonOb.has("whitelistTopicName") - && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring( - jsonOb.getString("whitelistTopicName").lastIndexOf(".") + 1, - jsonOb.getString("whitelistTopicName").length()))) { - - String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, - "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; - - // Check if the user have create permission for the - // namespace - if (checkMirrorMakerPermission(ctx, permission)) { - - JSONObject listAll = new JSONObject(); - JSONObject emptyObject = new JSONObject(); - - // Create a listAllMirrorMaker Json object - try { - listAll.put("listAllMirrorMaker", emptyObject); - - } catch (JSONException e) { - - LOGGER.error("JSONException: ", e); - } - - // set a random number as messageID - String randomStr = getRandomNum(); - listAll.put("messageID", randomStr); - InputStream inStream = null; - - // convert listAll Json object to InputStream object - try { - inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); - - } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); - } - // call listAllMirrorMaker - mirrorService.pushEvents(ctx, topic, inStream, null, null); - - // subscribe for listMirrorMaker - long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - - while (!isListMirrorMaker(msgFrmSubscribe, randomStr) - && (System.currentTimeMillis() - startTime) < timeout) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - - JSONObject jsonObj; - JSONArray jsonArray; - JSONArray listMirrorMaker = null; - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomStr)) { - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); - - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); - - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomStr) - && obj.has(LISTMIRRORMAKER)) { - listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER); - break; - } - } - String whitelist = null; - if (listMirrorMaker != null) { - for (int i = 0; i < listMirrorMaker.length(); i++) { - - JSONObject mm = new JSONObject(); - mm = listMirrorMaker.getJSONObject(i); - String name = mm.getString("name"); - - if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { - whitelist = mm.getString("whitelist"); - break; - } - } - } - - List topicList = new ArrayList<>(); - - if (whitelist != null) { - topicList = Arrays.asList(whitelist.split(",")); - } - boolean removeTopic = false; - String topicToRemove = jsonOb.getString("whitelistTopicName"); - - if (topicList.contains(topicToRemove)) { - removeTopic = true; - } else { - sendErrResponse(ctx, "The topic does not exist."); - } - - if (removeTopic) { - UpdateWhiteList updateWhiteList = new UpdateWhiteList(); - MirrorMaker mirrorMaker = new MirrorMaker(); - - mirrorMaker.setName(jsonOb.getString("name")); - mirrorMaker.setWhitelist(removeTopic(whitelist, topicToRemove)); - - String newRandom = getRandomNum(); - - updateWhiteList.setMessageID(newRandom); - updateWhiteList.setUpdateWhiteList(mirrorMaker); - - Gson g = new Gson(); - g.toJson(updateWhiteList); - - InputStream inputStream; - inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8); - callPubSubForWhitelist(newRandom, ctx, inputStream, getNamespace(topicToRemove)); - } - - } else { - - JSONObject err = new JSONObject(); - err.append(ERROR, - "listWhiteList is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); - } - - } else { - sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); - } - - } else { - - sendErrResponse(ctx, "This is not a DeleteAllWhitelist request. Please try again."); - } - - } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException - | TopicExistsException | missingReqdSetting | UnavailableException e) { - - LOGGER.error("IOException: ", e); - } - } - // Send error response if user does not provide Authorization - else { - sendErrResponse(ctx, NO_USER_PERMISSION); - } - } - - private String getNamespace(String topic) { - return topic.substring(0, topic.lastIndexOf(".")); - } - - private String removeTopic(String whitelist, String topicToRemove) { - List topicList = new ArrayList<>(); - List newTopicList = new ArrayList<>(); - - if (whitelist.contains(",")) { - topicList = Arrays.asList(whitelist.split(",")); - - } - - if (topicList.contains(topicToRemove)) { - for (String topic : topicList) { - if (!topic.equals(topicToRemove)) { - newTopicList.add(topic); - } - } - } - - String newWhitelist = StringUtils.join(newTopicList, ","); - - return newWhitelist; - } - - private void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, String namespace) { - - try { - mirrorService.pushEvents(ctx, topic, inStream, null, null); - long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - - while (!isListMirrorMaker(msgFrmSubscribe, randomStr) - && (System.currentTimeMillis() - startTime) < timeout) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - - JSONObject jsonObj; - JSONArray jsonArray; - JSONArray jsonArrayNamespace = null; - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomStr)) { - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); - - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); - - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) { - jsonArrayNamespace = obj.getJSONArray(LISTMIRRORMAKER); - } - } - JSONObject finalJasonObj = new JSONObject(); - JSONArray finalJsonArray = new JSONArray(); - - for (int i = 0; i < jsonArrayNamespace.length(); i++) { - - JSONObject mmObj; - mmObj = jsonArrayNamespace.getJSONObject(i); - String whitelist; - - if (mmObj.has("whitelist")) { - whitelist = getWhitelistByNamespace(mmObj.getString("whitelist"), namespace); - - if (whitelist != null) { - mmObj.remove("whitelist"); - mmObj.put("whitelist", whitelist); - } else { - mmObj.remove("whitelist"); - } - } - finalJsonArray.put(mmObj); - } - finalJasonObj.put(LISTMIRRORMAKER, finalJsonArray); - - DMaaPResponseBuilder.respondOk(ctx, finalJasonObj); - - } else { - - JSONObject err = new JSONObject(); - err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); - } - - } catch (Exception e) { - LOGGER.error("Exception: ", e); - } - } - - private String getWhitelistByNamespace(String originalWhitelist, String namespace) { - - String whitelist = null; - List resultList = new ArrayList<>(); - List whitelistList = new ArrayList<>(); - whitelistList = Arrays.asList(originalWhitelist.split(",")); - - for (String topic : whitelistList) { - if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) { - resultList.add(topic); - } - } - if (!resultList.isEmpty()) { - whitelist = StringUtils.join(resultList, ","); - } - - return whitelist; - } - - private JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) { - JSONObject jsonObj; - JSONArray jsonArray; - JSONArray listMirrorMaker = new JSONArray(); - - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); - - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); - - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) { - listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER); - break; - } - } - return listMirrorMaker; - } -} diff --git a/src/main/java/com/att/nsa/dmaap/service/MetricsRestService.java b/src/main/java/com/att/nsa/dmaap/service/MetricsRestService.java deleted file mode 100644 index 8ff58f3..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/MetricsRestService.java +++ /dev/null @@ -1,152 +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.dmaap.service; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; - -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.service.MetricsService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; - -/** - * This class is a CXF REST service which acts - * as gateway for MR Metrics Service. - * @author rajashree.khare - * - */ -@Component -@Path("/") -public class MetricsRestService { - - /** - * Logger obj - */ - //private Logger log = Logger.getLogger(MetricsRestService.class.toString()); - private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigurationReader.class); - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest request; - - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse response; - - /** - * Config Reader - */ - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - /** - * MetricsService obj - */ - @Autowired - private MetricsService metricsService; - - /** - * Get Metrics method - * @throws CambriaApiException ex - */ - @GET - @Produces("text/plain") - public void getMetrics() throws CambriaApiException { - try { - log.info("MetricsRestService: getMetrics : START"); - metricsService.get(getDmaapContext()); - log.info("MetricsRestService: getMetrics : Completed"); - } catch (IOException e) { - log.error("Error while fetching metrics data : ", e); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.GET_METRICS_ERROR.getResponseCode(), - "Error while fetching metrics data"+ e.getMessage()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - /** - * This method is for get the metrics details by the metrics name - * - * @param metricName - * @throws CambriaApiException - */ - @GET - @Path("/{metricName}") - @Produces("text/plain") - public void getMetricsByName(@PathParam("metricName") String metricName) - throws CambriaApiException { - - try { - log.info("MetricsProducer: getMetricsByName : START"); - metricsService.getMetricByName(getDmaapContext(), metricName); - log.info("MetricsRestService: getMetricsByName : Completed"); - } catch (IOException | CambriaApiException e) { - log.error("Error while fetching metrics data : ", e); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GET_METRICS_ERROR.getResponseCode(), - "Error while fetching metrics data"+ e.getMessage()); - log.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - /** - * This method is used for taking Configuration Object,HttpServletRequest - * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession - * Object. - * - * @return DMaaPContext object from where user can get Configuration - * Object,HttpServlet Object - * - */ - private DMaaPContext getDmaapContext() { - DMaaPContext dmaapContext = new DMaaPContext(); - dmaapContext.setConfigReader(configReader); - dmaapContext.setRequest(request); - dmaapContext.setResponse(response); - return dmaapContext; - } - -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/service/ServiceUtil.java b/src/main/java/com/att/nsa/dmaap/service/ServiceUtil.java deleted file mode 100644 index d73bcaf..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/ServiceUtil.java +++ /dev/null @@ -1,39 +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.dmaap.service; - -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; - -public class ServiceUtil { - private static DMaaPContext dmaaPContext; - - - public static DMaaPContext getDMaaPContext(ConfigurationReader configReader,HttpServletRequest request,HttpServletResponse response) { - dmaaPContext = new DMaaPContext(); - dmaaPContext.setConfigReader(configReader); - dmaaPContext.setRequest(request); - dmaaPContext.setResponse(response); - return dmaaPContext; - } - -} diff --git a/src/main/java/com/att/nsa/dmaap/service/TopicRestService.java b/src/main/java/com/att/nsa/dmaap/service/TopicRestService.java deleted file mode 100644 index 42049d2..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/TopicRestService.java +++ /dev/null @@ -1,696 +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.dmaap.service; - -import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -import org.apache.http.HttpStatus; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.json.JSONException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.beans.TopicBean; -import org.onap.dmaap.dmf.mr.constants.CambriaConstants; -import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; -import org.onap.dmaap.dmf.mr.service.TopicService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; - -/** - * This class is a CXF REST service which acts - * as gateway for MR Topic Service. - * @author Ramkumar Sembaiyan - * - */ - -@Component -@Path("/") -public class TopicRestService { - - /** - * Logger obj - */ - //private static final Logger LOGGER = Logger .getLogger(TopicRestService.class); - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(TopicRestService.class); - /** - * Config Reader - */ - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest request; - - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse response; - - /** - * TopicService obj - */ - @Autowired - private TopicService topicService; - - /** - * DMaaPErrorMessages obj - */ - @Autowired - private DMaaPErrorMessages errorMessages; - - /** - * mrNamespace - */ - //@Value("${msgRtr.namespace.aaf}") -// private String mrNamespace; - - - /** - * Fetches a list of topics from the current kafka instance and converted - * into json object. - * - * @return list of the topics in json format - * @throws AccessDeniedException - * @throws CambriaApiException - * @throws IOException - * @throws JSONException - * */ - @GET - //@Produces(MediaType.TEXT_PLAIN) - public void getTopics() throws CambriaApiException { - try { - - LOGGER.info("Authenticating the user before fetching the topics"); - //String permission = "com.att.dmaap.mr.topic|*|view"; - String mrNameS= com.att.ajsc.beans.PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop,"msgRtr.namespace.aaf"); - String permission =mrNameS+"|"+"*"+"|"+"view"; - DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); - //Check if client is using AAF CADI Basic Authorization - //If yes then check for AAF role authentication else display all topics - if(null!=getDmaapContext().getRequest().getHeader("Authorization")) - { - if(!aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) - { - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), - errorMessages.getNotPermitted1()+" read "+errorMessages.getNotPermitted2()); - LOGGER.info(errRes.toString()); - throw new DMaaPAccessDeniedException(errRes); - - - } - } - - LOGGER.info("Fetching all Topics"); - //topicService = new com.att.dmf.mr.service.impl.TopicServiceImpl(); - topicService.getTopics(getDmaapContext()); - - LOGGER.info("Returning List of all Topics"); - - - } catch (JSONException | ConfigDbException | IOException excp) { - LOGGER.error( - "Failed to retrieve list of all topics: " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GET_TOPICS_FAIL.getResponseCode(), - errorMessages.getTopicsfailure()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - - } - } - - /** - * Fetches a list of topics from the current kafka instance and converted - * into json object. - * - * @return list of the topics in json format - * @throws AccessDeniedException - * @throws CambriaApiException - * @throws IOException - * @throws JSONException - * */ - @GET - @Path("/listAll") - //@Produces(MediaType.TEXT_PLAIN) - public void getAllTopics() throws CambriaApiException { - try { - - LOGGER.info("Authenticating the user before fetching the topics"); - //String permission = "com.att.dmaap.mr.topic|*|view"; - String mrNameS= com.att.ajsc.beans.PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop,"msgRtr.namespace.aaf"); - String permission =mrNameS+"|"+"*"+"|"+"view"; - DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); - //Check if client is using AAF CADI Basic Authorization - //If yes then check for AAF role authentication else display all topics - if(null!=getDmaapContext().getRequest().getHeader("Authorization")) - { - if(!aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) - { - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), - errorMessages.getNotPermitted1()+" read "+errorMessages.getNotPermitted2()); - LOGGER.info(errRes.toString()); - throw new DMaaPAccessDeniedException(errRes); - - - } - } - - LOGGER.info("Fetching all Topics"); - - topicService.getAllTopics(getDmaapContext()); - - LOGGER.info("Returning List of all Topics"); - - - } catch (JSONException | ConfigDbException | IOException excp) { - LOGGER.error( - "Failed to retrieve list of all topics: " - + excp.getMessage(), excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GET_TOPICS_FAIL.getResponseCode(), - errorMessages.getTopicsfailure()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - - } - } - - - /** - * Returns details of the topic whose name is passed as a parameter - * - * @param topicName - * - name of the topic - * @return details of a topic whose name is mentioned in the request in json - * format. - * @throws AccessDeniedException - * @throws DMaaPAccessDeniedException - * @throws IOException - * */ - @GET - @Path("/{topicName}") - //@Produces(MediaType.TEXT_PLAIN) - public void getTopic(@PathParam("topicName") String topicName) throws CambriaApiException { - try { - - LOGGER.info("Authenticating the user before fetching the details about topic = "+ topicName); - DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); - - //String permission= "com.att.ecomp_test.crm.mr.topic|:topic.com.att.ecomp_test.crm.preDemo|view"; - - //Check if client is using AAF CADI Basic Authorization - //If yes then check for AAF role authentication else display all topics - if(null!=getDmaapContext().getRequest().getHeader("Authorization")) - { - String permission = aaf.aafPermissionString(topicName, "view"); - if(!aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) - { - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), - errorMessages.getNotPermitted1()+" read "+errorMessages.getNotPermitted2()); - LOGGER.info(errRes.toString()); - throw new DMaaPAccessDeniedException(errRes); - } - } - - LOGGER.info("Fetching Topic: " + topicName); - - topicService.getTopic(getDmaapContext(), topicName); - - LOGGER.info("Fetched details of topic: " + topicName); - - } catch (ConfigDbException | IOException | TopicExistsException excp) { - LOGGER.error("Failed to retrieve details of topic: " + topicName, - excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GET_TOPICS_DETAILS_FAIL.getResponseCode(), - errorMessages.getTopicDetailsFail()+topicName+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - - } - } - - - - /** - * This method is still not working. Need to check on post call and how to - * accept parameters for post call - * - * @param topicBean - * it will have the bean object - * @throws TopicExistsException - * @throws CambriaApiException - * @throws JSONException - * @throws IOException - * @throws AccessDeniedException - * - * */ - @POST - @Path("/create") - @Consumes({ MediaType.APPLICATION_JSON }) - //@Produces(MediaType.TEXT_PLAIN) - public void createTopic(TopicBean topicBean) throws CambriaApiException, JSONException { - try { - LOGGER.info("Creating Topic."+topicBean.getTopicName()); - - topicService.createTopic(getDmaapContext(), topicBean); - - LOGGER.info("Topic created Successfully."); - } - catch (TopicExistsException ex){ - - LOGGER.error("Error while creating a topic: " + ex.getMessage(), - ex); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, - DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), - errorMessages.getCreateTopicFail()+ ex.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - - - - }catch (AccessDeniedException | DMaaPAccessDeniedException excp) { - LOGGER.error("Error while creating a topic: " + excp.getMessage(), - excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), - errorMessages.getCreateTopicFail()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - }catch (CambriaApiException | IOException excp) { - LOGGER.error("Error while creating a topic: " + excp.getMessage(), - excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), - errorMessages.getCreateTopicFail()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * Deletes existing topic whose name is passed as a parameter - * - * @param topicName - * topic - * @throws CambriaApiException - * @throws IOException - * */ - @DELETE - @Path("/{topicName}") - //@Produces(MediaType.TEXT_PLAIN) - public void deleteTopic(@PathParam("topicName") String topicName) throws CambriaApiException { - try { - LOGGER.info("Deleting Topic: " + topicName); - - topicService.deleteTopic(getDmaapContext(), topicName); - - LOGGER.info("Topic [" + topicName + "] deleted successfully."); - } catch (DMaaPAccessDeniedException| AccessDeniedException excp) { - LOGGER.error("Error while creating a topic: " + excp.getMessage(), - excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), - errorMessages.getCreateTopicFail()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - }catch (IOException | ConfigDbException - | CambriaApiException | TopicExistsException excp) { - LOGGER.error("Error while deleting topic: " + topicName, excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.DELETE_TOPIC_FAIL.getResponseCode(), - errorMessages.getDeleteTopicFail()+ topicName + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - private DMaaPContext getDmaapContext() { - - DMaaPContext dmaapContext = new DMaaPContext(); - dmaapContext.setRequest(request); - dmaapContext.setResponse(response); - dmaapContext.setConfigReader(configReader); - - return dmaapContext; - - } - - /** - * This method will fetch the details of publisher by giving topic name - * - * @param topicName - * @throws CambriaApiException - * @throws AccessDeniedException - */ - @GET - @Path("/{topicName}/producers") - //@Produces(MediaType.TEXT_PLAIN) - public void getPublishersByTopicName( - @PathParam("topicName") String topicName) throws CambriaApiException { - try { - -// String permission = "com.att.dmaap.mr.topic"+"|"+topicName+"|"+"manage"; -// DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); -// String permission = aaf.aafPermissionString(topicName, "view"); -// if(aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) -// { - LOGGER.info("Fetching list of all the publishers for topic " - + topicName); - - topicService.getPublishersByTopicName(getDmaapContext(), topicName); - - LOGGER.info("Returning list of all the publishers for topic " - + topicName); -// }else{ -// LOGGER.error("Error while fetching list of publishers for topic "+ topicName); -// -// ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, -// DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), -// errorMessages.getNotPermitted1()+" fetch list of publishers "+errorMessages.getNotPermitted2()); -// LOGGER.info(errRes); -// throw new DMaaPAccessDeniedException(errRes); -// -// } - - } catch (IOException | ConfigDbException | TopicExistsException excp) { - LOGGER.error("Error while fetching list of publishers for topic " - + topicName, excp); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.GET_PUBLISHERS_BY_TOPIC.getResponseCode(), - "Error while fetching list of publishers for topic: " - + topicName + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * proving permission for the topic for a particular publisher id - * - * @param topicName - * @param producerId - * @throws CambriaApiException - */ - @PUT - @Path("/{topicName}/producers/{producerId}") - public void permitPublisherForTopic( - @PathParam("topicName") String topicName, - @PathParam("producerId") String producerId) throws CambriaApiException { - try { - LOGGER.info("Granting write access to producer [" + producerId - + "] for topic " + topicName); - - topicService.permitPublisherForTopic(getDmaapContext(), topicName, - producerId); - - LOGGER.info("Write access has been granted to producer [" - + producerId + "] for topic " + topicName); - } catch (AccessDeniedException | DMaaPAccessDeniedException excp) { - LOGGER.error("Error while creating a topic: " + excp.getMessage(), - excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), - errorMessages.getCreateTopicFail()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - }catch ( ConfigDbException | IOException - | TopicExistsException excp) { - LOGGER.error("Error while granting write access to producer [" - + producerId + "] for topic " + topicName, excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, - DMaaPResponseCode.PERMIT_PUBLISHER_FOR_TOPIC.getResponseCode(), - "Error while granting write access to producer [" - + producerId + "] for topic " + topicName + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * Removing access for a publisher id for any particular topic - * - * @param topicName - * @param producerId - * @throws CambriaApiException - */ - @DELETE - @Path("/{topicName}/producers/{producerId}") - public void denyPublisherForTopic(@PathParam("topicName") String topicName, - @PathParam("producerId") String producerId) throws CambriaApiException { - try { - LOGGER.info("Revoking write access to producer [" + producerId - + "] for topic " + topicName); - - topicService.denyPublisherForTopic(getDmaapContext(), topicName, - producerId); - - LOGGER.info("Write access revoked for producer [" + producerId - + "] for topic " + topicName); - } catch (DMaaPAccessDeniedException | AccessDeniedException excp) { - LOGGER.error("Error while creating a topic: " + excp.getMessage(), - excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), - errorMessages.getCreateTopicFail()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - }catch ( ConfigDbException | IOException - | TopicExistsException excp) { - LOGGER.error("Error while revoking write access for producer [" - + producerId + "] for topic " + topicName, excp); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.REVOKE_PUBLISHER_FOR_TOPIC.getResponseCode(), - "Error while revoking write access to producer [" - + producerId + "] for topic " + topicName + excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - /** - * Get the consumer details by the topic name - * - * @param topicName - * @throws AccessDeniedException - * @throws CambriaApiException - */ - @GET - @Path("/{topicName}/consumers") - //@Produces(MediaType.TEXT_PLAIN) - public void getConsumersByTopicName(@PathParam("topicName") String topicName) throws AccessDeniedException, - CambriaApiException { - try { - - -// String permission = "com.att.dmaap.mr.topic"+"|"+topicName+"|"+"view"; -// DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); -// String permission = aaf.aafPermissionString(topicName, "view"); -// if(aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) -// { - LOGGER.info("Fetching list of all consumers for topic " + topicName); - - topicService.getConsumersByTopicName(getDmaapContext(), topicName); - - LOGGER.info("Returning list of all consumers for topic " - + topicName); - -// }else{ -// LOGGER.error( -// "Error while fetching list of all consumers for topic " -// + topicName); -// ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, -// DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), -// errorMessages.getNotPermitted1()+" fetch list of consumers "+errorMessages.getNotPermitted2()); -// LOGGER.info(errRes); -// throw new DMaaPAccessDeniedException(errRes); -// -// -// } - - - - } catch (IOException | ConfigDbException | TopicExistsException excp) { - LOGGER.error( - "Error while fetching list of all consumers for topic " - + topicName, excp); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.GET_CONSUMERS_BY_TOPIC.getResponseCode(), - "Error while fetching list of all consumers for topic: " - + topicName+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * providing access for consumer for any particular topic - * - * @param topicName - * @param consumerId - * @throws CambriaApiException - */ - @PUT - @Path("/{topicName}/consumers/{consumerId}") - public void permitConsumerForTopic( - @PathParam("topicName") String topicName, - @PathParam("consumerId") String consumerId) throws CambriaApiException { - try { - LOGGER.info("Granting read access to consumer [" + consumerId - + "] for topic " + topicName); - - topicService.permitConsumerForTopic(getDmaapContext(), topicName, - consumerId); - - LOGGER.info("Read access granted to consumer [" + consumerId - + "] for topic " + topicName); - } catch (AccessDeniedException | ConfigDbException | IOException - | TopicExistsException excp) { - LOGGER.error("Error while granting read access to consumer [" - + consumerId + "] for topic " + topicName, excp); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.PERMIT_CONSUMER_FOR_TOPIC.getResponseCode(), - "Error while granting read access to consumer [" - + consumerId + "] for topic " + topicName+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - /** - * Removing access for consumer for any particular topic - * - * @param topicName - * @param consumerId - * @throws CambriaApiException - */ - @DELETE - @Path("/{topicName}/consumers/{consumerId}") - public void denyConsumerForTopic(@PathParam("topicName") String topicName, - @PathParam("consumerId") String consumerId) throws CambriaApiException { - try { - LOGGER.info("Revoking read access to consumer [" + consumerId - + "] for topic " + topicName); - - topicService.denyConsumerForTopic(getDmaapContext(), topicName, - consumerId); - - LOGGER.info("Read access revoked to consumer [" + consumerId - + "] for topic " + topicName); - } catch ( ConfigDbException | IOException - | TopicExistsException excp) { - LOGGER.error("Error while revoking read access to consumer [" - + consumerId + "] for topic " + topicName, excp); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, - DMaaPResponseCode.REVOKE_CONSUMER_FOR_TOPIC.getResponseCode(), - "Error while revoking read access to consumer [" - + consumerId + "] for topic " + topicName+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - }catch (DMaaPAccessDeniedException | AccessDeniedException excp) { - LOGGER.error("Error while creating a topic: " + excp.getMessage(), - excp); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, - DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), - errorMessages.getCreateTopicFail()+ excp.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - } - - public TopicService getTopicService() { - return topicService; - } - - public void setTopicService(TopicService topicService) { - this.topicService = topicService; - } - - - - -} diff --git a/src/main/java/com/att/nsa/dmaap/service/TransactionRestService.java b/src/main/java/com/att/nsa/dmaap/service/TransactionRestService.java deleted file mode 100644 index 9354f5c..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/TransactionRestService.java +++ /dev/null @@ -1,176 +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.dmaap.service; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; - -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import com.att.aft.dme2.internal.jettison.json.JSONException; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.service.TransactionService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import com.att.nsa.configs.ConfigDbException; - -/** - * This class is a CXF REST service - * which acts as gateway for DMaaP - * Transaction Ids. - * @author rajashree.khare - * - */ -@Component -@Path("/") -public class TransactionRestService { - - /** - * Logger obj - */ - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(TransactionRestService.class); - - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest request; - - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse response; - - /** - * Config Reader - */ - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - @Autowired - private TransactionService transactionService; - - /** - * - * Returns a list of all the existing Transaction Ids - * @throws CambriaApiException - * - * @throws IOException - * @exception ConfigDbException - * @exception IOException - * - * - */ - @GET - public void getAllTransactionObjs() throws CambriaApiException { - try { - LOGGER.info("Retrieving list of all transactions."); - - transactionService.getAllTransactionObjs(getDmaapContext()); - - LOGGER.info("Returning list of all transactions."); - } catch (ConfigDbException | IOException e) { - LOGGER.error("Error while retrieving list of all transactions: " - + e.getMessage(), e); - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_EXPECTATION_FAILED, - DMaaPResponseCode.RETRIEVE_TRANSACTIONS.getResponseCode(), - "Error while retrieving list of all transactions:"+e.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - } - } - - /** - * - * Returns details of a particular transaction id whose name is - * passed as a parameter - * - * @param transactionId - * - id of transaction - * @throws CambriaApiException - * @throws IOException - * @exception ConfigDbException - * @exception IOException - * @exception JSONException - * - * - */ - @GET - @Path("/{transactionId}") - public void getTransactionObj( - @PathParam("transactionId") String transactionId) throws CambriaApiException { - - LOGGER.info("Fetching details of Transaction ID : " + transactionId); - - try { - transactionService.getTransactionObj(getDmaapContext(), - transactionId); - } catch (ConfigDbException | JSONException | IOException e) { - LOGGER.error("Error while retrieving transaction details for id: " - + transactionId, e); - - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_EXPECTATION_FAILED, - DMaaPResponseCode.RETRIEVE_TRANSACTIONS_DETAILS.getResponseCode(), - "Error while retrieving transaction details for id: [" - + transactionId + "]: " + e.getMessage()); - LOGGER.info(errRes.toString()); - throw new CambriaApiException(errRes); - - } - - LOGGER.info("Returning details of transaction " + transactionId); - - } - - /** - * This method is used for taking Configuration Object,HttpServletRequest - * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession - * Object. - * - * @return DMaaPContext object from where user can get Configuration - * Object,HttpServlet Object - * - */ - private DMaaPContext getDmaapContext() { - DMaaPContext dmaapContext = new DMaaPContext(); - dmaapContext.setConfigReader(configReader); - dmaapContext.setRequest(request); - dmaapContext.setResponse(response); - return dmaapContext; - } - -} \ No newline at end of file diff --git a/src/main/java/com/att/nsa/dmaap/service/UIRestServices.java b/src/main/java/com/att/nsa/dmaap/service/UIRestServices.java deleted file mode 100644 index f82d0a1..0000000 --- a/src/main/java/com/att/nsa/dmaap/service/UIRestServices.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.dmaap.service; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; - -import org.apache.kafka.common.errors.TopicExistsException; - -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.service.UIService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; -import com.att.nsa.configs.ConfigDbException; - -/** - * UI Rest Service - * @author rajashree.khare - * - */ -@Component -public class UIRestServices { - - /** - * Logger obj - */ - //private static final Logger LOGGER = Logger.getLogger(UIRestServices.class); - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(UIRestServices.class); - - @Autowired - private UIService uiService; - - /** - * Config Reader - */ - @Autowired - @Qualifier("configurationReader") - private ConfigurationReader configReader; - - /** - * HttpServletRequest obj - */ - @Context - private HttpServletRequest request; - - /** - * HttpServletResponse obj - */ - @Context - private HttpServletResponse response; - - /** - * getting the hello - */ - @GET - @Path("/") - public void hello() { - try { - LOGGER.info("Calling hello page."); - - uiService.hello(getDmaapContext()); - - LOGGER.info("Hello page is returned."); - } catch (IOException excp) { - LOGGER.error("Error while calling hello page: " + excp.getMessage(), excp); - DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, - "Error while calling hello page: " + excp.getMessage()); - } - } - - /** - * getApikeysTable - */ - @GET - @Path("/ui/apikeys") - public void getApiKeysTable() { - try { - LOGGER.info("Fetching list of all api keys."); - - uiService.getApiKeysTable(getDmaapContext()); - - LOGGER.info("Returning list of all api keys."); - } catch (ConfigDbException | IOException excp) { - LOGGER.error("Error while fetching list of all api keys: " + excp.getMessage(), excp); - DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, - "Error while fetching list of all api keys: " + excp.getMessage()); - } - } - - /** - * getApiKey - * - * @param apiKey - * @exception Exception - */ - @GET - @Path("/ui/apikeys/{apiKey}") - public void getApiKey(@PathParam("apiKey") String apiKey) { - try { - LOGGER.info("Fetching details of api key: " + apiKey); - - uiService.getApiKey(getDmaapContext(), apiKey); - - LOGGER.info("Returning details of api key: " + apiKey); - } catch (Exception excp) { - LOGGER.error("Error while fetching details of api key: " + apiKey, excp); - DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, - "Error while fetching details of api key: " + apiKey); - } - } - - @GET - @Path("/ui/topics") - public void getTopicsTable() { - try { - LOGGER.info("Fetching list of all topics."); - - uiService.getTopicsTable(getDmaapContext()); - - LOGGER.info("Returning list of all topics."); - } catch (ConfigDbException | IOException excp) { - LOGGER.error("Error while fetching list of all topics: " + excp, excp); - DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, - "Error while fetching list of all topics: " + excp.getMessage()); - } - } - - /** - * - * @param topic - */ - @GET - @Path("/ui/topics/{topic}") - public void getTopic(@PathParam("topic") String topic) { - try { - LOGGER.info("Fetching details of topic: " + topic); - - uiService.getTopic(getDmaapContext(), topic); - - LOGGER.info("Returning details of topic: " + topic); - } catch (ConfigDbException | IOException | TopicExistsException excp) { - LOGGER.error("Error while fetching details of topic: " + topic, excp); - DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, - "Error while fetching details of topic: " + topic); - } - } - - /** - * This method is used for taking Configuration Object,HttpServletRequest - * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession - * Object. - * - * @return DMaaPContext object from where user can get Configuration - * Object,HttpServlet Object - * - */ - private DMaaPContext getDmaapContext() { - DMaaPContext dmaapContext = new DMaaPContext(); - dmaapContext.setConfigReader(configReader); - dmaapContext.setRequest(request); - dmaapContext.setResponse(response); - return dmaapContext; - } -} diff --git a/src/main/java/com/att/nsa/dmaap/tools/ConfigTool.java b/src/main/java/com/att/nsa/dmaap/tools/ConfigTool.java deleted file mode 100644 index d896bdd..0000000 --- a/src/main/java/com/att/nsa/dmaap/tools/ConfigTool.java +++ /dev/null @@ -1,818 +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.dmaap.tools; - -import java.io.IOException; -import java.io.PrintStream; -import java.security.NoSuchAlgorithmException; -import java.util.Date; -import java.util.LinkedList; -import java.util.Map.Entry; - -import org.json.JSONException; - -import com.att.nsa.apiServer.CommonServlet; -import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker; -import org.onap.dmaap.dmf.mr.metabroker.Topic; -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandLineTool; -import com.att.nsa.cmdtool.CommandNotReadyException; -import com.att.nsa.configs.ConfigDb; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.configs.ConfigPath; -import com.att.nsa.configs.confimpl.EncryptingLayer; -import com.att.nsa.configs.confimpl.ZkConfigDb; -import com.att.nsa.drumlin.till.data.rrConvertor; -import com.att.nsa.drumlin.till.data.uniqueStringGenerator; -import com.att.nsa.drumlin.till.nv.impl.nvWriteableTable; -import com.att.nsa.security.db.BaseNsaApiDbImpl; -import com.att.nsa.security.db.EncryptingApiDbImpl; -import com.att.nsa.security.db.NsaApiDb.KeyExistsException; -import com.att.nsa.security.db.simple.NsaSimpleApiKey; -import com.att.nsa.security.db.simple.NsaSimpleApiKeyFactory; -import com.att.nsa.util.NsaClock; - -public class ConfigTool extends CommandLineTool -{ - protected ConfigTool () - { - super ( "Cambria API Config Tool", "cambriaConfig> " ); - - super.registerCommand ( new ListTopicCommand () ); - super.registerCommand ( new WriteTopicCommand () ); - super.registerCommand ( new ReadTopicCommand () ); - super.registerCommand ( new SetTopicOwnerCommand () ); - super.registerCommand ( new InitSecureTopicCommand () ); - super.registerCommand ( new ListApiKeysCommand () ); - super.registerCommand ( new PutApiCommand () ); - super.registerCommand ( new writeApiKeyCommand () ); - super.registerCommand ( new EncryptApiKeysCommand () ); - super.registerCommand ( new DecryptApiKeysCommand () ); - super.registerCommand ( new NodeFetchCommand () ); - super.registerCommand ( new DropOldConsumerGroupsCommand () ); - } - - public static void main ( String[] args ) throws IOException - { - final String connStr = args.length>0 ? args[0] : "localhost:2181"; - final ConfigDb db = new ZkConfigDb ( - connStr, - args.length>1 ? args[1] : CommonServlet.getDefaultZkRoot ( "cambria" ) - ); - - final ConfigToolContext context = new ConfigToolContext ( db, connStr, new nvWriteableTable() ); - final ConfigTool ct = new ConfigTool (); - ct.runFromMain ( args, context ); - } - - private static class ListTopicCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "topics", "list (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final ConfigDb db = context.getDb(); - final ConfigPath base = db.parse ( "/topics" ); - - if ( parts.length > 0 ) - { - final ConfigPath myTopic = base.getChild ( parts[0] ); - final String data = db.load ( myTopic ); - if ( data != null ) - { - out.println ( data ); - } - else - { - out.println ( "No topic [" + parts[0] + "]" ); - } - } - else - { - for ( ConfigPath child : db.loadChildrenNames ( base ) ) - { - out.println ( child.getName () ); - } - } - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "topics" ); - out.println ( "list " ); - } - } - - private static class WriteTopicCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "write (\\S*) (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final ConfigDb db = context.getDb(); - final ConfigPath base = db.parse ( "/topics" ); - final ConfigPath myTopic = base.getChild ( parts[0] ); - db.store ( myTopic, parts[1] ); - out.println ( "wrote [" + parts[1] + "] to topic [" + parts[0] + "]" ); - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "write " ); - out.println ( "\tBe careful with this. You can write data that's not compatible with Cambria's config db." ); - } - } - - private static class ReadTopicCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "read (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final ConfigDb db = context.getDb(); - final ConfigPath base = db.parse ( "/topics" ); - final ConfigPath myTopic = base.getChild ( parts[0] ); - db.store ( myTopic, parts[1] ); - out.println ( "wrote [" + parts[1] + "] to topic [" + parts[0] + "]" ); - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "read " ); - out.println ( "\tRead config data for a topic." ); - } - } - - private static class InitSecureTopicCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "initTopic (\\S*) (\\S*) (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - DMaaPKafkaMetaBroker.createTopicEntry ( context.getDb (), - context.getDb ().parse("/topics"), parts[0], parts[2], parts[1],true ); - out.println ( "Topic [" + parts[0] + "] updated." ); - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage () ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "initTopic " ); - } - } - - private static class SetTopicOwnerCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "setOwner (\\S*) (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final Topic kt = DMaaPKafkaMetaBroker.getKafkaTopicConfig ( context.getDb(), - context.getDb().parse ( "/topics" ), parts[0] ); - if ( kt != null ) - { - final String desc = kt.getDescription (); - - DMaaPKafkaMetaBroker.createTopicEntry ( context.getDb (), - context.getDb ().parse("/topics"), parts[0], desc, parts[1], true ); - out.println ( "Topic [" + parts[0] + "] updated." ); - } - else - { - out.println ( "Topic [" + parts[0] + "] doesn't exist." ); - } - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage () ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "setOwner " ); - } - } - - private static class ListApiKeysCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "listApiKeys", "listApiKey (\\S*) (\\S*) (\\S*)", "listApiKey (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final ConfigDb db = context.getDb (); - if ( parts.length == 0 ) - { - final BaseNsaApiDbImpl readFrom = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); - int count = 0; - for ( String key : readFrom.loadAllKeys () ) - { - out.println ( key ); - count++; - } - out.println ( "" + count + " records." ); - } - else - { - BaseNsaApiDbImpl readFrom = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); - if ( parts.length == 3 ) - { - readFrom = new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), - EncryptingLayer.readSecretKey ( parts[1] ), rrConvertor.base64Decode ( parts[2] ) ); - } - final NsaSimpleApiKey apikey = readFrom.loadApiKey ( parts[0] ); - if ( apikey == null ) - { - out.println ( "Key '" + parts[0] + "' not found." ); - } - else - { - out.println ( apikey.asJsonObject ().toString () ); - } - } - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( JSONException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "listApiKeys" ); - out.println ( "listApiKey " ); - out.println ( "listApiKey " ); - } - } - - private static class PutApiCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] - { - // these are - "putApiKey (secret) (\\S*) (\\S*) (\\S*) (\\S*)", - "putApiKey (email) (\\S*) (\\S*) (\\S*) (\\S*)", - "putApiKey (description) (\\S*) (\\S*) (\\S*) (\\S*)" - }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final ConfigDb db = context.getDb (); - if ( parts.length == 5 ) - { - final BaseNsaApiDbImpl apiKeyDb = - new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), - EncryptingLayer.readSecretKey ( parts[2] ), rrConvertor.base64Decode ( parts[3] ) ); - - final NsaSimpleApiKey apikey = apiKeyDb.loadApiKey ( parts[1] ); - if ( apikey == null ) - { - out.println ( "Key '" + parts[1] + "' not found." ); - } - else - { - if ( parts[0].equalsIgnoreCase ( "secret" ) ) - { - apikey.resetSecret ( parts[4] ); - } - else if ( parts[0].equalsIgnoreCase ( "email" ) ) - { - apikey.setContactEmail ( parts[4] ); - } - else if ( parts[0].equalsIgnoreCase ( "description" ) ) - { - apikey.setDescription ( parts[4] ); - } - - apiKeyDb.saveApiKey ( apikey ); - out.println ( apikey.asJsonObject ().toString () ); - } - } - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( JSONException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "putApiKey secret " ); - out.println ( "putApiKey email " ); - out.println ( "putApiKey description " ); - } - } - - private static class writeApiKeyCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] - { - // - "writeApiKey (\\S*) (\\S*) (\\S*) (\\S*)", - }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final ConfigDb db = context.getDb (); - if ( parts.length == 4 ) - { - final BaseNsaApiDbImpl apiKeyDb = - new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), - EncryptingLayer.readSecretKey ( parts[0] ), rrConvertor.base64Decode ( parts[1] ) ); - - apiKeyDb.deleteApiKey ( parts[2] ); - final NsaSimpleApiKey apikey = apiKeyDb.createApiKey ( parts[2], parts[3] ); - out.println ( apikey.asJsonObject ().toString () ); - } - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( JSONException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( KeyExistsException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "writeApiKey " ); - } - } - - private static class EncryptApiKeysCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "convertApiKeyDb", "convertApiKeyDb (\\S*) (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final String key = parts.length == 2 ? parts[0] : EncryptingLayer.createSecretKey (); - final String iv = parts.length == 2 ? parts[1] : rrConvertor.base64Encode ( uniqueStringGenerator.createValue ( 16 ) ); - - // This doesn't do well when the number of API keys is giant... - if ( parts.length == 0 ) - { - out.println ( "YOU MUST RECORD THESE VALUES AND USE THEM IN THE SERVER CONFIG" ); - out.println ( "Key: " + key ); - out.println ( " IV: " + iv ); - out.println ( "\n" ); - out.println ( "Call again with key and IV on command line." ); - out.println ( "\n" ); - return; // because otherwise the values get lost - } - - final ConfigDb db = context.getDb (); - final BaseNsaApiDbImpl readFrom = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); - final EncryptingApiDbImpl writeTo = new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), - EncryptingLayer.readSecretKey ( key ), rrConvertor.base64Decode ( iv ) ); - - int count = 0; - for ( Entry e : readFrom.loadAllKeyRecords ().entrySet () ) - { - out.println ( "-------------------------------" ); - out.println ( "Converting " + e.getKey () ); - final String was = e.getValue ().asJsonObject ().toString (); - out.println ( was ); - - writeTo.saveApiKey ( e.getValue () ); - count++; - } - - out.println ( "Conversion complete, converted " + count + " records." ); - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( NoSuchAlgorithmException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "convertApiKeyDb" ); - out.println ( "\tconvert an API key DB to an encrypted DB and output the cipher details" ); - } - } - - private static class DecryptApiKeysCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "revertApiKeyDb (\\S*) (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final String keyStr = parts[0]; - final String iv = parts[1]; - final byte[] ivBytes = rrConvertor.base64Decode ( iv ); - - final ConfigDb db = context.getDb (); - final EncryptingApiDbImpl readFrom = new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), - EncryptingLayer.readSecretKey ( keyStr ), ivBytes ); - final BaseNsaApiDbImpl writeTo = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); - - int count = 0; - for ( String apiKey : readFrom.loadAllKeys () ) - { - out.println ( "Converting " + apiKey ); - final NsaSimpleApiKey record = readFrom.loadApiKey ( apiKey ); - if ( record == null ) - { - out.println ( "Couldn't load " + apiKey ); - } - else - { - writeTo.saveApiKey ( record ); - count++; - } - } - out.println ( "Conversion complete, converted " + count + " records." ); - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "revertApiKeyDb " ); - out.println ( "\trevert an API key DB to a deencrypted DB" ); - } - } - - private static class NodeFetchCommand implements Command - { - @Override - public String[] getMatches () - { - return new String[] { "node (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final String node = parts[0]; - - final ConfigDb db = context.getDb (); - final ConfigPath cp = db.parse ( node ); - - boolean doneOne = false; - for ( ConfigPath child : db.loadChildrenNames ( cp ) ) - { - out.println ( "\t- " + child.getName () ); - doneOne = true; - } - if ( doneOne ) - { - out.println (); - } - else - { - out.println ( "(No child nodes of '" + node + "')" ); - } - - final String val = db.load ( cp ); - if ( val == null ) - { - out.println ( "(No data at '" + node + "')" ); - } - else - { - out.println ( val ); - } - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( IllegalArgumentException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "node " ); - out.println ( "\tread a config db node" ); - } - } - - private static class DropOldConsumerGroupsCommand implements Command - { - private final long kMaxRemovals = 500; - - @Override - public String[] getMatches () - { - return new String[] { "(dropOldConsumers) (\\S*)", "(showOldConsumers) (\\S*)" }; - } - - @Override - public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException - { - } - - @Override - public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException - { - try - { - final boolean runDrops = parts[0].equalsIgnoreCase ( "dropOldConsumers" ); - final String maxAgeInDaysStr = parts[1]; - final int maxAgeInDays = Integer.parseInt ( maxAgeInDaysStr ); - final long oldestEpochSecs = ( NsaClock.now () / 1000 ) - ( 24 * 60 * 60 * maxAgeInDays ); - - out.println ( "Dropping consumer groups older than " + new Date ( oldestEpochSecs * 1000 ) ); - - final ConfigDb db = context.getDb (); - - // kafka updates consumer partition records in ZK each time a message - // is served. we can determine which consumers are old based on a lack - // of update to the partition entries - // (see https://cwiki.apache.org/confluence/display/KAFKA/Kafka+data+structures+in+Zookeeper) - - // kafka only works with ZK, and our configDb was constructed with a non-kafka - // root node. We have to switch it to get to the right content... - if ( ! ( db instanceof ZkConfigDb ) ) - { - throw new ConfigDbException ( "You can only show/drop old consumers against a ZK config db." ); - } - - final ZkConfigDb newZkDb = new ZkConfigDb ( context.getConnectionString (), "" ); - long cgCount = 0; - - final LinkedList removals = new LinkedList (); - for ( ConfigPath consumerGroupName : newZkDb.loadChildrenNames ( newZkDb.parse ( "/consumers" ) ) ) - { - cgCount++; - if ( cgCount % 500 == 0 ) - { - out.println ( "" + cgCount + " groups examined" ); - } - - boolean foundAnything = false; - boolean foundRecentUse = false; - long mostRecent = -1; - - // each consumer group has an "offsets" entry, which contains 0 or more topic entries. - // each topic contains partition nodes. - for ( ConfigPath topic : newZkDb.loadChildrenNames ( consumerGroupName.getChild ( "offsets" ) ) ) - { - for ( ConfigPath offset : newZkDb.loadChildrenNames ( topic ) ) - { - foundAnything = true; - - final long modTime = newZkDb.getLastModificationTime ( offset ); - mostRecent = Math.max ( mostRecent, modTime ); - - foundRecentUse = ( modTime > oldestEpochSecs ); - if ( foundRecentUse ) break; - } - if ( foundRecentUse ) break; - } - - // decide if this consumer group is old - out.println ( "Group " + consumerGroupName.getName () + " was most recently used " + new Date ( mostRecent*1000 ) ); - if ( foundAnything && !foundRecentUse ) - { - removals.add ( consumerGroupName ); - } - - if ( removals.size () >= kMaxRemovals ) - { - break; - } - } - - // removals - for ( ConfigPath consumerGroupName : removals ) - { - out.println ( "Group " + consumerGroupName.getName () + " has no recent activity." ); - if ( runDrops ) - { - out.println ( "Removing group " + consumerGroupName.getName () + "..." ); - newZkDb.clear ( consumerGroupName ); - } - } - } - catch ( ConfigDbException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( NumberFormatException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - catch ( JSONException e ) - { - out.println ( "Command failed: " + e.getMessage() ); - } - } - - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "showOldConsumers " ); - out.println ( "dropOldConsumers " ); - out.println ( "\tDrop (or just show) any consumer group that has been inactive longer than days." ); - out.println (); - out.println ( "\tTo be safe, should be much higher than the maximum storage time on the Kafka topics." ); - out.println ( "\tA very old consumer will potentially miss messages, but will resume at the oldest message, while a" ); - out.println ( "\tdeleted consumer will start at the current message if it ever comes back." ); - out.println (); - out.println ( "\tNote that show/drops are limited to " + kMaxRemovals + " records per invocation." ); - } - } -} diff --git a/src/main/java/com/att/nsa/dmaap/tools/ConfigToolContext.java b/src/main/java/com/att/nsa/dmaap/tools/ConfigToolContext.java deleted file mode 100644 index f61d179..0000000 --- a/src/main/java/com/att/nsa/dmaap/tools/ConfigToolContext.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.dmaap.tools; - -import org.onap.dmaap.dmf.mr.beans.DMaaPMetricsSet; -import com.att.nsa.cmdtool.CommandContext; -import com.att.nsa.configs.ConfigDb; -import com.att.nsa.drumlin.till.nv.rrNvReadable; - -public class ConfigToolContext implements CommandContext -{ - public ConfigToolContext ( ConfigDb db, String connStr, rrNvReadable cs ) - { - fDb = db; - fConnStr = connStr; - fMetrics = new DMaaPMetricsSet( cs ); - } - - @Override - public void requestShutdown () - { - fQuit = true; - } - - @Override - public boolean shouldContinue () - { - return !fQuit; - } - - public ConfigDb getDb () - { - return fDb; - } - - public String getConnectionString () - { - return fConnStr; - } - - public DMaaPMetricsSet getMetrics () - { - return fMetrics; - } - - private final ConfigDb fDb; - private final String fConnStr; - private boolean fQuit = false; - private DMaaPMetricsSet fMetrics; -} diff --git a/src/main/java/com/att/nsa/dmaap/util/ContentLengthInterceptor.java b/src/main/java/com/att/nsa/dmaap/util/ContentLengthInterceptor.java deleted file mode 100644 index 4ddc54a..0000000 --- a/src/main/java/com/att/nsa/dmaap/util/ContentLengthInterceptor.java +++ /dev/null @@ -1,138 +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.dmaap.util; - -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.apache.http.HttpStatus; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.stereotype.Component; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import ajsc.beans.interceptors.AjscInterceptor; - -/** - * AJSC Intercepter implementation of ContentLengthFilter - */ -@Component -public class ContentLengthInterceptor implements AjscInterceptor{ - - - private String defLength; - //private Logger log = Logger.getLogger(ContentLengthInterceptor.class.toString()); - private static final EELFLogger log = EELFManager.getInstance().getLogger(ContentLengthInterceptor.class); - - - /** - * Intercepter method to intercept requests before processing - */ - @Override - public boolean allowOrReject(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, - Map map) throws Exception { - - log.info("inside Interceptor allowOrReject content length checking before pub/sub"); - - JSONObject jsonObj = null; - int requestLength = 0; - setDefLength(System.getProperty("maxcontentlength")); - try { - // retrieving content length from message header - - if (null != httpservletrequest.getHeader("Content-Length")) { - requestLength = Integer.parseInt(httpservletrequest.getHeader("Content-Length")); - } - // retrieving encoding from message header - String transferEncoding = httpservletrequest.getHeader("Transfer-Encoding"); - // checking for no encoding, chunked and requestLength greater then - // default length - if (null != transferEncoding && !(transferEncoding.contains("chunked")) - && (requestLength > Integer.parseInt(getDefLength()))) { - jsonObj = new JSONObject().append("defaultlength", getDefLength()) - .append("requestlength", requestLength); - log.error("message length is greater than default"); - throw new CambriaApiException(jsonObj); - } - else if (null == transferEncoding && (requestLength > Integer.parseInt(getDefLength()))) - { - jsonObj = new JSONObject().append("defaultlength", getDefLength()).append( - "requestlength", requestLength); - log.error("Request message is not chunked or request length is greater than default length"); - throw new CambriaApiException(jsonObj); - - - } - else - { - //chain.doFilter(req, res); - return true; - } - - } catch (CambriaApiException | NumberFormatException | JSONException e) { - - log.info("Exception obj--"+e); - log.error("message size is greater then default"+e.getMessage()); - String messg=e.toString(); - if(jsonObj!=null){ - messg=jsonObj.toString(); - } - ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_REQUEST_TOO_LONG, - DMaaPResponseCode.MSG_SIZE_EXCEEDS_MSG_LIMIT.getResponseCode(), System.getProperty("msg_size_exceeds") - + messg); - log.info(errRes.toString()); - - - map.put(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"test"); - httpservletresponse.setStatus(HttpStatus.SC_REQUEST_TOO_LONG); - if(httpservletresponse.getOutputStream()!=null){ - httpservletresponse.getOutputStream().write(errRes.toString().getBytes()); - } - return false; - } - - - - } - - - /** - * Get Default Content Length - * @return defLength - */ - public String getDefLength() { - return defLength; - } - /** - * Set Default Content Length - * @param defLength - */ - public void setDefLength(String defLength) { - this.defLength = defLength; - } - - - -} diff --git a/src/main/java/com/att/nsa/dmaap/util/DMaaPAuthFilter.java b/src/main/java/com/att/nsa/dmaap/util/DMaaPAuthFilter.java deleted file mode 100644 index 4ef8626..0000000 --- a/src/main/java/com/att/nsa/dmaap/util/DMaaPAuthFilter.java +++ /dev/null @@ -1,90 +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.dmaap.util; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - -import org.onap.dmaap.dmf.mr.utils.Utils; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.springframework.stereotype.Component; - -import org.onap.aaf.cadi.filter.CadiFilter; -//import ajsc.external.plugins.cadi.AjscCadiFilter; -import javax.servlet.FilterConfig; - -/** - * This is a Servlet Filter class - * overriding the AjscCadiFilter - */ -@Component -public class DMaaPAuthFilter extends CadiFilter { - - //private Logger log = Logger.getLogger(DMaaPAuthFilter.class.toString()); - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPAuthFilter.class); - - public DMaaPAuthFilter() throws Exception { - super(); - } - - /* public void init(FilterConfig filterConfig) throws ServletException { - - super.init(filterConfig); - System.out.println("---------------------------- in init method"); - }*/ - - /** - * This method will disable Cadi Authentication - * if cambria headers are present in the request - * else continue with Cadi Authentication - */ - @Override - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, - ServletException { - log.info("inside servlet filter Cambria Auth Headers checking before doing other Authentication"); - HttpServletRequest request = (HttpServletRequest) req; - boolean forceAAF = Boolean.valueOf(System.getProperty("forceAAF")); - - //if (forceAAF || null != request.getHeader("Authorization") ){ - if (Utils.isCadiEnabled()&&(forceAAF || null != request.getHeader("Authorization") || - (null != request.getHeader("AppName") && request.getHeader("AppName").equalsIgnoreCase("invenio") && - null != request.getHeader("cookie")))){ - super.doFilter(req, res, chain); - - } else { - System.setProperty("CadiAuthN", "authentication-scheme-2"); - chain.doFilter(req, res); - - - } - - } - - } - diff --git a/src/main/java/com/att/nsa/dmaap/util/ServicePropertiesMapBean.java b/src/main/java/com/att/nsa/dmaap/util/ServicePropertiesMapBean.java deleted file mode 100644 index b16162b..0000000 --- a/src/main/java/com/att/nsa/dmaap/util/ServicePropertiesMapBean.java +++ /dev/null @@ -1,41 +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.dmaap.util; - -import com.att.nsa.dmaap.filemonitor.ServicePropertiesMap; - -/** - * Class ServicePropertiesMapBean - * @author rajashree.khare - * - */ -public class ServicePropertiesMapBean { - /** - * get property - * @param propFileName propFileName - * @param propertyKey propertyKey - * @return str - */ - public static String getProperty(String propFileName, String propertyKey) { - return ServicePropertiesMap.getProperty(propFileName, propertyKey); - } -} diff --git a/src/main/java/org/onap/dmaap/DMaaPCambriaExceptionMapper.java b/src/main/java/org/onap/dmaap/DMaaPCambriaExceptionMapper.java new file mode 100644 index 0000000..4b9324e --- /dev/null +++ b/src/main/java/org/onap/dmaap/DMaaPCambriaExceptionMapper.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; + + +import javax.inject.Singleton; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.springframework.beans.factory.annotation.Autowired; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; + +/** + * Exception Mapper class to handle + * CambriaApiException + * @author rajashree.khare + * + */ +@Provider +@Singleton +public class DMaaPCambriaExceptionMapper implements ExceptionMapper{ + +/** + * Error response obj + */ + private ErrorResponse errRes; + +/** + * Logger obj + */ + + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DMaaPCambriaExceptionMapper.class); + + + /** + * Error msg obj + */ + @Autowired + private DMaaPErrorMessages msgs; + + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest req; + + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse res; + + /** + * Contructor for DMaaPCambriaExceptionMapper + */ + public DMaaPCambriaExceptionMapper() { + super(); + LOGGER.info("Cambria Exception Mapper Created.."); + } + + /** + * The toResponse method is called when + * an exception of type CambriaApiException + * is thrown.This method will send a custom error + * response to the client. + */ + @Override + public Response toResponse(CambriaApiException ex) { + + LOGGER.info("Reached Cambria Exception Mapper.."); + + /** + * Cambria Generic Exception + */ + /*if(ex instanceof CambriaApiException) + {*/ + + errRes = ex.getErrRes(); + if(errRes!=null) { + + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + } + else + { + + Response response = Response.status(ex.getStatus()).header("exception", + ex.getMessage()).build(); + + return response; + } + + + /*} + else + { + errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(), msgs.getServerUnav()); + + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + }*/ + + } + + + +} diff --git a/src/main/java/org/onap/dmaap/DMaaPWebExceptionMapper.java b/src/main/java/org/onap/dmaap/DMaaPWebExceptionMapper.java new file mode 100644 index 0000000..389fb5c --- /dev/null +++ b/src/main/java/org/onap/dmaap/DMaaPWebExceptionMapper.java @@ -0,0 +1,202 @@ +/******************************************************************************* + * ============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; + + +import javax.inject.Singleton; +import javax.ws.rs.BadRequestException; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.NotAllowedException; +import javax.ws.rs.NotAuthorizedException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.ServiceUnavailableException; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.springframework.beans.factory.annotation.Autowired; + +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; + +/** + * Exception Mapper class to handle + * Web Exceptions + * @author rajashree.khare + * + */ +@Provider +@Singleton +public class DMaaPWebExceptionMapper implements ExceptionMapper{ + + /** + * Logger obj + */ + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DMaaPWebExceptionMapper.class); + /** + * Error response obj + */ + private ErrorResponse errRes; + /** + * Error msg obj + */ + @Autowired + private DMaaPErrorMessages msgs; + + /** + * Contructor for DMaaPWebExceptionMapper + */ + public DMaaPWebExceptionMapper() { + super(); + LOGGER.info("WebException Mapper Created.."); + } + + /** + * The toResponse method is called when + * an exception of type WebApplicationException + * is thrown.This method will send a custom error + * response to the client + */ + @Override + public Response toResponse(WebApplicationException ex) { + //System.out.println("--------------------------------------------------"+ex); + LOGGER.info("Reached WebException Mapper"); + + /** + * Resource Not Found + */ + if(ex instanceof NotFoundException) + { + errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND,DMaaPResponseCode.RESOURCE_NOT_FOUND. + getResponseCode(),msgs.getNotFound()); + + LOGGER.info(errRes.toString()); + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + + } + /** + * Internal Server Error + */ + if(ex instanceof InternalServerErrorException) + { + + int errCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; + int dmaapErrCode = DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(); + String errMsg = msgs.getServerUnav(); + + + if(ex.getCause().toString().contains("Json")) { + errCode = HttpStatus.SC_BAD_REQUEST; + dmaapErrCode = DMaaPResponseCode.INCORRECT_JSON.getResponseCode(); + errMsg = ex.getCause().getMessage().substring(0, ex.getCause().getMessage().indexOf("[Source")-3); + } + else if (ex.getCause().toString().contains("UnrecognizedPropertyException")) { + errCode = HttpStatus.SC_BAD_REQUEST; + dmaapErrCode = DMaaPResponseCode.INCORRECT_JSON.getResponseCode(); + errMsg = ex.getCause().getMessage().substring(0, ex.getCause().getMessage().indexOf("[Source")-3); + } + errRes = new ErrorResponse(errCode,dmaapErrCode,errMsg); + + LOGGER.info(errRes.toString()); + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + + } + /** + * UnAuthorized + */ + if(ex instanceof NotAuthorizedException) + { + errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED,DMaaPResponseCode.ACCESS_NOT_PERMITTED. + getResponseCode(),msgs.getAuthFailure()); + + LOGGER.info(errRes.toString()); + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + } + /** + * Malformed request + */ + if(ex instanceof BadRequestException) + { + errRes = new ErrorResponse(HttpStatus.SC_BAD_REQUEST,DMaaPResponseCode.INCORRECT_JSON. + getResponseCode(),msgs.getBadRequest()); + + LOGGER.info(errRes.toString()); + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + } + /** + * HTTP Method not allowed + */ + if(ex instanceof NotAllowedException) + { + errRes = new ErrorResponse(HttpStatus.SC_METHOD_NOT_ALLOWED,DMaaPResponseCode.METHOD_NOT_ALLOWED. + getResponseCode(),msgs.getMethodNotAllowed()); + + LOGGER.info(errRes.toString()); + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + } + + /** + * Server unavailable + */ + if(ex instanceof ServiceUnavailableException) + { + errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE,DMaaPResponseCode.SERVER_UNAVAILABLE. + getResponseCode(),msgs.getServerUnav()); + + LOGGER.info(errRes.toString()); + Response response = Response.status(errRes.getHttpStatusCode()).header("exception", + errRes.getErrMapperStr()).build(); + + return response; + } + + + + return Response.serverError().build(); + } + + + + +} + diff --git a/src/main/java/org/onap/dmaap/HelloWorld.java b/src/main/java/org/onap/dmaap/HelloWorld.java new file mode 100644 index 0000000..5907e7f --- /dev/null +++ b/src/main/java/org/onap/dmaap/HelloWorld.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * ============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; + +import org.apache.camel.Exchange; + +/** + * Hello World Sample Camel Service + * @author rajashree.khare + * + */ +public class HelloWorld { + public HelloWorld () { + } + /** + * speak method + * @param e exchange + */ + public final void speak(Exchange e) { + e.setOut(e.getIn()); + e.getOut().setBody("Hello World!"); + } +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/JaxrsEchoService.java b/src/main/java/org/onap/dmaap/JaxrsEchoService.java new file mode 100644 index 0000000..1bebaf8 --- /dev/null +++ b/src/main/java/org/onap/dmaap/JaxrsEchoService.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * ============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; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +import com.att.ajsc.beans.PropertiesMapBean; +import org.onap.dmaap.filemonitor.ServicePropertiesMap; + +/** + * Example JAX-RS Service + * @author rajashree.khare + * + */ +@Path("/jaxrs-services") +public class JaxrsEchoService { + + /** + * Logger obj + */ + /*private static final Logger LOGGER = Logger + .getLogger(JaxrsEchoService.class);*/ + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(JaxrsEchoService.class); + + /** + * Method ping + * @param input input + * @return str + */ + @GET + @Path("/echo/{input}") + @Produces("text/plain") + public String ping(@PathParam("input") String input) { + return "Hello, " + input + "."; + } + + /** + * Method to fetch property + * @param fileName file + * @param input input + * @return prop + */ + @GET + @Path("/property/{fileName}/{input:.*}") + @Produces("text/plain") + public String getProperty(@PathParam("fileName") String fileName, @PathParam("input") String input) { + String val=null; + try { + val = ServicePropertiesMap.getProperty(fileName, input); + if(val == null || val.isEmpty() || val.length() < 1){ + val = PropertiesMapBean.getProperty(fileName, input); + } + } + catch(Exception ex) { + LOGGER.info("*** Error retrieving property "+input+": "+ex); + + } + if (val ==null) { + return "Property is not available"; + } + return "Property value is, " + val +"."; + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/JaxrsUserService.java b/src/main/java/org/onap/dmaap/JaxrsUserService.java new file mode 100644 index 0000000..714a9c1 --- /dev/null +++ b/src/main/java/org/onap/dmaap/JaxrsUserService.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; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import java.util.Map; +import java.util.HashMap; + +/** + * Example JAX-RS User Service + * @author rajashree.khare + * + */ +@Path("/user") +public class JaxrsUserService { + + private static final Map userIdToNameMap; + static { + userIdToNameMap = new HashMap(); + userIdToNameMap.put("dw113c","Doug Wait"); + userIdToNameMap.put("so401q","Stuart O'Day"); + } + + /** + * Method to fetch user details + * @param userId user + * @return userDetails + */ + @GET + @Path("/{userId}") + @Produces("text/plain") + public String lookupUser(@PathParam("userId") String userId) { + String name = userIdToNameMap.get(userId); + return name != null ? name : "unknown id"; + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesListener.java b/src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesListener.java new file mode 100644 index 0000000..56cccca --- /dev/null +++ b/src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesListener.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * ============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.filemonitor; + +import java.io.File; + +//import com.att.ssf.filemonitor.FileChangedListener; +/** + * Class ServicePropertiesListener + * @author rajashree.khare + * + */ +public class ServicePropertiesListener/* implements FileChangedListener*/ { + + /** + * Update method + */ + //@Override + /*public void update(File file) throws Exception + { + ServicePropertiesMap.refresh(file); + }*/ +} diff --git a/src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesMap.java b/src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesMap.java new file mode 100644 index 0000000..27cf0a2 --- /dev/null +++ b/src/main/java/org/onap/dmaap/filemonitor/ServicePropertiesMap.java @@ -0,0 +1,120 @@ +/******************************************************************************* + * ============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.filemonitor; + +import java.util.HashMap; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * ServicePropertiesMap class + * @author rajashree.khare + * + */ +@SuppressWarnings("squid:S1118") +public class ServicePropertiesMap +{ + private static HashMap> mapOfMaps = + new HashMap>(); +// static final Logger logger = LoggerFactory.getLogger(ServicePropertiesMap.class); + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ServicePropertiesMap.class); + /** + * refresh method + * @param file file + * @throws Exception ex + */ + /*public static void refresh(File file) throws Exception + { + try + { + logger.info("Loading properties - " + (file != null?file.getName():"")); + + //Store .json & .properties files into map of maps + String filePath = file.getPath(); + + if(filePath.lastIndexOf(".json")>0){ + + ObjectMapper om = new ObjectMapper(); + TypeReference> typeRef = + new TypeReference>() {}; + HashMap propMap = om.readValue(file, typeRef); + HashMap lcasePropMap = new HashMap(); + for (String key : propMap.keySet() ) + { + String lcaseKey = ifNullThenEmpty(key); + lcasePropMap.put(lcaseKey, propMap.get(key)); + } + + mapOfMaps.put(file.getName(), lcasePropMap); + + + }else if(filePath.lastIndexOf(".properties")>0){ + Properties prop = new Properties(); + FileInputStream fis = new FileInputStream(file); + prop.load(fis); + + @SuppressWarnings("unchecked") + HashMap propMap = new HashMap((Map)prop); + + mapOfMaps.put(file.getName(), propMap); + } + + logger.info("File - " + file.getName() + " is loaded into the map and the " + + "corresponding system properties have been refreshed"); + } + catch (Exception e) + { + logger.error("File " + (file != null?file.getName():"") + " cannot be loaded into the map ", e); + throw new Exception("Error reading map file " + (file != null?file.getName():""), e); + } + }*/ + /** + * Get property + * @param fileName fileName + * @param propertyKey propertyKey + * @return str + */ + public static String getProperty(String fileName, String propertyKey) + { + HashMap propMap = mapOfMaps.get(fileName); + return propMap!=null?propMap.get(ifNullThenEmpty(propertyKey)):""; + } + /** + * get properties + * @param fileName fileName + * @return mapProp + */ + public static HashMap getProperties(String fileName){ + return mapOfMaps.get(fileName); + } + + private static String ifNullThenEmpty(String key) { + if (key == null) { + return ""; + } else { + return key; + } + } + +} diff --git a/src/main/java/org/onap/dmaap/filemonitor/ServicePropertyService.java b/src/main/java/org/onap/dmaap/filemonitor/ServicePropertyService.java new file mode 100644 index 0000000..fe25e58 --- /dev/null +++ b/src/main/java/org/onap/dmaap/filemonitor/ServicePropertyService.java @@ -0,0 +1,164 @@ +/******************************************************************************* + * ============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.filemonitor; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.annotation.PostConstruct; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +//import com.att.ssf.filemonitor.FileChangedListener; +//import com.att.ssf.filemonitor.FileMonitor; + +/** + * ServicePropertyService class + * @author rajashree.khare + * + */ +public class ServicePropertyService { + private boolean loadOnStartup; + private ServicePropertiesListener fileChangedListener; + private ServicePropertiesMap filePropertiesMap; + private String ssfFileMonitorPollingInterval; + private String ssfFileMonitorThreadpoolSize; + private List fileList; + private static final String FILE_CHANGE_LISTENER_LOC = System + .getProperty("AJSC_CONF_HOME") + "/etc"; + private static final String USER_CONFIG_FILE = "service-file-monitor.properties"; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ServicePropertyService.class); + + // do not remove the postConstruct annotation, init method will not be + // called after constructor + /** + * Init method + * @throws Exception ex + */ + @PostConstruct + public void init() { + + try { + getFileList(FILE_CHANGE_LISTENER_LOC); + + /*for (File file : fileList) { + FileChangedListener fileChangedListener = this.fileChangedListener; + Object filePropertiesMap = this.filePropertiesMap; + Method m = filePropertiesMap.getClass().getMethod( + "refresh", File.class); + m.invoke(filePropertiesMap, file); + FileMonitor fm = FileMonitor.getInstance(); + fm.addFileChangedListener(file, fileChangedListener, + loadOnStartup); + + }*/ + } catch (Exception ex) { + logger.error("Error creating property map ", ex); + } + + } + + private void getFileList(String dirName) throws IOException { + File directory = new File(dirName); + FileInputStream fis = null; + + if (fileList == null) + fileList = new ArrayList(); + + // get all the files that are ".json" or ".properties", from a directory + // & it's sub-directories + File[] fList = directory.listFiles(); + + for (File file : fList) { + // read service property files from the configuration file + if (file.isFile() && file.getPath().endsWith(USER_CONFIG_FILE)) { + try { + fis = new FileInputStream(file); + Properties prop = new Properties(); + prop.load(fis); + + for (String filePath : prop.stringPropertyNames()) { + fileList.add(new File(prop.getProperty(filePath))); + } + } catch (Exception ioe) { + logger.error("Error reading the file stream ", ioe); + } finally { + fis.close(); + } + } else if (file.isDirectory()) { + getFileList(file.getPath()); + } + } + + } + + public void setLoadOnStartup(boolean loadOnStartup) { + this.loadOnStartup = loadOnStartup; + } + + public void setSsfFileMonitorPollingInterval( + String ssfFileMonitorPollingInterval) { + this.ssfFileMonitorPollingInterval = ssfFileMonitorPollingInterval; + } + + public void setSsfFileMonitorThreadpoolSize( + String ssfFileMonitorThreadpoolSize) { + this.ssfFileMonitorThreadpoolSize = ssfFileMonitorThreadpoolSize; + } + + public boolean isLoadOnStartup() { + return loadOnStartup; + } + + public String getSsfFileMonitorPollingInterval() { + return ssfFileMonitorPollingInterval; + } + + public String getSsfFileMonitorThreadpoolSize() { + return ssfFileMonitorThreadpoolSize; + } + + public ServicePropertiesListener getFileChangedListener() { + return fileChangedListener; + } + + public void setFileChangedListener( + ServicePropertiesListener fileChangedListener) { + this.fileChangedListener = fileChangedListener; + } + + public ServicePropertiesMap getFilePropertiesMap() { + return filePropertiesMap; + } + + public void setFilePropertiesMap(ServicePropertiesMap filePropertiesMap) { + this.filePropertiesMap = filePropertiesMap; + } +} diff --git a/src/main/java/org/onap/dmaap/mmagent/CreateMirrorMaker.java b/src/main/java/org/onap/dmaap/mmagent/CreateMirrorMaker.java new file mode 100644 index 0000000..72df46f --- /dev/null +++ b/src/main/java/org/onap/dmaap/mmagent/CreateMirrorMaker.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.mmagent; + +import java.util.Date; + +import org.apache.http.HttpStatus; +import org.json.JSONObject; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.utils.Utils; + +public class CreateMirrorMaker { + String messageID; + MirrorMaker createMirrorMaker; + + public MirrorMaker getCreateMirrorMaker() { + return createMirrorMaker; + } + + public void setCreateMirrorMaker(MirrorMaker createMirrorMaker) throws CambriaApiException { + this.createMirrorMaker = createMirrorMaker; + } + + public String getMessageID() { + return messageID; + } + + public void setMessageID(String messageID) { + this.messageID = messageID; + } + public void validateJSON() throws CambriaApiException + { + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, + DMaaPResponseCode.INCORRECT_JSON.getResponseCode(), "", null, Utils.getFormattedDate(new Date()), null, null, null, + null, + ""); + if(null==this.createMirrorMaker.getConsumer()) + { + errRes.setErrorMessage("Please provide Consumer host:port details"); + throw new CambriaApiException(errRes); + } + if(null==this.createMirrorMaker.getProducer()) + { + errRes.setErrorMessage("Please provide Producer host:port details"); + throw new CambriaApiException(errRes); + } + if(this.createMirrorMaker.getNumStreams()<=0) + { + errRes.setErrorMessage("Please provide numStreams value"); + throw new CambriaApiException(errRes); + } + + } +} diff --git a/src/main/java/org/onap/dmaap/mmagent/MMAgentUtil.java b/src/main/java/org/onap/dmaap/mmagent/MMAgentUtil.java new file mode 100644 index 0000000..f2ddaed --- /dev/null +++ b/src/main/java/org/onap/dmaap/mmagent/MMAgentUtil.java @@ -0,0 +1,430 @@ +/** + * + */ +/******************************************************************************* + * ============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.mmagent; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Context; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpStatus; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import com.att.ajsc.filemonitor.AJSCPropertiesMap; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.constants.CambriaConstants; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; +import org.onap.dmaap.dmf.mr.service.MMService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; +import org.onap.dmaap.dmf.mr.utils.Utils; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * @author rajashree.khare + *Util class for MM Rest Service + */ +@Component +public class MMAgentUtil {/* + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + @Context + private HttpServletRequest request; + + @Context + private HttpServletResponse response; + + @Autowired + private MMService mirrorService; + + private String topic; + private int timeout; + private String consumergroup; + private String consumerid; + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMAgentUtil.class); + + public JSONObject callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream, String name, boolean listAll) throws Exception { + loadProperty(); + JSONObject jsonObj = new JSONObject(); + JSONObject finalJsonObj = new JSONObject(); + JSONArray jsonArray = null; + try { + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + mirrorService.pushEvents(ctx, topic, inStream, null, null); + long startTime = System.currentTimeMillis(); + + while (!isListMirrorMaker(msgFrmSubscribe, randomstr) + && ((System.currentTimeMillis() - startTime) < timeout)) { + msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + + } + + + if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 + && isListMirrorMaker(msgFrmSubscribe, randomstr)) { + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + + jsonArray = new JSONArray(msgFrmSubscribe); + jsonObj = jsonArray.getJSONObject(0); + if(jsonObj.has("listMirrorMaker")) + { + jsonArray = (JSONArray) jsonObj.get("listMirrorMaker"); + if(true==listAll) + { + return jsonObj; + } + else + { + for (int i = 0; i < jsonArray.length(); i++) + { + jsonObj = jsonArray.getJSONObject(i); + if(null!=name && !name.isEmpty()) + { + if(jsonObj.getString("name").equals(name)) + { + finalJsonObj.put("listMirrorMaker", jsonObj); + break; + } + } + else + { + finalJsonObj.put("listMirrorMaker", jsonObj); + } + + } + } + } + return finalJsonObj; + + } else { + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, + DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(), + "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + + } catch (Exception e) { + + throw e; + } + } + + public void sendErrResponse(DMaaPContext ctx, String errMsg) { + JSONObject err = new JSONObject(); + err.append("Error", errMsg); + + try { + DMaaPResponseBuilder.respondOk(ctx, err); + LOGGER.error(errMsg.toString()); + + } catch (JSONException | IOException e) { + LOGGER.error(errMsg.toString()); + } + } + public boolean isListMirrorMaker(String msg, String messageID) { + String topicmsg = msg; + topicmsg = removeExtraChar(topicmsg); + JSONObject jObj = new JSONObject(); + JSONArray jArray = null; + boolean exist = false; + + if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) { + jArray = new JSONArray(topicmsg); + + for (int i = 0; i < jArray.length(); i++) { + jObj = jArray.getJSONObject(i); + + + if (jObj.has("messageID") && jObj.get("messageID").equals(messageID) && jObj.has("listMirrorMaker")) { + exist = true; + break; + } + } + } + return exist; + } + + public void loadProperty() { + + this.timeout = Integer.parseInt( + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim()); + this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim(); + this.consumergroup = AJSCPropertiesMap + .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim(); + this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid") + .trim(); + + + } + + public String removeExtraChar(String message) { + String str = message; + str = checkJsonFormate(str); + + if (str != null && str.length() > 0) { + str = str.replace("\\", ""); + str = str.replace("\"{", "{"); + str = str.replace("}\"", "}"); + } + return str; + } + + public String getRandomNum() { + long random = Math.round(Math.random() * 89999) + 10000; + String strLong = Long.toString(random); + return strLong; + } + + public boolean isAlphaNumeric(String name) { + String pattern = "^[a-zA-Z0-9]*$"; + if (name.matches(pattern)) { + return true; + } + return false; + } + + // This method validate IPv4 + public boolean validateIPPort(String ipPort) { + String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):" + + "([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; + if (ipPort.matches(pattern)) { + return true; + } + return false; + } + + public String checkJsonFormate(String jsonStr) { + + String json = jsonStr; + if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) { + json = json + "]"; + } + return json; + } + + public boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) { + + boolean hasPermission = false; + + DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); + + if (aaf.aafAuthentication(ctx.getRequest(), permission)) { + hasPermission = true; + } + return hasPermission; + } + + public String getNamespace(String topic) { + return topic.substring(0, topic.lastIndexOf(".")); + } + + public String removeTopic(String whitelist, String topicToRemove) { + List topicList = new ArrayList(); + List newTopicList = new ArrayList(); + + if (whitelist.contains(",")) { + topicList = Arrays.asList(whitelist.split(",")); + + } + + if (topicList.contains(topicToRemove)) { + for (String topic : topicList) { + if (!topic.equals(topicToRemove)) { + newTopicList.add(topic); + } + } + } + + String newWhitelist = StringUtils.join(newTopicList, ","); + + return newWhitelist; + } + + public void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, JSONObject jsonOb) { + + loadProperty(); + try { + String namespace = jsonOb.getString("namespace"); + String mmName = jsonOb.getString("name"); + + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + mirrorService.pushEvents(ctx, topic, inStream, null, null); + long startTime = System.currentTimeMillis(); + + while (!isListMirrorMaker(msgFrmSubscribe, randomStr) + && (System.currentTimeMillis() - startTime) < timeout) { + msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + } + + JSONObject jsonObj = new JSONObject(); + JSONArray jsonArray = null; + JSONArray jsonArrayNamespace = null; + + if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 + && isListMirrorMaker(msgFrmSubscribe, randomStr)) { + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + jsonArray = new JSONArray(msgFrmSubscribe); + + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + + + if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) { + jsonArrayNamespace = jsonObj.getJSONArray("listMirrorMaker"); + } + } + JSONObject finalJasonObj = new JSONObject(); + JSONArray finalJsonArray = new JSONArray(); + + for (int i = 0; i < jsonArrayNamespace.length(); i++) { + + JSONObject mmObj = new JSONObject(); + mmObj = jsonArrayNamespace.getJSONObject(i); + if(mmObj.has("name")&& mmName.equals(mmObj.getString("name"))) + { + + finalJsonArray.put(mmObj); + } + + } + finalJasonObj.put("listMirrorMaker", finalJsonArray); + + DMaaPResponseBuilder.respondOk(ctx, finalJasonObj); + + } else { + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, + DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(), + "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public String getWhitelistByNamespace(String originalWhitelist, String namespace) { + + String whitelist = null; + List resultList = new ArrayList(); + List whitelistList = new ArrayList(); + whitelistList = Arrays.asList(originalWhitelist.split(",")); + + for (String topic : whitelistList) { + if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) { + resultList.add(topic); + } + } + if (resultList.size() > 0) { + whitelist = StringUtils.join(resultList, ","); + } + + return whitelist; + } + + public JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) { + JSONObject jsonObj = new JSONObject(); + JSONArray jsonArray = new JSONArray(); + JSONArray listMirrorMaker = new JSONArray(); + + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + jsonArray = new JSONArray(msgFrmSubscribe); + jsonObj = jsonArray.getJSONObject(0); + + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + + if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) { + listMirrorMaker = jsonObj.getJSONArray("listMirrorMaker"); + break; + } + } + return listMirrorMaker; + } + + public JSONObject validateMMExists(DMaaPContext ctx,String name) throws Exception + { + // Create a listAllMirrorMaker Json object + JSONObject listAll = new JSONObject(); + try { + listAll.put("listAllMirrorMaker", new JSONObject()); + + } catch (JSONException e) { + + e.printStackTrace(); + } + + // set a random number as messageID + String randomStr = getRandomNum(); + listAll.put("messageID", randomStr); + InputStream inStream = null; + + // convert listAll Json object to InputStream object + try { + inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8"); + + } catch (IOException ioe) { + ioe.printStackTrace(); + } + JSONObject listMirrorMaker =new JSONObject(); + listMirrorMaker = callPubSub(randomStr, ctx, inStream, name, false); + if (null!=listMirrorMaker && listMirrorMaker.length()>0){ + listMirrorMaker.put("exists", true); + return listMirrorMaker; + + } + listMirrorMaker.put("exists", false); + return listMirrorMaker; + + } +*/} diff --git a/src/main/java/org/onap/dmaap/mmagent/MirrorMaker.java b/src/main/java/org/onap/dmaap/mmagent/MirrorMaker.java new file mode 100644 index 0000000..480c40f --- /dev/null +++ b/src/main/java/org/onap/dmaap/mmagent/MirrorMaker.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.mmagent; + +public class MirrorMaker { + public String name; + public String consumer; + public String producer; + public String whitelist; + public String status; + private int numStreams =1; + private boolean enablelogCheck = false; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getConsumer() { + return consumer; + } + + public void setConsumer(String consumer) { + this.consumer = consumer; + } + + public String getProducer() { + return producer; + } + + public void setProducer(String producer) { + this.producer = producer; + } + + public String getWhitelist() { + return whitelist; + } + + public void setWhitelist(String whitelist) { + this.whitelist = whitelist; + } + + public int getNumStreams() { + return numStreams; + } + + public void setNumStreams(int numStreams) { + this.numStreams = numStreams; + } + + public boolean isEnablelogCheck() { + return enablelogCheck; + } + + public void setEnablelogCheck(boolean enablelogCheck) { + this.enablelogCheck = enablelogCheck; + } +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/mmagent/UpdateMirrorMaker.java b/src/main/java/org/onap/dmaap/mmagent/UpdateMirrorMaker.java new file mode 100644 index 0000000..1c2f32c --- /dev/null +++ b/src/main/java/org/onap/dmaap/mmagent/UpdateMirrorMaker.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * ============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.mmagent; + +import java.util.Date; + +import org.apache.http.HttpStatus; +import org.json.JSONObject; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.utils.Utils; + +public class UpdateMirrorMaker { + String messageID; + MirrorMaker updateMirrorMaker; + + public MirrorMaker getUpdateMirrorMaker() { + return updateMirrorMaker; + } + + public void setUpdateMirrorMaker(MirrorMaker updateMirrorMaker) { + this.updateMirrorMaker = updateMirrorMaker; + } + + public String getMessageID() { + return messageID; + } + + public void setMessageID(String messageID) { + this.messageID = messageID; + } + public void validateJSON(JSONObject jsonObj) throws CambriaApiException + { + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, + DMaaPResponseCode.INCORRECT_JSON.getResponseCode(), "", null, Utils.getFormattedDate(new Date()), null, null, null, + null, + ""); + + + if(jsonObj.has("consumer")&& null==this.updateMirrorMaker.getConsumer()) + { + errRes.setErrorMessage("Please provide Consumer host:port details"); + throw new CambriaApiException(errRes); + } + if(jsonObj.has("producer")&& null==this.updateMirrorMaker.getProducer()) + { + errRes.setErrorMessage("Please provide Producer host:port details"); + throw new CambriaApiException(errRes); + } + if(jsonObj.has("numStreams")&& this.updateMirrorMaker.getNumStreams()<=0) + { + errRes.setErrorMessage("Please provide numStreams value"); + throw new CambriaApiException(errRes); + } + if(jsonObj.has("whitelist")) + { + errRes.setErrorMessage("Please use Create Whitelist API to add whitelist topics"); + throw new CambriaApiException(errRes); + } + + } +} diff --git a/src/main/java/org/onap/dmaap/mmagent/UpdateWhiteList.java b/src/main/java/org/onap/dmaap/mmagent/UpdateWhiteList.java new file mode 100644 index 0000000..dc67298 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mmagent/UpdateWhiteList.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.mmagent; + +public class UpdateWhiteList { + + String messageID; + MirrorMaker updateWhiteList; + + public MirrorMaker getUpdateWhiteList() { + return updateWhiteList; + } + + public void setUpdateWhiteList(MirrorMaker updateWhiteList) { + this.updateWhiteList = updateWhiteList; + } + + public String getMessageID() { + return messageID; + } + + public void setMessageID(String messageID) { + this.messageID = messageID; + } +} diff --git a/src/main/java/org/onap/dmaap/service/AdminRestService.java b/src/main/java/org/onap/dmaap/service/AdminRestService.java new file mode 100644 index 0000000..61f6a08 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/AdminRestService.java @@ -0,0 +1,282 @@ +/******************************************************************************* + * ============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.service; + +import java.io.IOException; +import java.util.Enumeration; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.http.HttpStatus; +//import org.apache.log4j.Logger; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.json.JSONException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.service.AdminService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; + +/** + * Rest Service class + * for Admin Services + * @author Ramkumar + * + */ +@Component +@Path("/") +public class AdminRestService { + + /** + * Logger obj + */ + //private static final Logger LOGGER = Logger + // .getLogger(AdminRestService.class); + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AdminRestService.class); + /** + * Config Reader + */ + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest request; + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse response; + /** + * AdminService obj + */ + @Autowired + private AdminService adminService; + + /** + * Fetches a list of all the registered consumers along with their created + * time and last accessed details + * + * @return consumer list in json string format + * @throws CambriaApiException + * @throws AccessDeniedException + * @throws IOException + * */ + @GET + @Path("/consumerCache") + //@Produces(MediaType.TEXT_PLAIN) + public void getConsumerCache() throws CambriaApiException, AccessDeniedException { + LOGGER.info("Fetching list of registered consumers."); + try { + adminService.showConsumerCache(ServiceUtil.getDMaaPContext(configReader, request, response)); + LOGGER.info("Fetching Consumer Cache Successfully"); + } catch (IOException e) { + LOGGER.error("Error while Fetching list of registered consumers : " + + e.getMessage(), e); + + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GET_CONSUMER_CACHE.getResponseCode(), + "Error while Fetching list of registered consumers " + e.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + /** + * Clears consumer cache + * @throws CambriaApiException ex + * @throws AccessDeniedException + * + * @throws IOException ex + * @throws JSONException ex + * */ + @POST + @Path("/dropConsumerCache") + //@Produces(MediaType.TEXT_PLAIN) + public void dropConsumerCache() throws CambriaApiException, AccessDeniedException { + LOGGER.info("Dropping consumer cache"); + try { + adminService.dropConsumerCache(ServiceUtil.getDMaaPContext(configReader, request, response)); + LOGGER.info("Dropping Consumer Cache successfully"); + } catch ( AccessDeniedException excp) { + LOGGER.error("Error while dropConsumerCache : " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), + "Error while Fetching list of blacklist ips " + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } catch (JSONException | IOException e) { + LOGGER.error( + "Error while Dropping consumer cache : " + e.getMessage(), + e); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.DROP_CONSUMER_CACHE.getResponseCode(), + "Error while Dropping consumer cache " + e.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + /** + * Get list of blacklisted ips + * @throws CambriaApiException excp + */ + @GET + @Path("/blacklist") + //@Produces(MediaType.TEXT_PLAIN) + public void getBlacklist() throws CambriaApiException { + LOGGER.info("Fetching list of blacklist ips."); + try { + Enumeration headerNames =ServiceUtil.getDMaaPContext(configReader, request, response).getRequest().getHeaderNames(); + while (headerNames.hasMoreElements()) { + String key = (String) headerNames.nextElement(); + String value = request.getHeader(key); + + } + + adminService.getBlacklist(ServiceUtil.getDMaaPContext(configReader, request, response)); + LOGGER.info("Fetching list of blacklist ips Successfully"); + }catch ( AccessDeniedException excp) { + LOGGER.error("Error while Fetching list of blacklist ips : " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), + "Error while Fetching list of blacklist ips " + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } catch ( IOException excp) { + LOGGER.error("Error while Fetching list of blacklist ips : " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), + "Error while Fetching list of blacklist ips " + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + + } + + /** + * Add ip to list of blacklist ips + * @param ip ip + * @throws CambriaApiException excp + */ + @POST + @Path("/blacklist/{ip}") + //@Produces(MediaType.TEXT_PLAIN) + public void addToBlacklist (@PathParam("ip") String ip ) throws CambriaApiException + { + LOGGER.info("Adding ip to list of blacklist ips."); + try { + adminService.addToBlacklist(ServiceUtil.getDMaaPContext(configReader, request, response), ip); + LOGGER.info("Fetching list of blacklist ips Successfully"); + } catch ( AccessDeniedException excp) { + LOGGER.error("Error while blacklist : " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), + "Error while Fetching list of blacklist ips " + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } catch (IOException | ConfigDbException excp) { + LOGGER.error("Error while adding ip to list of blacklist ips : " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.ADD_BLACKLIST.getResponseCode(), + "Error while adding ip to list of blacklist ips " + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + + } + /** + * Remove ip from blacklist + * @param ip ip + * @throws CambriaApiException excp + * @throws AccessDeniedException excp + * @throws ConfigDbException excp + */ + @DELETE + @Path("/blacklist/{ip}") + //@Produces(MediaType.TEXT_PLAIN) + public void removeFromBlacklist(@PathParam("ip") String ip) throws CambriaApiException, AccessDeniedException, ConfigDbException { + LOGGER.info("Fetching list of blacklist ips."); + try { + adminService.removeFromBlacklist(ServiceUtil.getDMaaPContext(configReader, request, response), ip); + LOGGER.info("Fetching list of blacklist ips Successfully"); + }catch ( AccessDeniedException excp) { + LOGGER.error("Error while blacklist : " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.GET_BLACKLIST.getResponseCode(), + "Error while removeFromBlacklist list of blacklist ips " + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } catch (IOException | ConfigDbException excp) { + LOGGER.error("Error while removing ip from list of blacklist ips : " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.REMOVE_BLACKLIST.getResponseCode(), + "Error while removing ip from list of blacklist ips " + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + +} diff --git a/src/main/java/org/onap/dmaap/service/ApiKeysRestService.java b/src/main/java/org/onap/dmaap/service/ApiKeysRestService.java new file mode 100644 index 0000000..49eddd9 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/ApiKeysRestService.java @@ -0,0 +1,254 @@ +/******************************************************************************* + * ============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.service; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.json.JSONException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.ApiKeyBean; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.service.ApiKeysService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.db.NsaApiDb.KeyExistsException; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; + +/** + * This class is a CXF REST service + * which acts as gateway for Cambria Api + * Keys. + * @author rajashree.khare + * + */ +@Component +@Path("/") +public class ApiKeysRestService { + + /** + * Logger obj + */ + //private Logger log = Logger.getLogger(ApiKeysRestService.class.toString()); + private static final EELFLogger log = EELFManager.getInstance().getLogger(ApiKeysRestService.class); + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest request; + + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse response; + + /** + * Config Reader + */ + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + /** + * ApiKeysService obj + */ + @Autowired + private ApiKeysService apiKeyService; + + /** + * Returns a list of all the existing Api keys + * @throws CambriaApiException + * + * @throws IOException + * */ + @GET + public void getAllApiKeys() throws CambriaApiException { + + log.info("Inside ApiKeysRestService.getAllApiKeys"); + + try { + apiKeyService.getAllApiKeys(getDmaapContext()); + log.info("Fetching all API keys is Successful"); + } catch (ConfigDbException | IOException e) { + log.error("Error while retrieving API keys: " + e); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), + "Error while retrieving API keys: "+ e.getMessage()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + + } + + /** + * Returns details of a particular api key whose name is passed + * as a parameter + * + * @param apiKeyName + * - name of the api key + * @throws CambriaApiException + * @throws IOException + * */ + @GET + @Path("/{apiKey}") + public void getApiKey(@PathParam("apiKey") String apiKeyName) throws CambriaApiException { + log.info("Fetching details of api key: " + apiKeyName); + + try { + apiKeyService.getApiKey(getDmaapContext(), apiKeyName); + log.info("Fetching specific API key is Successful"); + } catch (ConfigDbException | IOException e) { + log.error("Error while retrieving API key details: " + e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), + "Error while retrieving API key details: "+ e.getMessage()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + + + /** + * Creates api key using the email and description + * + * @param nsaApiKey + * @throws CambriaApiException + * @throws JSONException + * */ + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + public void createApiKey(ApiKeyBean nsaApiKey) throws CambriaApiException, JSONException { + log.info("Creating Api Key."); + + try { + apiKeyService.createApiKey(getDmaapContext(), nsaApiKey); + log.info("Creating API key is Successful"); + } catch (KeyExistsException | ConfigDbException | IOException e) { + log.error("Error while Creating API key : " + e.getMessage(), e); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), + "Error while Creating API key : "+ e.getMessage()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + + } + + /** + * Updates an existing apiKey using the key name passed a parameter and the + * details passed. + * + * @param apiKeyName + * - name of the api key to be updated + * @param nsaApiKey + * @throws CambriaApiException + * @throws JSONException + * @throws IOException + * @throws AccessDeniedException + * */ + @PUT + @Path("/{apiKey}") + public void updateApiKey(@PathParam("apiKey") String apiKeyName, + ApiKeyBean nsaApiKey) throws CambriaApiException, JSONException { + log.info("Updating Api Key."); + + try { + + apiKeyService + .updateApiKey(getDmaapContext(), apiKeyName, nsaApiKey); + log.error("API key updated sucessfully"); + } catch (ConfigDbException | IOException | AccessDeniedException e) { + log.error("Error while Updating API key : " + apiKeyName, e); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), + "Error while Updating API key : "+ e.getMessage()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * Deletes an existing apiKey using the key name passed as a parameter. + * + * @param apiKeyName + * - name of the api key to be updated + * @throws CambriaApiException + * @throws IOException + * @throws AccessDeniedException + * */ + @DELETE + @Path("/{apiKey}") + public void deleteApiKey(@PathParam("apiKey") String apiKeyName) throws CambriaApiException { + log.info("Deleting Api Key: " + apiKeyName); + try { + apiKeyService.deleteApiKey(getDmaapContext(), apiKeyName); + log.info("Api Key deleted successfully: " + apiKeyName); + } catch (ConfigDbException | IOException | AccessDeniedException e) { + log.error("Error while deleting API key : " + apiKeyName, e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GENERIC_INTERNAL_ERROR.getResponseCode(), + "Error while deleting API key : "+ e.getMessage()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * Create a dmaap context + * @return DMaaPContext + */ + private DMaaPContext getDmaapContext() { + DMaaPContext dmaapContext = new DMaaPContext(); + dmaapContext.setConfigReader(configReader); + dmaapContext.setRequest(request); + dmaapContext.setResponse(response); + return dmaapContext; + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/service/EventsRestService.java b/src/main/java/org/onap/dmaap/service/EventsRestService.java new file mode 100644 index 0000000..2672261 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/EventsRestService.java @@ -0,0 +1,378 @@ +/******************************************************************************* + * ============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.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; + +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; +import org.onap.dmaap.dmf.mr.service.EventsService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import org.onap.dmaap.dmf.mr.utils.Utils; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; +import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; +/** + * This class is a CXF REST service which acts + * as gateway for MR Event Service. + * @author rajashree.khare + * + */ +@Component +@Path("/") +public class EventsRestService { + + /** + * Logger obj + */ + //private Logger log = Logger.getLogger(EventsRestService.class.toString()); + private static final EELFLogger log = EELFManager.getInstance().getLogger(EventsRestService.class); + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest request; + + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse response; + + + /** + * Config Reader + */ + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + @Autowired + private EventsService eventsService; + + @Autowired + private DMaaPErrorMessages errorMessages; + + /** + * This method is used to consume messages.Taking three parameter + * topic,consumerGroup and consumerId .Consumer decide to which topic they + * want to consume messages.In on consumer Group there might be many + * consumer may be present. + * + * @param topic + * specify- the topic name + * @param consumergroup + * - specify the consumer group + * @param consumerid + * -specify the consumer id + * + * handles CambriaApiException | ConfigDbException | + * TopicExistsException | AccessDeniedException | + * UnavailableException | IOException in try catch block + * @throws CambriaApiException + * + */ + @GET + @Path("/{topic}/{consumergroup}/{consumerid}") + public void getEvents(@PathParam("topic") String topic, @PathParam("consumergroup") + String consumergroup, + @PathParam("consumerid") String consumerid) throws CambriaApiException { + // log.info("Consuming message from topic " + topic ); + DMaaPContext dMaaPContext = getDmaapContext(); + dMaaPContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); + + try { + + eventsService.getEvents(dMaaPContext, topic, consumergroup, consumerid); + } + catch (TopicExistsException e) { + log.error("Error while reading data from topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, + DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), errorMessages.getConsumeMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, null, null, + consumerid, + request.getRemoteHost()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + catch (DMaaPAccessDeniedException | AccessDeniedException e) { + log.error("Error while reading data from topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), errorMessages.getConsumeMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, null, null, + consumerid, + request.getRemoteHost()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + + catch (ConfigDbException | UnavailableException | IOException e) { + log.error("Error while reading data from topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), errorMessages.getConsumeMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, null, null, + consumerid, + request.getRemoteHost()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + + /** + * This method is used to throw an exception back to the client app if CG/CID is not passed + * while consuming messages + */ + @GET + @Path("/{topic}") + public void getEventsToException(@PathParam("topic") String topic) throws CambriaApiException { + // log.info("Consuming message from topic " + topic ); + DMaaPContext dMaaPContext = getDmaapContext(); + dMaaPContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); + + try { + + throw new TopicExistsException("Incorrect URL"); + } + catch (TopicExistsException e) { + log.error("Error while reading data from topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), "Incorrect url - Expects consumer Group and ID in " + request.getRequestURI() + " from "+request.getRemoteHost() + ); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + + } + + /** + * This method is used to throw an exception back to the client app if CG/CID is not passed + * while consuming messages + */ + @GET + @Path("/{topic}/{consumergroup}") + public void getEventsToException(@PathParam("topic") String topic, @PathParam("consumergroup") + String consumergroup + ) throws CambriaApiException { + // log.info("Consuming message from topic " + topic ); + DMaaPContext dMaaPContext = getDmaapContext(); + dMaaPContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); + + try { + + throw new TopicExistsException("Incorrect URL"); + } + catch (TopicExistsException e) { + log.error("Error while reading data from topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.CONSUME_MSG_ERROR.getResponseCode(), "Incorrect url - Expects consumer ID in " + request.getRequestURI() + " from "+request.getRemoteHost() + ); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + + } + + + + + + + + /** + * This method is used to publish messages.Taking two parameter topic and + * partition.Publisher decide to which topic they want to publish message + * and kafka decide to which partition of topic message will send, + * + * @param topic + * @param msg + * @param partitionKey + * + * handles CambriaApiException | ConfigDbException | + * TopicExistsException | AccessDeniedException | IOException in + * try catch block + * @throws CambriaApiException + */ + + @POST + @Produces("application/json") + @Path("/{topic}") + public void pushEvents(@PathParam("topic") String topic, InputStream msg, + @QueryParam("partitionKey") String partitionKey) throws CambriaApiException { + log.info("Publishing message to topic " + topic); + + try { + eventsService.pushEvents(getDmaapContext(), topic, msg, partitionKey, null); + } + catch ( TopicExistsException e) { + log.error("Error while publishing to topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, + DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, + Utils.getUserApiKey(request), request.getRemoteHost(), null, null); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + catch ( DMaaPAccessDeniedException | AccessDeniedException e) { + log.error("Error while publishing to topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, + Utils.getUserApiKey(request), request.getRemoteHost(), null, null); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + + + catch (ConfigDbException | IOException | missingReqdSetting e) { + log.error("Error while publishing to topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, + Utils.getUserApiKey(request), request.getRemoteHost(), null, null); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + /** + * This method is used to publish messages by passing an optional header + * called 'transactionId'. If the 'transactionId' is not provided in the + * input then a new transaction object will be created. Else the existing + * transaction object will be updated with the counter details. + * + * @param topic + * @param partitionKey + * + * handles CambriaApiException | ConfigDbException | + * TopicExistsException | AccessDeniedException | IOException in + * try catch block + * @throws CambriaApiException + */ + @POST + @Produces("application/json") + @Path("/transaction/{topic}") + public void pushEventsWithTransaction(@PathParam("topic") String topic, + @QueryParam("partitionKey") String partitionKey) throws CambriaApiException { + // log.info("Publishing message with transaction id for topic " + topic + // ); + + try { + eventsService.pushEvents(getDmaapContext(), topic, request.getInputStream(), + partitionKey, + Utils.getFormattedDate(new Date())); + } + + catch ( TopicExistsException e) { + log.error("Error while publishing to topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, + DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, + Utils.getUserApiKey(request), request.getRemoteHost(), null, null); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + catch ( DMaaPAccessDeniedException| AccessDeniedException e) { + log.error("Error while publishing to topic [" + topic + "].", e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), errorMessages.getPublishMsgError() + + e.getMessage(), null, Utils.getFormattedDate(new Date()), topic, + Utils.getUserApiKey(request), request.getRemoteHost(), null, null); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + + catch (ConfigDbException | IOException | missingReqdSetting e) { + log.error("Error while publishing to topic : " + topic, e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.PUBLISH_MSG_ERROR.getResponseCode(), "Transaction-" + + errorMessages.getPublishMsgError() + e.getMessage(), null, + Utils.getFormattedDate(new Date()), topic, Utils.getUserApiKey(request), + request.getRemoteHost(), + null, null); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * This method is used for taking Configuration Object,HttpServletRequest + * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession + * Object. + * + * @return DMaaPContext object from where user can get Configuration + * Object,HttpServlet Object + * + */ + private DMaaPContext getDmaapContext() { + + DMaaPContext dmaapContext = new DMaaPContext(); + dmaapContext.setRequest(request); + dmaapContext.setResponse(response); + dmaapContext.setConfigReader(configReader); + + return dmaapContext; + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/service/MMRestService.java b/src/main/java/org/onap/dmaap/service/MMRestService.java new file mode 100644 index 0000000..fc3c9a1 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/MMRestService.java @@ -0,0 +1,1259 @@ +/******************************************************************************* + * ============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.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import org.json.JSONObject; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; +import org.onap.dmaap.dmf.mr.utils.Utils; +import com.att.nsa.configs.ConfigDbException; +import org.onap.dmaap.mmagent.*; +import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; + +import edu.emory.mathcs.backport.java.util.Arrays; + +import com.att.ajsc.filemonitor.AJSCPropertiesMap; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException; + +import org.json.JSONArray; +import org.json.JSONException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.constants.CambriaConstants; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; +import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticatorImpl; +import org.onap.dmaap.dmf.mr.service.MMService; + +/** + * Rest Service class for Mirror Maker proxy Rest Services + * + * @author + * + * @since May 25, 2016 + */ + +@Component +public class MMRestService { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMRestService.class); + private static final String NO_ADMIN_PERMISSION = "No Mirror Maker Admin permission."; + private static final String NO_USER_PERMISSION = "No Mirror Maker User permission."; + private static final String NO_USER_CREATE_PERMISSION = "No Mirror Maker User Create permission."; + private static final String NAME_DOES_NOT_MEET_REQUIREMENT = "Mirror Maker name can only contain alpha numeric"; + private static final String INVALID_IPPORT = "This is not a valid IP:Port"; + private static final String MIRROR_MAKERADMIN = "msgRtr.mirrormakeradmin.aaf"; + private static final String MIRROR_MAKERUSER = "msgRtr.mirrormakeruser.aaf"; + private static final String UTF_8 = "UTF-8"; + private static final String MESSAGE = "message"; + private static final String LISTMIRRORMAKER = "listMirrorMaker"; + private static final String ERROR = "error"; + private static final String NAMESPACE = "namespace"; + + private String topic; + private int timeout; + private String consumergroup; + private String consumerid; + + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + @Context + private HttpServletRequest request; + + @Context + private HttpServletResponse response; + + @Autowired + private MMService mirrorService; + + @Autowired + private DMaaPErrorMessages errorMessages; + + private DMaaPAAFAuthenticator dmaapAAFauthenticator = new DMaaPAAFAuthenticatorImpl(); + + /** + * This method is used for taking Configuration Object,HttpServletRequest + * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession + * Object. + * + * @return DMaaPContext object from where user can get Configuration + * Object,HttpServlet Object + * + */ + private DMaaPContext getDmaapContext() { + DMaaPContext dmaapContext = new DMaaPContext(); + dmaapContext.setRequest(request); + dmaapContext.setResponse(response); + dmaapContext.setConfigReader(configReader); + dmaapContext.setConsumerRequestTime(Utils.getFormattedDate(new Date())); + + return dmaapContext; + } + + @POST + @Produces("application/json") + @Path("/create") + public void callCreateMirrorMaker(InputStream msg) { + + DMaaPContext ctx = getDmaapContext(); + if (checkMirrorMakerPermission(ctx, + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + + loadProperty(); + String input = null; + String randomStr = getRandomNum(); + + InputStream inStream = null; + Gson gson = new Gson(); + CreateMirrorMaker createMirrorMaker = new CreateMirrorMaker(); + + try { + input = IOUtils.toString(msg, UTF_8); + + if (input != null && input.length() > 0) { + input = removeExtraChar(input); + } + + // Check if the request has CreateMirrorMaker + try { + createMirrorMaker = gson.fromJson(input, CreateMirrorMaker.class); + + } catch (JsonSyntaxException ex) { + + sendErrResponse(ctx, errorMessages.getIncorrectJson()); + LOGGER.error("JsonSyntaxException: ", ex); + } + String name = createMirrorMaker.getCreateMirrorMaker()==null? "":createMirrorMaker.getCreateMirrorMaker().getName(); + // send error message if it is not a CreateMirrorMaker request. + if (createMirrorMaker.getCreateMirrorMaker() == null) { + sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again."); + } + + // MirrorMaker whitelist and status should not be passed + else if (createMirrorMaker.getCreateMirrorMaker().getWhitelist() != null + || createMirrorMaker.getCreateMirrorMaker().getStatus() != null) { + sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again."); + } + + // if empty, blank name is entered + else if (StringUtils.isBlank(name)) { + sendErrResponse(ctx, "Name can not be empty or blank."); + } + + // Check if the name contains only Alpha Numeric + else if (!isAlphaNumeric(name)) { + sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT); + + } + + // Validate the IP and Port + else if (!StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getConsumer()) + && !StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getProducer()) + && !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer()) + || !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) { + sendErrResponse(ctx, INVALID_IPPORT); + + } + // Set a random number as messageID, convert Json Object to + // InputStream and finally call publisher and subscriber + else if (isAlphaNumeric(name) && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer()) + && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) { + + createMirrorMaker.setMessageID(randomStr); + inStream = IOUtils.toInputStream(gson.toJson(createMirrorMaker), UTF_8); + callPubSub(randomStr, ctx, inStream); + } + + } catch (IOException e) { + + LOGGER.error("IOException: ", e); + } + } + // Send error response if user does not provide Authorization + else { + sendErrResponse(ctx, NO_ADMIN_PERMISSION); + } + } + + @POST + @Produces("application/json") + @Path("/listall") + public void callListAllMirrorMaker(InputStream msg) { + DMaaPContext ctx = getDmaapContext(); + + if (checkMirrorMakerPermission(ctx, + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + + loadProperty(); + + String input = null; + + try { + input = IOUtils.toString(msg, UTF_8); + + if (input != null && input.length() > 0) { + input = removeExtraChar(input); + } + + String randomStr = getRandomNum(); + JSONObject jsonOb = null; + + try { + jsonOb = new JSONObject(input); + + } catch (JSONException ex) { + + sendErrResponse(ctx, errorMessages.getIncorrectJson()); + LOGGER.error("JSONException: ", ex); + } + + // Check if request has listAllMirrorMaker and + // listAllMirrorMaker is empty + if ((jsonOb != null) && (jsonOb.has("listAllMirrorMaker") + && jsonOb.getJSONObject("listAllMirrorMaker").length() == 0)) { + jsonOb.put("messageID", randomStr); + InputStream inStream = null; + + try { + inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8); + + } catch (IOException ioe) { + LOGGER.error("IOException: ", ioe); + } + + callPubSub(randomStr, ctx, inStream); + + } else { + + sendErrResponse(ctx, "This is not a ListAllMirrorMaker request. Please try again."); + } + + } catch (IOException ioe) { + + LOGGER.error("IOException: ", ioe); + } + + } else { + + sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION); + } + } + + @POST + @Produces("application/json") + @Path("/update") + public void callUpdateMirrorMaker(InputStream msg) { + + DMaaPContext ctx = getDmaapContext(); + if (checkMirrorMakerPermission(ctx, + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + + loadProperty(); + String input = null; + String randomStr = getRandomNum(); + + InputStream inStream = null; + Gson gson = new Gson(); + UpdateMirrorMaker updateMirrorMaker = new UpdateMirrorMaker(); + + try { + input = IOUtils.toString(msg, UTF_8); + + if (input != null && input.length() > 0) { + input = removeExtraChar(input); + } + + // Check if the request has UpdateMirrorMaker + try { + updateMirrorMaker = gson.fromJson(input, UpdateMirrorMaker.class); + + } catch (JsonSyntaxException ex) { + + sendErrResponse(ctx, errorMessages.getIncorrectJson()); + LOGGER.error("JsonSyntaxException: ", ex); + + } + String name = updateMirrorMaker.getUpdateMirrorMaker()==null? "":updateMirrorMaker.getUpdateMirrorMaker().getName(); + // send error message if it is not a UpdateMirrorMaker request. + if (updateMirrorMaker.getUpdateMirrorMaker() == null) { + sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again."); + } + + // MirrorMaker whitelist and status should not be passed + else if (updateMirrorMaker.getUpdateMirrorMaker().getWhitelist() != null + || updateMirrorMaker.getUpdateMirrorMaker().getStatus() != null) { + sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again."); + } + + // if empty, blank name is entered + else if (StringUtils.isBlank(name)) { + sendErrResponse(ctx, "Name can not be empty or blank."); + } + + // Check if the name contains only Alpha Numeric + else if (!isAlphaNumeric(name)) { + sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT); + + } + + // Validate the IP and Port + else if (!StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) + && !StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getProducer()) + && !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) + || !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) { + sendErrResponse(ctx, INVALID_IPPORT); + + } + // Set a random number as messageID, convert Json Object to + // InputStream and finally call publisher and subscriber + else if (isAlphaNumeric(name) && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) + && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) { + + updateMirrorMaker.setMessageID(randomStr); + inStream = IOUtils.toInputStream(gson.toJson(updateMirrorMaker), UTF_8); + callPubSub(randomStr, ctx, inStream); + } + + } catch (IOException e) { + + LOGGER.error("IOException: ", e); + } + } + // Send error response if user does not provide Authorization + else { + sendErrResponse(ctx, NO_ADMIN_PERMISSION); + } + } + + @POST + @Produces("application/json") + @Path("/delete") + public void callDeleteMirrorMaker(InputStream msg) { + DMaaPContext ctx = getDmaapContext(); + + if (checkMirrorMakerPermission(ctx, + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + + loadProperty(); + + String input = null; + + try { + input = IOUtils.toString(msg, UTF_8); + + if (input != null && input.length() > 0) { + input = removeExtraChar(input); + } + + String randomStr = getRandomNum(); + JSONObject jsonOb = null; + + try { + jsonOb = new JSONObject(input); + + } catch (JSONException ex) { + + sendErrResponse(ctx, errorMessages.getIncorrectJson()); + LOGGER.error("JSONException: ", ex); + } + + // Check if request has DeleteMirrorMaker and + // DeleteMirrorMaker has MirrorMaker object with name variable + // and check if the name contain only alpha numeric + if ((jsonOb != null) + && (jsonOb.has("deleteMirrorMaker") && jsonOb.getJSONObject("deleteMirrorMaker").length() == 1 + && jsonOb.getJSONObject("deleteMirrorMaker").has("name") + && !StringUtils.isBlank(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")) + && isAlphaNumeric(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")))) { + + jsonOb.put("messageID", randomStr); + InputStream inStream = null; + + try { + inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8); + + } catch (IOException ioe) { + LOGGER.error("IOException: ", ioe); + } + + callPubSub(randomStr, ctx, inStream); + + } else { + + sendErrResponse(ctx, "This is not a DeleteMirrorMaker request. Please try again."); + } + + } catch (IOException ioe) { + LOGGER.error("IOException: ", ioe); + } + + } else { + + sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION); + } + } + + private boolean isListMirrorMaker(String msg, String messageID) { + String topicmsg = msg; + topicmsg = removeExtraChar(topicmsg); + + JSONObject jObj; + JSONArray jArray; + boolean exist = false; + + if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) { + jArray = new JSONArray(topicmsg); + + for (int i = 0; i < jArray.length(); i++) { + jObj = jArray.getJSONObject(i); + + JSONObject obj = new JSONObject(); + if (jObj.has(MESSAGE)) { + obj = jObj.getJSONObject(MESSAGE); + } + if (obj.has("messageID") && obj.get("messageID").equals(messageID) && obj.has(LISTMIRRORMAKER)) { + exist = true; + break; + } + } + } + return exist; + } + + private void loadProperty() { + + this.timeout = Integer.parseInt( + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim()); + this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim(); + this.consumergroup = AJSCPropertiesMap + .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim(); + this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid") + .trim(); + } + + private String removeExtraChar(String message) { + String str = message; + str = checkJsonFormate(str); + + if (str != null && str.length() > 0) { + str = str.replace("\\", ""); + str = str.replace("\"{", "{"); + str = str.replace("}\"", "}"); + } + return str; + } + + private String getRandomNum() { + long random = Math.round(Math.random() * 89999) + 10000; + String strLong = Long.toString(random); + return strLong; + } + + private boolean isAlphaNumeric(String name) { + String pattern = "^[a-zA-Z0-9]*$"; + if (name.matches(pattern)) { + return true; + } + return false; + } + + // This method validate IPv4 + private boolean validateIPPort(String ipPort) { + String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):" + + "([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; + if (ipPort.matches(pattern)) { + return true; + } + return false; + } + + private String checkJsonFormate(String jsonStr) { + + String json = jsonStr; + if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) { + json = json + "]"; + } + return json; + } + + private boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) { + + boolean hasPermission = false; + + if (dmaapAAFauthenticator.aafAuthentication(ctx.getRequest(), permission)) { + hasPermission = true; + } + return hasPermission; + } + + private void callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream) { + try { + mirrorService.pushEvents(ctx, topic, inStream, null, null); + long startTime = System.currentTimeMillis(); + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + + while (!isListMirrorMaker(msgFrmSubscribe, randomstr) + && (System.currentTimeMillis() - startTime) < timeout) { + msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + } + + JSONObject jsonObj; + JSONObject finalJsonObj = new JSONObject(); + JSONArray jsonArray; + + if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 + && isListMirrorMaker(msgFrmSubscribe, randomstr)) { + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + jsonArray = new JSONArray(msgFrmSubscribe); + + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + + JSONObject obj = new JSONObject(); + if (jsonObj.has(MESSAGE)) { + obj = jsonObj.getJSONObject(MESSAGE); + } + if (obj.has("messageID") && obj.get("messageID").equals(randomstr) && obj.has(LISTMIRRORMAKER)) { + finalJsonObj.put(LISTMIRRORMAKER, obj.get(LISTMIRRORMAKER)); + break; + } + } + + DMaaPResponseBuilder.respondOk(ctx, finalJsonObj); + + } else { + + JSONObject err = new JSONObject(); + err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running"); + DMaaPResponseBuilder.respondOk(ctx, err); + } + + } catch (Exception e) { + LOGGER.error("Exception: ", e); + } + } + + private void sendErrResponse(DMaaPContext ctx, String errMsg) { + JSONObject err = new JSONObject(); + err.append(ERROR, errMsg); + + try { + DMaaPResponseBuilder.respondOk(ctx, err); + LOGGER.error(errMsg); + + } catch (JSONException | IOException e) { + LOGGER.error("Error at sendErrResponse method:" + errMsg + "Exception name:" + e); + } + } + + @SuppressWarnings("unchecked") + @POST + @Produces("application/json") + @Path("/listallwhitelist") + public void listWhiteList(InputStream msg) { + + DMaaPContext ctx = getDmaapContext(); + if (checkMirrorMakerPermission(ctx, + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { + + loadProperty(); + String input = null; + + try { + input = IOUtils.toString(msg, UTF_8); + + if (input != null && input.length() > 0) { + input = removeExtraChar(input); + } + + // Check if it is correct Json object + JSONObject jsonOb = null; + + try { + jsonOb = new JSONObject(input); + + } catch (JSONException ex) { + + sendErrResponse(ctx, errorMessages.getIncorrectJson()); + LOGGER.error("JSONException: ", ex); + } + + // Check if the request has name and name contains only alpha + // numeric + // and check if the request has namespace and namespace contains + // only alpha numeric + if (jsonOb != null && jsonOb.length() == 2 && jsonOb.has("name") + && !StringUtils.isBlank(jsonOb.getString("name")) && isAlphaNumeric(jsonOb.getString("name")) + && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE))) { + + String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, + "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; + + // Check if the user have create permission for the + // namespace + if (checkMirrorMakerPermission(ctx, permission)) { + + JSONObject listAll = new JSONObject(); + JSONObject emptyObject = new JSONObject(); + + // Create a listAllMirrorMaker Json object + try { + listAll.put("listAllMirrorMaker", emptyObject); + + } catch (JSONException e) { + + LOGGER.error("JSONException: ", e); + } + + // set a random number as messageID + String randomStr = getRandomNum(); + listAll.put("messageID", randomStr); + InputStream inStream = null; + + // convert listAll Json object to InputStream object + try { + inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); + + } catch (IOException ioe) { + LOGGER.error("IOException: ", ioe); + } + // call listAllMirrorMaker + mirrorService.pushEvents(ctx, topic, inStream, null, null); + + // subscribe for listMirrorMaker + long startTime = System.currentTimeMillis(); + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + + while (!isListMirrorMaker(msgFrmSubscribe, randomStr) + && (System.currentTimeMillis() - startTime) < timeout) { + msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + } + + if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 + && isListMirrorMaker(msgFrmSubscribe, randomStr)) { + + JSONArray listMirrorMaker; + listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr); + + String whitelist = null; + for (int i = 0; i < listMirrorMaker.length(); i++) { + + JSONObject mm; + mm = listMirrorMaker.getJSONObject(i); + String name = mm.getString("name"); + + if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { + whitelist = mm.getString("whitelist"); + break; + } + } + + if (!StringUtils.isBlank(whitelist)) { + + List topicList = new ArrayList<>(); + List finalTopicList = new ArrayList<>(); + topicList = Arrays.asList(whitelist.split(",")); + + for (String topic : topicList) { + if (topic != null && !topic.equals("null") + && getNamespace(topic).equals(jsonOb.getString(NAMESPACE))) { + + finalTopicList.add(topic); + } + } + + String topicNames = ""; + + if (!finalTopicList.isEmpty()) { + topicNames = StringUtils.join(finalTopicList, ","); + } + + JSONObject listAllWhiteList = new JSONObject(); + listAllWhiteList.put("name", jsonOb.getString("name")); + listAllWhiteList.put("whitelist", topicNames); + + DMaaPResponseBuilder.respondOk(ctx, listAllWhiteList); + } + + } else { + + JSONObject err = new JSONObject(); + err.append(ERROR, + "listWhiteList is not available, please make sure MirrorMakerAgent is running"); + DMaaPResponseBuilder.respondOk(ctx, err); + } + + } else { + sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); + } + + } else { + + sendErrResponse(ctx, "This is not a ListAllWhitelist request. Please try again."); + } + + } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException + | TopicExistsException | missingReqdSetting | UnavailableException e) { + + LOGGER.error("IOException: ", e); + } + } else { + sendErrResponse(ctx, NO_USER_PERMISSION); + } + } + + @SuppressWarnings("unchecked") + @POST + @Produces("application/json") + @Path("/createwhitelist") + public void createWhiteList(InputStream msg) { + + DMaaPContext ctx = getDmaapContext(); + if (checkMirrorMakerPermission(ctx, + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { + + loadProperty(); + String input = null; + + try { + input = IOUtils.toString(msg, UTF_8); + + if (input != null && input.length() > 0) { + input = removeExtraChar(input); + } + + // Check if it is correct Json object + JSONObject jsonOb = null; + + try { + jsonOb = new JSONObject(input); + + } catch (JSONException ex) { + + sendErrResponse(ctx, errorMessages.getIncorrectJson()); + LOGGER.error("JSONException: ", ex); + } + + // Check if the request has name and name contains only alpha + // numeric, + // check if the request has namespace and + // check if the request has whitelistTopicName + // check if the topic name contains only alpha numeric + if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") + && !StringUtils.isBlank(jsonOb.getString("name")) && isAlphaNumeric(jsonOb.getString("name")) + && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE)) + && jsonOb.has("whitelistTopicName") + && !StringUtils.isBlank(jsonOb.getString("whitelistTopicName")) + && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring( + jsonOb.getString("whitelistTopicName").lastIndexOf(".") + 1, + jsonOb.getString("whitelistTopicName").length()))) { + + String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, + "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; + + // Check if the user have create permission for the + // namespace + if (checkMirrorMakerPermission(ctx, permission)) { + + JSONObject listAll = new JSONObject(); + JSONObject emptyObject = new JSONObject(); + + // Create a listAllMirrorMaker Json object + try { + listAll.put("listAllMirrorMaker", emptyObject); + + } catch (JSONException e) { + + LOGGER.error("JSONException: ", e); + } + + // set a random number as messageID + String randomStr = getRandomNum(); + listAll.put("messageID", randomStr); + InputStream inStream = null; + + // convert listAll Json object to InputStream object + try { + inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); + + } catch (IOException ioe) { + LOGGER.error("IOException: ", ioe); + } + // call listAllMirrorMaker + mirrorService.pushEvents(ctx, topic, inStream, null, null); + + // subscribe for listMirrorMaker + long startTime = System.currentTimeMillis(); + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + + while (!isListMirrorMaker(msgFrmSubscribe, randomStr) + && (System.currentTimeMillis() - startTime) < timeout) { + msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + } + + JSONArray listMirrorMaker; + + if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 + && isListMirrorMaker(msgFrmSubscribe, randomStr)) { + + listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr); + String whitelist = null; + + for (int i = 0; i < listMirrorMaker.length(); i++) { + JSONObject mm; + mm = listMirrorMaker.getJSONObject(i); + String name = mm.getString("name"); + + if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { + whitelist = mm.getString("whitelist"); + break; + } + } + + List topicList = new ArrayList<>(); + List finalTopicList = new ArrayList<>(); + + if (whitelist != null) { + topicList = Arrays.asList(whitelist.split(",")); + } + + for (String st : topicList) { + if (!StringUtils.isBlank(st)) { + finalTopicList.add(st); + } + } + + String newTopic = jsonOb.getString("whitelistTopicName"); + + if (!topicList.contains(newTopic) + && getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) { + + UpdateWhiteList updateWhiteList = new UpdateWhiteList(); + MirrorMaker mirrorMaker = new MirrorMaker(); + mirrorMaker.setName(jsonOb.getString("name")); + finalTopicList.add(newTopic); + String newWhitelist = ""; + + if (!finalTopicList.isEmpty()) { + newWhitelist = StringUtils.join(finalTopicList, ","); + } + + mirrorMaker.setWhitelist(newWhitelist); + + String newRandom = getRandomNum(); + updateWhiteList.setMessageID(newRandom); + updateWhiteList.setUpdateWhiteList(mirrorMaker); + + Gson g = new Gson(); + g.toJson(updateWhiteList); + InputStream inputStream; + inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8); + // callPubSub(newRandom, ctx, inputStream); + callPubSubForWhitelist(newRandom, ctx, inputStream, jsonOb.getString(NAMESPACE)); + + } else if (topicList.contains(newTopic)) { + sendErrResponse(ctx, "The topic already exist."); + + } else if (!getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) { + sendErrResponse(ctx, + "The namespace of the topic does not match with the namespace you provided."); + } + } else { + + JSONObject err = new JSONObject(); + err.append(ERROR, + "listWhiteList is not available, please make sure MirrorMakerAgent is running"); + DMaaPResponseBuilder.respondOk(ctx, err); + } + + } else { + sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); + } + + } else { + + sendErrResponse(ctx, "This is not a createWhitelist request. Please try again."); + } + + } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException + | TopicExistsException | missingReqdSetting | UnavailableException e) { + + LOGGER.error("IOException: ", e); + } + } + // Send error response if user does not provide Authorization + else { + sendErrResponse(ctx, NO_USER_PERMISSION); + } + } + + @SuppressWarnings("unchecked") + @POST + @Produces("application/json") + @Path("/deletewhitelist") + public void deleteWhiteList(InputStream msg) { + + DMaaPContext ctx = getDmaapContext(); + if (checkMirrorMakerPermission(ctx, + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { + + loadProperty(); + String input = null; + + try { + input = IOUtils.toString(msg, UTF_8); + + if (input != null && input.length() > 0) { + input = removeExtraChar(input); + } + + // Check if it is correct Json object + JSONObject jsonOb = null; + + try { + jsonOb = new JSONObject(input); + + } catch (JSONException ex) { + + sendErrResponse(ctx, errorMessages.getIncorrectJson()); + LOGGER.error("JSONException: ", ex); + } + + // Check if the request has name and name contains only alpha + // numeric, + // check if the request has namespace and + // check if the request has whitelistTopicName + if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") + && isAlphaNumeric(jsonOb.getString("name")) && jsonOb.has(NAMESPACE) + && jsonOb.has("whitelistTopicName") + && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring( + jsonOb.getString("whitelistTopicName").lastIndexOf(".") + 1, + jsonOb.getString("whitelistTopicName").length()))) { + + String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, + "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; + + // Check if the user have create permission for the + // namespace + if (checkMirrorMakerPermission(ctx, permission)) { + + JSONObject listAll = new JSONObject(); + JSONObject emptyObject = new JSONObject(); + + // Create a listAllMirrorMaker Json object + try { + listAll.put("listAllMirrorMaker", emptyObject); + + } catch (JSONException e) { + + LOGGER.error("JSONException: ", e); + } + + // set a random number as messageID + String randomStr = getRandomNum(); + listAll.put("messageID", randomStr); + InputStream inStream = null; + + // convert listAll Json object to InputStream object + try { + inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); + + } catch (IOException ioe) { + LOGGER.error("IOException: ", ioe); + } + // call listAllMirrorMaker + mirrorService.pushEvents(ctx, topic, inStream, null, null); + + // subscribe for listMirrorMaker + long startTime = System.currentTimeMillis(); + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + + while (!isListMirrorMaker(msgFrmSubscribe, randomStr) + && (System.currentTimeMillis() - startTime) < timeout) { + msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + } + + JSONObject jsonObj; + JSONArray jsonArray; + JSONArray listMirrorMaker = null; + + if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 + && isListMirrorMaker(msgFrmSubscribe, randomStr)) { + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + jsonArray = new JSONArray(msgFrmSubscribe); + + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + + JSONObject obj = new JSONObject(); + if (jsonObj.has(MESSAGE)) { + obj = jsonObj.getJSONObject(MESSAGE); + } + if (obj.has("messageID") && obj.get("messageID").equals(randomStr) + && obj.has(LISTMIRRORMAKER)) { + listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER); + break; + } + } + String whitelist = null; + if (listMirrorMaker != null) { + for (int i = 0; i < listMirrorMaker.length(); i++) { + + JSONObject mm = new JSONObject(); + mm = listMirrorMaker.getJSONObject(i); + String name = mm.getString("name"); + + if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { + whitelist = mm.getString("whitelist"); + break; + } + } + } + + List topicList = new ArrayList<>(); + + if (whitelist != null) { + topicList = Arrays.asList(whitelist.split(",")); + } + boolean removeTopic = false; + String topicToRemove = jsonOb.getString("whitelistTopicName"); + + if (topicList.contains(topicToRemove)) { + removeTopic = true; + } else { + sendErrResponse(ctx, "The topic does not exist."); + } + + if (removeTopic) { + UpdateWhiteList updateWhiteList = new UpdateWhiteList(); + MirrorMaker mirrorMaker = new MirrorMaker(); + + mirrorMaker.setName(jsonOb.getString("name")); + mirrorMaker.setWhitelist(removeTopic(whitelist, topicToRemove)); + + String newRandom = getRandomNum(); + + updateWhiteList.setMessageID(newRandom); + updateWhiteList.setUpdateWhiteList(mirrorMaker); + + Gson g = new Gson(); + g.toJson(updateWhiteList); + + InputStream inputStream; + inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8); + callPubSubForWhitelist(newRandom, ctx, inputStream, getNamespace(topicToRemove)); + } + + } else { + + JSONObject err = new JSONObject(); + err.append(ERROR, + "listWhiteList is not available, please make sure MirrorMakerAgent is running"); + DMaaPResponseBuilder.respondOk(ctx, err); + } + + } else { + sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); + } + + } else { + + sendErrResponse(ctx, "This is not a DeleteAllWhitelist request. Please try again."); + } + + } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException + | TopicExistsException | missingReqdSetting | UnavailableException e) { + + LOGGER.error("IOException: ", e); + } + } + // Send error response if user does not provide Authorization + else { + sendErrResponse(ctx, NO_USER_PERMISSION); + } + } + + private String getNamespace(String topic) { + return topic.substring(0, topic.lastIndexOf(".")); + } + + private String removeTopic(String whitelist, String topicToRemove) { + List topicList = new ArrayList<>(); + List newTopicList = new ArrayList<>(); + + if (whitelist.contains(",")) { + topicList = Arrays.asList(whitelist.split(",")); + + } + + if (topicList.contains(topicToRemove)) { + for (String topic : topicList) { + if (!topic.equals(topicToRemove)) { + newTopicList.add(topic); + } + } + } + + String newWhitelist = StringUtils.join(newTopicList, ","); + + return newWhitelist; + } + + private void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, String namespace) { + + try { + mirrorService.pushEvents(ctx, topic, inStream, null, null); + long startTime = System.currentTimeMillis(); + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + + while (!isListMirrorMaker(msgFrmSubscribe, randomStr) + && (System.currentTimeMillis() - startTime) < timeout) { + msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + } + + JSONObject jsonObj; + JSONArray jsonArray; + JSONArray jsonArrayNamespace = null; + + if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 + && isListMirrorMaker(msgFrmSubscribe, randomStr)) { + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + jsonArray = new JSONArray(msgFrmSubscribe); + + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + + JSONObject obj = new JSONObject(); + if (jsonObj.has(MESSAGE)) { + obj = jsonObj.getJSONObject(MESSAGE); + } + if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) { + jsonArrayNamespace = obj.getJSONArray(LISTMIRRORMAKER); + } + } + JSONObject finalJasonObj = new JSONObject(); + JSONArray finalJsonArray = new JSONArray(); + + for (int i = 0; i < jsonArrayNamespace.length(); i++) { + + JSONObject mmObj; + mmObj = jsonArrayNamespace.getJSONObject(i); + String whitelist; + + if (mmObj.has("whitelist")) { + whitelist = getWhitelistByNamespace(mmObj.getString("whitelist"), namespace); + + if (whitelist != null) { + mmObj.remove("whitelist"); + mmObj.put("whitelist", whitelist); + } else { + mmObj.remove("whitelist"); + } + } + finalJsonArray.put(mmObj); + } + finalJasonObj.put(LISTMIRRORMAKER, finalJsonArray); + + DMaaPResponseBuilder.respondOk(ctx, finalJasonObj); + + } else { + + JSONObject err = new JSONObject(); + err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running"); + DMaaPResponseBuilder.respondOk(ctx, err); + } + + } catch (Exception e) { + LOGGER.error("Exception: ", e); + } + } + + private String getWhitelistByNamespace(String originalWhitelist, String namespace) { + + String whitelist = null; + List resultList = new ArrayList<>(); + List whitelistList = new ArrayList<>(); + whitelistList = Arrays.asList(originalWhitelist.split(",")); + + for (String topic : whitelistList) { + if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) { + resultList.add(topic); + } + } + if (!resultList.isEmpty()) { + whitelist = StringUtils.join(resultList, ","); + } + + return whitelist; + } + + private JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) { + JSONObject jsonObj; + JSONArray jsonArray; + JSONArray listMirrorMaker = new JSONArray(); + + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + jsonArray = new JSONArray(msgFrmSubscribe); + + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + + JSONObject obj = new JSONObject(); + if (jsonObj.has(MESSAGE)) { + obj = jsonObj.getJSONObject(MESSAGE); + } + if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) { + listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER); + break; + } + } + return listMirrorMaker; + } +} diff --git a/src/main/java/org/onap/dmaap/service/MetricsRestService.java b/src/main/java/org/onap/dmaap/service/MetricsRestService.java new file mode 100644 index 0000000..0a9193b --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/MetricsRestService.java @@ -0,0 +1,152 @@ +/******************************************************************************* + * ============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.service; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; + +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.service.MetricsService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; + +/** + * This class is a CXF REST service which acts + * as gateway for MR Metrics Service. + * @author rajashree.khare + * + */ +@Component +@Path("/") +public class MetricsRestService { + + /** + * Logger obj + */ + //private Logger log = Logger.getLogger(MetricsRestService.class.toString()); + private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigurationReader.class); + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest request; + + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse response; + + /** + * Config Reader + */ + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + /** + * MetricsService obj + */ + @Autowired + private MetricsService metricsService; + + /** + * Get Metrics method + * @throws CambriaApiException ex + */ + @GET + @Produces("text/plain") + public void getMetrics() throws CambriaApiException { + try { + log.info("MetricsRestService: getMetrics : START"); + metricsService.get(getDmaapContext()); + log.info("MetricsRestService: getMetrics : Completed"); + } catch (IOException e) { + log.error("Error while fetching metrics data : ", e); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.GET_METRICS_ERROR.getResponseCode(), + "Error while fetching metrics data"+ e.getMessage()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + /** + * This method is for get the metrics details by the metrics name + * + * @param metricName + * @throws CambriaApiException + */ + @GET + @Path("/{metricName}") + @Produces("text/plain") + public void getMetricsByName(@PathParam("metricName") String metricName) + throws CambriaApiException { + + try { + log.info("MetricsProducer: getMetricsByName : START"); + metricsService.getMetricByName(getDmaapContext(), metricName); + log.info("MetricsRestService: getMetricsByName : Completed"); + } catch (IOException | CambriaApiException e) { + log.error("Error while fetching metrics data : ", e); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GET_METRICS_ERROR.getResponseCode(), + "Error while fetching metrics data"+ e.getMessage()); + log.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + /** + * This method is used for taking Configuration Object,HttpServletRequest + * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession + * Object. + * + * @return DMaaPContext object from where user can get Configuration + * Object,HttpServlet Object + * + */ + private DMaaPContext getDmaapContext() { + DMaaPContext dmaapContext = new DMaaPContext(); + dmaapContext.setConfigReader(configReader); + dmaapContext.setRequest(request); + dmaapContext.setResponse(response); + return dmaapContext; + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/service/ServiceUtil.java b/src/main/java/org/onap/dmaap/service/ServiceUtil.java new file mode 100644 index 0000000..7384e54 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/ServiceUtil.java @@ -0,0 +1,39 @@ +/*- + * ============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.service; + +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; + +public class ServiceUtil { + private static DMaaPContext dmaaPContext; + + + public static DMaaPContext getDMaaPContext(ConfigurationReader configReader,HttpServletRequest request,HttpServletResponse response) { + dmaaPContext = new DMaaPContext(); + dmaaPContext.setConfigReader(configReader); + dmaaPContext.setRequest(request); + dmaaPContext.setResponse(response); + return dmaaPContext; + } + +} diff --git a/src/main/java/org/onap/dmaap/service/TopicRestService.java b/src/main/java/org/onap/dmaap/service/TopicRestService.java new file mode 100644 index 0000000..bbf2708 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/TopicRestService.java @@ -0,0 +1,696 @@ +/******************************************************************************* + * ============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.service; + +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.http.HttpStatus; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.json.JSONException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.beans.TopicBean; +import org.onap.dmaap.dmf.mr.constants.CambriaConstants; +import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; +import org.onap.dmaap.dmf.mr.service.TopicService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; + +/** + * This class is a CXF REST service which acts + * as gateway for MR Topic Service. + * @author Ramkumar Sembaiyan + * + */ + +@Component +@Path("/") +public class TopicRestService { + + /** + * Logger obj + */ + //private static final Logger LOGGER = Logger .getLogger(TopicRestService.class); + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(TopicRestService.class); + /** + * Config Reader + */ + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest request; + + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse response; + + /** + * TopicService obj + */ + @Autowired + private TopicService topicService; + + /** + * DMaaPErrorMessages obj + */ + @Autowired + private DMaaPErrorMessages errorMessages; + + /** + * mrNamespace + */ + //@Value("${msgRtr.namespace.aaf}") +// private String mrNamespace; + + + /** + * Fetches a list of topics from the current kafka instance and converted + * into json object. + * + * @return list of the topics in json format + * @throws AccessDeniedException + * @throws CambriaApiException + * @throws IOException + * @throws JSONException + * */ + @GET + //@Produces(MediaType.TEXT_PLAIN) + public void getTopics() throws CambriaApiException { + try { + + LOGGER.info("Authenticating the user before fetching the topics"); + //String permission = "com.att.dmaap.mr.topic|*|view"; + String mrNameS= com.att.ajsc.beans.PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop,"msgRtr.namespace.aaf"); + String permission =mrNameS+"|"+"*"+"|"+"view"; + DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); + //Check if client is using AAF CADI Basic Authorization + //If yes then check for AAF role authentication else display all topics + if(null!=getDmaapContext().getRequest().getHeader("Authorization")) + { + if(!aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) + { + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), + errorMessages.getNotPermitted1()+" read "+errorMessages.getNotPermitted2()); + LOGGER.info(errRes.toString()); + throw new DMaaPAccessDeniedException(errRes); + + + } + } + + LOGGER.info("Fetching all Topics"); + //topicService = new com.att.dmf.mr.service.impl.TopicServiceImpl(); + topicService.getTopics(getDmaapContext()); + + LOGGER.info("Returning List of all Topics"); + + + } catch (JSONException | ConfigDbException | IOException excp) { + LOGGER.error( + "Failed to retrieve list of all topics: " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GET_TOPICS_FAIL.getResponseCode(), + errorMessages.getTopicsfailure()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + + } + } + + /** + * Fetches a list of topics from the current kafka instance and converted + * into json object. + * + * @return list of the topics in json format + * @throws AccessDeniedException + * @throws CambriaApiException + * @throws IOException + * @throws JSONException + * */ + @GET + @Path("/listAll") + //@Produces(MediaType.TEXT_PLAIN) + public void getAllTopics() throws CambriaApiException { + try { + + LOGGER.info("Authenticating the user before fetching the topics"); + //String permission = "com.att.dmaap.mr.topic|*|view"; + String mrNameS= com.att.ajsc.beans.PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop,"msgRtr.namespace.aaf"); + String permission =mrNameS+"|"+"*"+"|"+"view"; + DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); + //Check if client is using AAF CADI Basic Authorization + //If yes then check for AAF role authentication else display all topics + if(null!=getDmaapContext().getRequest().getHeader("Authorization")) + { + if(!aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) + { + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), + errorMessages.getNotPermitted1()+" read "+errorMessages.getNotPermitted2()); + LOGGER.info(errRes.toString()); + throw new DMaaPAccessDeniedException(errRes); + + + } + } + + LOGGER.info("Fetching all Topics"); + + topicService.getAllTopics(getDmaapContext()); + + LOGGER.info("Returning List of all Topics"); + + + } catch (JSONException | ConfigDbException | IOException excp) { + LOGGER.error( + "Failed to retrieve list of all topics: " + + excp.getMessage(), excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GET_TOPICS_FAIL.getResponseCode(), + errorMessages.getTopicsfailure()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + + } + } + + + /** + * Returns details of the topic whose name is passed as a parameter + * + * @param topicName + * - name of the topic + * @return details of a topic whose name is mentioned in the request in json + * format. + * @throws AccessDeniedException + * @throws DMaaPAccessDeniedException + * @throws IOException + * */ + @GET + @Path("/{topicName}") + //@Produces(MediaType.TEXT_PLAIN) + public void getTopic(@PathParam("topicName") String topicName) throws CambriaApiException { + try { + + LOGGER.info("Authenticating the user before fetching the details about topic = "+ topicName); + DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); + + //String permission= "com.att.ecomp_test.crm.mr.topic|:topic.com.att.ecomp_test.crm.preDemo|view"; + + //Check if client is using AAF CADI Basic Authorization + //If yes then check for AAF role authentication else display all topics + if(null!=getDmaapContext().getRequest().getHeader("Authorization")) + { + String permission = aaf.aafPermissionString(topicName, "view"); + if(!aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) + { + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), + errorMessages.getNotPermitted1()+" read "+errorMessages.getNotPermitted2()); + LOGGER.info(errRes.toString()); + throw new DMaaPAccessDeniedException(errRes); + } + } + + LOGGER.info("Fetching Topic: " + topicName); + + topicService.getTopic(getDmaapContext(), topicName); + + LOGGER.info("Fetched details of topic: " + topicName); + + } catch (ConfigDbException | IOException | TopicExistsException excp) { + LOGGER.error("Failed to retrieve details of topic: " + topicName, + excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GET_TOPICS_DETAILS_FAIL.getResponseCode(), + errorMessages.getTopicDetailsFail()+topicName+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + + } + } + + + + /** + * This method is still not working. Need to check on post call and how to + * accept parameters for post call + * + * @param topicBean + * it will have the bean object + * @throws TopicExistsException + * @throws CambriaApiException + * @throws JSONException + * @throws IOException + * @throws AccessDeniedException + * + * */ + @POST + @Path("/create") + @Consumes({ MediaType.APPLICATION_JSON }) + //@Produces(MediaType.TEXT_PLAIN) + public void createTopic(TopicBean topicBean) throws CambriaApiException, JSONException { + try { + LOGGER.info("Creating Topic."+topicBean.getTopicName()); + + topicService.createTopic(getDmaapContext(), topicBean); + + LOGGER.info("Topic created Successfully."); + } + catch (TopicExistsException ex){ + + LOGGER.error("Error while creating a topic: " + ex.getMessage(), + ex); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_CONFLICT, + DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), + errorMessages.getCreateTopicFail()+ ex.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + + + + }catch (AccessDeniedException | DMaaPAccessDeniedException excp) { + LOGGER.error("Error while creating a topic: " + excp.getMessage(), + excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), + errorMessages.getCreateTopicFail()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + }catch (CambriaApiException | IOException excp) { + LOGGER.error("Error while creating a topic: " + excp.getMessage(), + excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), + errorMessages.getCreateTopicFail()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * Deletes existing topic whose name is passed as a parameter + * + * @param topicName + * topic + * @throws CambriaApiException + * @throws IOException + * */ + @DELETE + @Path("/{topicName}") + //@Produces(MediaType.TEXT_PLAIN) + public void deleteTopic(@PathParam("topicName") String topicName) throws CambriaApiException { + try { + LOGGER.info("Deleting Topic: " + topicName); + + topicService.deleteTopic(getDmaapContext(), topicName); + + LOGGER.info("Topic [" + topicName + "] deleted successfully."); + } catch (DMaaPAccessDeniedException| AccessDeniedException excp) { + LOGGER.error("Error while creating a topic: " + excp.getMessage(), + excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), + errorMessages.getCreateTopicFail()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + }catch (IOException | ConfigDbException + | CambriaApiException | TopicExistsException excp) { + LOGGER.error("Error while deleting topic: " + topicName, excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.DELETE_TOPIC_FAIL.getResponseCode(), + errorMessages.getDeleteTopicFail()+ topicName + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + private DMaaPContext getDmaapContext() { + + DMaaPContext dmaapContext = new DMaaPContext(); + dmaapContext.setRequest(request); + dmaapContext.setResponse(response); + dmaapContext.setConfigReader(configReader); + + return dmaapContext; + + } + + /** + * This method will fetch the details of publisher by giving topic name + * + * @param topicName + * @throws CambriaApiException + * @throws AccessDeniedException + */ + @GET + @Path("/{topicName}/producers") + //@Produces(MediaType.TEXT_PLAIN) + public void getPublishersByTopicName( + @PathParam("topicName") String topicName) throws CambriaApiException { + try { + +// String permission = "com.att.dmaap.mr.topic"+"|"+topicName+"|"+"manage"; +// DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); +// String permission = aaf.aafPermissionString(topicName, "view"); +// if(aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) +// { + LOGGER.info("Fetching list of all the publishers for topic " + + topicName); + + topicService.getPublishersByTopicName(getDmaapContext(), topicName); + + LOGGER.info("Returning list of all the publishers for topic " + + topicName); +// }else{ +// LOGGER.error("Error while fetching list of publishers for topic "+ topicName); +// +// ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, +// DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), +// errorMessages.getNotPermitted1()+" fetch list of publishers "+errorMessages.getNotPermitted2()); +// LOGGER.info(errRes); +// throw new DMaaPAccessDeniedException(errRes); +// +// } + + } catch (IOException | ConfigDbException | TopicExistsException excp) { + LOGGER.error("Error while fetching list of publishers for topic " + + topicName, excp); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.GET_PUBLISHERS_BY_TOPIC.getResponseCode(), + "Error while fetching list of publishers for topic: " + + topicName + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * proving permission for the topic for a particular publisher id + * + * @param topicName + * @param producerId + * @throws CambriaApiException + */ + @PUT + @Path("/{topicName}/producers/{producerId}") + public void permitPublisherForTopic( + @PathParam("topicName") String topicName, + @PathParam("producerId") String producerId) throws CambriaApiException { + try { + LOGGER.info("Granting write access to producer [" + producerId + + "] for topic " + topicName); + + topicService.permitPublisherForTopic(getDmaapContext(), topicName, + producerId); + + LOGGER.info("Write access has been granted to producer [" + + producerId + "] for topic " + topicName); + } catch (AccessDeniedException | DMaaPAccessDeniedException excp) { + LOGGER.error("Error while creating a topic: " + excp.getMessage(), + excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), + errorMessages.getCreateTopicFail()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + }catch ( ConfigDbException | IOException + | TopicExistsException excp) { + LOGGER.error("Error while granting write access to producer [" + + producerId + "] for topic " + topicName, excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND, + DMaaPResponseCode.PERMIT_PUBLISHER_FOR_TOPIC.getResponseCode(), + "Error while granting write access to producer [" + + producerId + "] for topic " + topicName + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * Removing access for a publisher id for any particular topic + * + * @param topicName + * @param producerId + * @throws CambriaApiException + */ + @DELETE + @Path("/{topicName}/producers/{producerId}") + public void denyPublisherForTopic(@PathParam("topicName") String topicName, + @PathParam("producerId") String producerId) throws CambriaApiException { + try { + LOGGER.info("Revoking write access to producer [" + producerId + + "] for topic " + topicName); + + topicService.denyPublisherForTopic(getDmaapContext(), topicName, + producerId); + + LOGGER.info("Write access revoked for producer [" + producerId + + "] for topic " + topicName); + } catch (DMaaPAccessDeniedException | AccessDeniedException excp) { + LOGGER.error("Error while creating a topic: " + excp.getMessage(), + excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), + errorMessages.getCreateTopicFail()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + }catch ( ConfigDbException | IOException + | TopicExistsException excp) { + LOGGER.error("Error while revoking write access for producer [" + + producerId + "] for topic " + topicName, excp); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.REVOKE_PUBLISHER_FOR_TOPIC.getResponseCode(), + "Error while revoking write access to producer [" + + producerId + "] for topic " + topicName + excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + /** + * Get the consumer details by the topic name + * + * @param topicName + * @throws AccessDeniedException + * @throws CambriaApiException + */ + @GET + @Path("/{topicName}/consumers") + //@Produces(MediaType.TEXT_PLAIN) + public void getConsumersByTopicName(@PathParam("topicName") String topicName) throws AccessDeniedException, + CambriaApiException { + try { + + +// String permission = "com.att.dmaap.mr.topic"+"|"+topicName+"|"+"view"; +// DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); +// String permission = aaf.aafPermissionString(topicName, "view"); +// if(aaf.aafAuthentication(getDmaapContext().getRequest(), permission)) +// { + LOGGER.info("Fetching list of all consumers for topic " + topicName); + + topicService.getConsumersByTopicName(getDmaapContext(), topicName); + + LOGGER.info("Returning list of all consumers for topic " + + topicName); + +// }else{ +// LOGGER.error( +// "Error while fetching list of all consumers for topic " +// + topicName); +// ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, +// DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), +// errorMessages.getNotPermitted1()+" fetch list of consumers "+errorMessages.getNotPermitted2()); +// LOGGER.info(errRes); +// throw new DMaaPAccessDeniedException(errRes); +// +// +// } + + + + } catch (IOException | ConfigDbException | TopicExistsException excp) { + LOGGER.error( + "Error while fetching list of all consumers for topic " + + topicName, excp); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.GET_CONSUMERS_BY_TOPIC.getResponseCode(), + "Error while fetching list of all consumers for topic: " + + topicName+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * providing access for consumer for any particular topic + * + * @param topicName + * @param consumerId + * @throws CambriaApiException + */ + @PUT + @Path("/{topicName}/consumers/{consumerId}") + public void permitConsumerForTopic( + @PathParam("topicName") String topicName, + @PathParam("consumerId") String consumerId) throws CambriaApiException { + try { + LOGGER.info("Granting read access to consumer [" + consumerId + + "] for topic " + topicName); + + topicService.permitConsumerForTopic(getDmaapContext(), topicName, + consumerId); + + LOGGER.info("Read access granted to consumer [" + consumerId + + "] for topic " + topicName); + } catch (AccessDeniedException | ConfigDbException | IOException + | TopicExistsException excp) { + LOGGER.error("Error while granting read access to consumer [" + + consumerId + "] for topic " + topicName, excp); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.PERMIT_CONSUMER_FOR_TOPIC.getResponseCode(), + "Error while granting read access to consumer [" + + consumerId + "] for topic " + topicName+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + /** + * Removing access for consumer for any particular topic + * + * @param topicName + * @param consumerId + * @throws CambriaApiException + */ + @DELETE + @Path("/{topicName}/consumers/{consumerId}") + public void denyConsumerForTopic(@PathParam("topicName") String topicName, + @PathParam("consumerId") String consumerId) throws CambriaApiException { + try { + LOGGER.info("Revoking read access to consumer [" + consumerId + + "] for topic " + topicName); + + topicService.denyConsumerForTopic(getDmaapContext(), topicName, + consumerId); + + LOGGER.info("Read access revoked to consumer [" + consumerId + + "] for topic " + topicName); + } catch ( ConfigDbException | IOException + | TopicExistsException excp) { + LOGGER.error("Error while revoking read access to consumer [" + + consumerId + "] for topic " + topicName, excp); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, + DMaaPResponseCode.REVOKE_CONSUMER_FOR_TOPIC.getResponseCode(), + "Error while revoking read access to consumer [" + + consumerId + "] for topic " + topicName+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + }catch (DMaaPAccessDeniedException | AccessDeniedException excp) { + LOGGER.error("Error while creating a topic: " + excp.getMessage(), + excp); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.CREATE_TOPIC_FAIL.getResponseCode(), + errorMessages.getCreateTopicFail()+ excp.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + } + + public TopicService getTopicService() { + return topicService; + } + + public void setTopicService(TopicService topicService) { + this.topicService = topicService; + } + + + + +} diff --git a/src/main/java/org/onap/dmaap/service/TransactionRestService.java b/src/main/java/org/onap/dmaap/service/TransactionRestService.java new file mode 100644 index 0000000..8b806b0 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/TransactionRestService.java @@ -0,0 +1,176 @@ +/******************************************************************************* + * ============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.service; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Context; + +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import com.att.aft.dme2.internal.jettison.json.JSONException; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.service.TransactionService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import com.att.nsa.configs.ConfigDbException; + +/** + * This class is a CXF REST service + * which acts as gateway for DMaaP + * Transaction Ids. + * @author rajashree.khare + * + */ +@Component +@Path("/") +public class TransactionRestService { + + /** + * Logger obj + */ + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(TransactionRestService.class); + + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest request; + + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse response; + + /** + * Config Reader + */ + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + @Autowired + private TransactionService transactionService; + + /** + * + * Returns a list of all the existing Transaction Ids + * @throws CambriaApiException + * + * @throws IOException + * @exception ConfigDbException + * @exception IOException + * + * + */ + @GET + public void getAllTransactionObjs() throws CambriaApiException { + try { + LOGGER.info("Retrieving list of all transactions."); + + transactionService.getAllTransactionObjs(getDmaapContext()); + + LOGGER.info("Returning list of all transactions."); + } catch (ConfigDbException | IOException e) { + LOGGER.error("Error while retrieving list of all transactions: " + + e.getMessage(), e); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_EXPECTATION_FAILED, + DMaaPResponseCode.RETRIEVE_TRANSACTIONS.getResponseCode(), + "Error while retrieving list of all transactions:"+e.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } + } + + /** + * + * Returns details of a particular transaction id whose name is + * passed as a parameter + * + * @param transactionId + * - id of transaction + * @throws CambriaApiException + * @throws IOException + * @exception ConfigDbException + * @exception IOException + * @exception JSONException + * + * + */ + @GET + @Path("/{transactionId}") + public void getTransactionObj( + @PathParam("transactionId") String transactionId) throws CambriaApiException { + + LOGGER.info("Fetching details of Transaction ID : " + transactionId); + + try { + transactionService.getTransactionObj(getDmaapContext(), + transactionId); + } catch (ConfigDbException | JSONException | IOException e) { + LOGGER.error("Error while retrieving transaction details for id: " + + transactionId, e); + + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_EXPECTATION_FAILED, + DMaaPResponseCode.RETRIEVE_TRANSACTIONS_DETAILS.getResponseCode(), + "Error while retrieving transaction details for id: [" + + transactionId + "]: " + e.getMessage()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } + + LOGGER.info("Returning details of transaction " + transactionId); + + } + + /** + * This method is used for taking Configuration Object,HttpServletRequest + * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession + * Object. + * + * @return DMaaPContext object from where user can get Configuration + * Object,HttpServlet Object + * + */ + private DMaaPContext getDmaapContext() { + DMaaPContext dmaapContext = new DMaaPContext(); + dmaapContext.setConfigReader(configReader); + dmaapContext.setRequest(request); + dmaapContext.setResponse(response); + return dmaapContext; + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/dmaap/service/UIRestServices.java b/src/main/java/org/onap/dmaap/service/UIRestServices.java new file mode 100644 index 0000000..bca64c4 --- /dev/null +++ b/src/main/java/org/onap/dmaap/service/UIRestServices.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.service; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Context; + +import org.apache.kafka.common.errors.TopicExistsException; + +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.service.UIService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; +import com.att.nsa.configs.ConfigDbException; + +/** + * UI Rest Service + * @author rajashree.khare + * + */ +@Component +public class UIRestServices { + + /** + * Logger obj + */ + //private static final Logger LOGGER = Logger.getLogger(UIRestServices.class); + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(UIRestServices.class); + + @Autowired + private UIService uiService; + + /** + * Config Reader + */ + @Autowired + @Qualifier("configurationReader") + private ConfigurationReader configReader; + + /** + * HttpServletRequest obj + */ + @Context + private HttpServletRequest request; + + /** + * HttpServletResponse obj + */ + @Context + private HttpServletResponse response; + + /** + * getting the hello + */ + @GET + @Path("/") + public void hello() { + try { + LOGGER.info("Calling hello page."); + + uiService.hello(getDmaapContext()); + + LOGGER.info("Hello page is returned."); + } catch (IOException excp) { + LOGGER.error("Error while calling hello page: " + excp.getMessage(), excp); + DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, + "Error while calling hello page: " + excp.getMessage()); + } + } + + /** + * getApikeysTable + */ + @GET + @Path("/ui/apikeys") + public void getApiKeysTable() { + try { + LOGGER.info("Fetching list of all api keys."); + + uiService.getApiKeysTable(getDmaapContext()); + + LOGGER.info("Returning list of all api keys."); + } catch (ConfigDbException | IOException excp) { + LOGGER.error("Error while fetching list of all api keys: " + excp.getMessage(), excp); + DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, + "Error while fetching list of all api keys: " + excp.getMessage()); + } + } + + /** + * getApiKey + * + * @param apiKey + * @exception Exception + */ + @GET + @Path("/ui/apikeys/{apiKey}") + public void getApiKey(@PathParam("apiKey") String apiKey) { + try { + LOGGER.info("Fetching details of api key: " + apiKey); + + uiService.getApiKey(getDmaapContext(), apiKey); + + LOGGER.info("Returning details of api key: " + apiKey); + } catch (Exception excp) { + LOGGER.error("Error while fetching details of api key: " + apiKey, excp); + DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, + "Error while fetching details of api key: " + apiKey); + } + } + + @GET + @Path("/ui/topics") + public void getTopicsTable() { + try { + LOGGER.info("Fetching list of all topics."); + + uiService.getTopicsTable(getDmaapContext()); + + LOGGER.info("Returning list of all topics."); + } catch (ConfigDbException | IOException excp) { + LOGGER.error("Error while fetching list of all topics: " + excp, excp); + DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, + "Error while fetching list of all topics: " + excp.getMessage()); + } + } + + /** + * + * @param topic + */ + @GET + @Path("/ui/topics/{topic}") + public void getTopic(@PathParam("topic") String topic) { + try { + LOGGER.info("Fetching details of topic: " + topic); + + uiService.getTopic(getDmaapContext(), topic); + + LOGGER.info("Returning details of topic: " + topic); + } catch (ConfigDbException | IOException | TopicExistsException excp) { + LOGGER.error("Error while fetching details of topic: " + topic, excp); + DMaaPResponseBuilder.respondWithError(getDmaapContext(), HttpStatus.SC_NOT_FOUND, + "Error while fetching details of topic: " + topic); + } + } + + /** + * This method is used for taking Configuration Object,HttpServletRequest + * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession + * Object. + * + * @return DMaaPContext object from where user can get Configuration + * Object,HttpServlet Object + * + */ + private DMaaPContext getDmaapContext() { + DMaaPContext dmaapContext = new DMaaPContext(); + dmaapContext.setConfigReader(configReader); + dmaapContext.setRequest(request); + dmaapContext.setResponse(response); + return dmaapContext; + } +} diff --git a/src/main/java/org/onap/dmaap/tools/ConfigTool.java b/src/main/java/org/onap/dmaap/tools/ConfigTool.java new file mode 100644 index 0000000..2531318 --- /dev/null +++ b/src/main/java/org/onap/dmaap/tools/ConfigTool.java @@ -0,0 +1,818 @@ +/******************************************************************************* + * ============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.tools; + +import java.io.IOException; +import java.io.PrintStream; +import java.security.NoSuchAlgorithmException; +import java.util.Date; +import java.util.LinkedList; +import java.util.Map.Entry; + +import org.json.JSONException; + +import com.att.nsa.apiServer.CommonServlet; +import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker; +import org.onap.dmaap.dmf.mr.metabroker.Topic; +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandLineTool; +import com.att.nsa.cmdtool.CommandNotReadyException; +import com.att.nsa.configs.ConfigDb; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.configs.ConfigPath; +import com.att.nsa.configs.confimpl.EncryptingLayer; +import com.att.nsa.configs.confimpl.ZkConfigDb; +import com.att.nsa.drumlin.till.data.rrConvertor; +import com.att.nsa.drumlin.till.data.uniqueStringGenerator; +import com.att.nsa.drumlin.till.nv.impl.nvWriteableTable; +import com.att.nsa.security.db.BaseNsaApiDbImpl; +import com.att.nsa.security.db.EncryptingApiDbImpl; +import com.att.nsa.security.db.NsaApiDb.KeyExistsException; +import com.att.nsa.security.db.simple.NsaSimpleApiKey; +import com.att.nsa.security.db.simple.NsaSimpleApiKeyFactory; +import com.att.nsa.util.NsaClock; + +public class ConfigTool extends CommandLineTool +{ + protected ConfigTool () + { + super ( "Cambria API Config Tool", "cambriaConfig> " ); + + super.registerCommand ( new ListTopicCommand () ); + super.registerCommand ( new WriteTopicCommand () ); + super.registerCommand ( new ReadTopicCommand () ); + super.registerCommand ( new SetTopicOwnerCommand () ); + super.registerCommand ( new InitSecureTopicCommand () ); + super.registerCommand ( new ListApiKeysCommand () ); + super.registerCommand ( new PutApiCommand () ); + super.registerCommand ( new writeApiKeyCommand () ); + super.registerCommand ( new EncryptApiKeysCommand () ); + super.registerCommand ( new DecryptApiKeysCommand () ); + super.registerCommand ( new NodeFetchCommand () ); + super.registerCommand ( new DropOldConsumerGroupsCommand () ); + } + + public static void main ( String[] args ) throws IOException + { + final String connStr = args.length>0 ? args[0] : "localhost:2181"; + final ConfigDb db = new ZkConfigDb ( + connStr, + args.length>1 ? args[1] : CommonServlet.getDefaultZkRoot ( "cambria" ) + ); + + final ConfigToolContext context = new ConfigToolContext ( db, connStr, new nvWriteableTable() ); + final ConfigTool ct = new ConfigTool (); + ct.runFromMain ( args, context ); + } + + private static class ListTopicCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "topics", "list (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final ConfigDb db = context.getDb(); + final ConfigPath base = db.parse ( "/topics" ); + + if ( parts.length > 0 ) + { + final ConfigPath myTopic = base.getChild ( parts[0] ); + final String data = db.load ( myTopic ); + if ( data != null ) + { + out.println ( data ); + } + else + { + out.println ( "No topic [" + parts[0] + "]" ); + } + } + else + { + for ( ConfigPath child : db.loadChildrenNames ( base ) ) + { + out.println ( child.getName () ); + } + } + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "topics" ); + out.println ( "list " ); + } + } + + private static class WriteTopicCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "write (\\S*) (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final ConfigDb db = context.getDb(); + final ConfigPath base = db.parse ( "/topics" ); + final ConfigPath myTopic = base.getChild ( parts[0] ); + db.store ( myTopic, parts[1] ); + out.println ( "wrote [" + parts[1] + "] to topic [" + parts[0] + "]" ); + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "write " ); + out.println ( "\tBe careful with this. You can write data that's not compatible with Cambria's config db." ); + } + } + + private static class ReadTopicCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "read (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final ConfigDb db = context.getDb(); + final ConfigPath base = db.parse ( "/topics" ); + final ConfigPath myTopic = base.getChild ( parts[0] ); + db.store ( myTopic, parts[1] ); + out.println ( "wrote [" + parts[1] + "] to topic [" + parts[0] + "]" ); + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "read " ); + out.println ( "\tRead config data for a topic." ); + } + } + + private static class InitSecureTopicCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "initTopic (\\S*) (\\S*) (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + DMaaPKafkaMetaBroker.createTopicEntry ( context.getDb (), + context.getDb ().parse("/topics"), parts[0], parts[2], parts[1],true ); + out.println ( "Topic [" + parts[0] + "] updated." ); + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage () ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "initTopic " ); + } + } + + private static class SetTopicOwnerCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "setOwner (\\S*) (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final Topic kt = DMaaPKafkaMetaBroker.getKafkaTopicConfig ( context.getDb(), + context.getDb().parse ( "/topics" ), parts[0] ); + if ( kt != null ) + { + final String desc = kt.getDescription (); + + DMaaPKafkaMetaBroker.createTopicEntry ( context.getDb (), + context.getDb ().parse("/topics"), parts[0], desc, parts[1], true ); + out.println ( "Topic [" + parts[0] + "] updated." ); + } + else + { + out.println ( "Topic [" + parts[0] + "] doesn't exist." ); + } + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage () ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "setOwner " ); + } + } + + private static class ListApiKeysCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "listApiKeys", "listApiKey (\\S*) (\\S*) (\\S*)", "listApiKey (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final ConfigDb db = context.getDb (); + if ( parts.length == 0 ) + { + final BaseNsaApiDbImpl readFrom = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); + int count = 0; + for ( String key : readFrom.loadAllKeys () ) + { + out.println ( key ); + count++; + } + out.println ( "" + count + " records." ); + } + else + { + BaseNsaApiDbImpl readFrom = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); + if ( parts.length == 3 ) + { + readFrom = new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), + EncryptingLayer.readSecretKey ( parts[1] ), rrConvertor.base64Decode ( parts[2] ) ); + } + final NsaSimpleApiKey apikey = readFrom.loadApiKey ( parts[0] ); + if ( apikey == null ) + { + out.println ( "Key '" + parts[0] + "' not found." ); + } + else + { + out.println ( apikey.asJsonObject ().toString () ); + } + } + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( JSONException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "listApiKeys" ); + out.println ( "listApiKey " ); + out.println ( "listApiKey " ); + } + } + + private static class PutApiCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] + { + // these are + "putApiKey (secret) (\\S*) (\\S*) (\\S*) (\\S*)", + "putApiKey (email) (\\S*) (\\S*) (\\S*) (\\S*)", + "putApiKey (description) (\\S*) (\\S*) (\\S*) (\\S*)" + }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final ConfigDb db = context.getDb (); + if ( parts.length == 5 ) + { + final BaseNsaApiDbImpl apiKeyDb = + new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), + EncryptingLayer.readSecretKey ( parts[2] ), rrConvertor.base64Decode ( parts[3] ) ); + + final NsaSimpleApiKey apikey = apiKeyDb.loadApiKey ( parts[1] ); + if ( apikey == null ) + { + out.println ( "Key '" + parts[1] + "' not found." ); + } + else + { + if ( parts[0].equalsIgnoreCase ( "secret" ) ) + { + apikey.resetSecret ( parts[4] ); + } + else if ( parts[0].equalsIgnoreCase ( "email" ) ) + { + apikey.setContactEmail ( parts[4] ); + } + else if ( parts[0].equalsIgnoreCase ( "description" ) ) + { + apikey.setDescription ( parts[4] ); + } + + apiKeyDb.saveApiKey ( apikey ); + out.println ( apikey.asJsonObject ().toString () ); + } + } + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( JSONException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "putApiKey secret " ); + out.println ( "putApiKey email " ); + out.println ( "putApiKey description " ); + } + } + + private static class writeApiKeyCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] + { + // + "writeApiKey (\\S*) (\\S*) (\\S*) (\\S*)", + }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final ConfigDb db = context.getDb (); + if ( parts.length == 4 ) + { + final BaseNsaApiDbImpl apiKeyDb = + new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), + EncryptingLayer.readSecretKey ( parts[0] ), rrConvertor.base64Decode ( parts[1] ) ); + + apiKeyDb.deleteApiKey ( parts[2] ); + final NsaSimpleApiKey apikey = apiKeyDb.createApiKey ( parts[2], parts[3] ); + out.println ( apikey.asJsonObject ().toString () ); + } + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( JSONException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( KeyExistsException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "writeApiKey " ); + } + } + + private static class EncryptApiKeysCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "convertApiKeyDb", "convertApiKeyDb (\\S*) (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final String key = parts.length == 2 ? parts[0] : EncryptingLayer.createSecretKey (); + final String iv = parts.length == 2 ? parts[1] : rrConvertor.base64Encode ( uniqueStringGenerator.createValue ( 16 ) ); + + // This doesn't do well when the number of API keys is giant... + if ( parts.length == 0 ) + { + out.println ( "YOU MUST RECORD THESE VALUES AND USE THEM IN THE SERVER CONFIG" ); + out.println ( "Key: " + key ); + out.println ( " IV: " + iv ); + out.println ( "\n" ); + out.println ( "Call again with key and IV on command line." ); + out.println ( "\n" ); + return; // because otherwise the values get lost + } + + final ConfigDb db = context.getDb (); + final BaseNsaApiDbImpl readFrom = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); + final EncryptingApiDbImpl writeTo = new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), + EncryptingLayer.readSecretKey ( key ), rrConvertor.base64Decode ( iv ) ); + + int count = 0; + for ( Entry e : readFrom.loadAllKeyRecords ().entrySet () ) + { + out.println ( "-------------------------------" ); + out.println ( "Converting " + e.getKey () ); + final String was = e.getValue ().asJsonObject ().toString (); + out.println ( was ); + + writeTo.saveApiKey ( e.getValue () ); + count++; + } + + out.println ( "Conversion complete, converted " + count + " records." ); + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( NoSuchAlgorithmException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "convertApiKeyDb" ); + out.println ( "\tconvert an API key DB to an encrypted DB and output the cipher details" ); + } + } + + private static class DecryptApiKeysCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "revertApiKeyDb (\\S*) (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final String keyStr = parts[0]; + final String iv = parts[1]; + final byte[] ivBytes = rrConvertor.base64Decode ( iv ); + + final ConfigDb db = context.getDb (); + final EncryptingApiDbImpl readFrom = new EncryptingApiDbImpl ( db, new NsaSimpleApiKeyFactory (), + EncryptingLayer.readSecretKey ( keyStr ), ivBytes ); + final BaseNsaApiDbImpl writeTo = new BaseNsaApiDbImpl ( db, new NsaSimpleApiKeyFactory () ); + + int count = 0; + for ( String apiKey : readFrom.loadAllKeys () ) + { + out.println ( "Converting " + apiKey ); + final NsaSimpleApiKey record = readFrom.loadApiKey ( apiKey ); + if ( record == null ) + { + out.println ( "Couldn't load " + apiKey ); + } + else + { + writeTo.saveApiKey ( record ); + count++; + } + } + out.println ( "Conversion complete, converted " + count + " records." ); + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "revertApiKeyDb " ); + out.println ( "\trevert an API key DB to a deencrypted DB" ); + } + } + + private static class NodeFetchCommand implements Command + { + @Override + public String[] getMatches () + { + return new String[] { "node (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final String node = parts[0]; + + final ConfigDb db = context.getDb (); + final ConfigPath cp = db.parse ( node ); + + boolean doneOne = false; + for ( ConfigPath child : db.loadChildrenNames ( cp ) ) + { + out.println ( "\t- " + child.getName () ); + doneOne = true; + } + if ( doneOne ) + { + out.println (); + } + else + { + out.println ( "(No child nodes of '" + node + "')" ); + } + + final String val = db.load ( cp ); + if ( val == null ) + { + out.println ( "(No data at '" + node + "')" ); + } + else + { + out.println ( val ); + } + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( IllegalArgumentException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "node " ); + out.println ( "\tread a config db node" ); + } + } + + private static class DropOldConsumerGroupsCommand implements Command + { + private final long kMaxRemovals = 500; + + @Override + public String[] getMatches () + { + return new String[] { "(dropOldConsumers) (\\S*)", "(showOldConsumers) (\\S*)" }; + } + + @Override + public void checkReady ( ConfigToolContext context ) throws CommandNotReadyException + { + } + + @Override + public void execute ( String[] parts, ConfigToolContext context, PrintStream out ) throws CommandNotReadyException + { + try + { + final boolean runDrops = parts[0].equalsIgnoreCase ( "dropOldConsumers" ); + final String maxAgeInDaysStr = parts[1]; + final int maxAgeInDays = Integer.parseInt ( maxAgeInDaysStr ); + final long oldestEpochSecs = ( NsaClock.now () / 1000 ) - ( 24 * 60 * 60 * maxAgeInDays ); + + out.println ( "Dropping consumer groups older than " + new Date ( oldestEpochSecs * 1000 ) ); + + final ConfigDb db = context.getDb (); + + // kafka updates consumer partition records in ZK each time a message + // is served. we can determine which consumers are old based on a lack + // of update to the partition entries + // (see https://cwiki.apache.org/confluence/display/KAFKA/Kafka+data+structures+in+Zookeeper) + + // kafka only works with ZK, and our configDb was constructed with a non-kafka + // root node. We have to switch it to get to the right content... + if ( ! ( db instanceof ZkConfigDb ) ) + { + throw new ConfigDbException ( "You can only show/drop old consumers against a ZK config db." ); + } + + final ZkConfigDb newZkDb = new ZkConfigDb ( context.getConnectionString (), "" ); + long cgCount = 0; + + final LinkedList removals = new LinkedList (); + for ( ConfigPath consumerGroupName : newZkDb.loadChildrenNames ( newZkDb.parse ( "/consumers" ) ) ) + { + cgCount++; + if ( cgCount % 500 == 0 ) + { + out.println ( "" + cgCount + " groups examined" ); + } + + boolean foundAnything = false; + boolean foundRecentUse = false; + long mostRecent = -1; + + // each consumer group has an "offsets" entry, which contains 0 or more topic entries. + // each topic contains partition nodes. + for ( ConfigPath topic : newZkDb.loadChildrenNames ( consumerGroupName.getChild ( "offsets" ) ) ) + { + for ( ConfigPath offset : newZkDb.loadChildrenNames ( topic ) ) + { + foundAnything = true; + + final long modTime = newZkDb.getLastModificationTime ( offset ); + mostRecent = Math.max ( mostRecent, modTime ); + + foundRecentUse = ( modTime > oldestEpochSecs ); + if ( foundRecentUse ) break; + } + if ( foundRecentUse ) break; + } + + // decide if this consumer group is old + out.println ( "Group " + consumerGroupName.getName () + " was most recently used " + new Date ( mostRecent*1000 ) ); + if ( foundAnything && !foundRecentUse ) + { + removals.add ( consumerGroupName ); + } + + if ( removals.size () >= kMaxRemovals ) + { + break; + } + } + + // removals + for ( ConfigPath consumerGroupName : removals ) + { + out.println ( "Group " + consumerGroupName.getName () + " has no recent activity." ); + if ( runDrops ) + { + out.println ( "Removing group " + consumerGroupName.getName () + "..." ); + newZkDb.clear ( consumerGroupName ); + } + } + } + catch ( ConfigDbException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( NumberFormatException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + catch ( JSONException e ) + { + out.println ( "Command failed: " + e.getMessage() ); + } + } + + @Override + public void displayHelp ( PrintStream out ) + { + out.println ( "showOldConsumers " ); + out.println ( "dropOldConsumers " ); + out.println ( "\tDrop (or just show) any consumer group that has been inactive longer than days." ); + out.println (); + out.println ( "\tTo be safe, should be much higher than the maximum storage time on the Kafka topics." ); + out.println ( "\tA very old consumer will potentially miss messages, but will resume at the oldest message, while a" ); + out.println ( "\tdeleted consumer will start at the current message if it ever comes back." ); + out.println (); + out.println ( "\tNote that show/drops are limited to " + kMaxRemovals + " records per invocation." ); + } + } +} diff --git a/src/main/java/org/onap/dmaap/tools/ConfigToolContext.java b/src/main/java/org/onap/dmaap/tools/ConfigToolContext.java new file mode 100644 index 0000000..0e89098 --- /dev/null +++ b/src/main/java/org/onap/dmaap/tools/ConfigToolContext.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.tools; + +import org.onap.dmaap.dmf.mr.beans.DMaaPMetricsSet; +import com.att.nsa.cmdtool.CommandContext; +import com.att.nsa.configs.ConfigDb; +import com.att.nsa.drumlin.till.nv.rrNvReadable; + +public class ConfigToolContext implements CommandContext +{ + public ConfigToolContext ( ConfigDb db, String connStr, rrNvReadable cs ) + { + fDb = db; + fConnStr = connStr; + fMetrics = new DMaaPMetricsSet( cs ); + } + + @Override + public void requestShutdown () + { + fQuit = true; + } + + @Override + public boolean shouldContinue () + { + return !fQuit; + } + + public ConfigDb getDb () + { + return fDb; + } + + public String getConnectionString () + { + return fConnStr; + } + + public DMaaPMetricsSet getMetrics () + { + return fMetrics; + } + + private final ConfigDb fDb; + private final String fConnStr; + private boolean fQuit = false; + private DMaaPMetricsSet fMetrics; +} diff --git a/src/main/java/org/onap/dmaap/util/ContentLengthInterceptor.java b/src/main/java/org/onap/dmaap/util/ContentLengthInterceptor.java new file mode 100644 index 0000000..b03eb5b --- /dev/null +++ b/src/main/java/org/onap/dmaap/util/ContentLengthInterceptor.java @@ -0,0 +1,138 @@ +/******************************************************************************* + * ============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.util; + +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.http.HttpStatus; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.stereotype.Component; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import ajsc.beans.interceptors.AjscInterceptor; + +/** + * AJSC Intercepter implementation of ContentLengthFilter + */ +@Component +public class ContentLengthInterceptor implements AjscInterceptor{ + + + private String defLength; + //private Logger log = Logger.getLogger(ContentLengthInterceptor.class.toString()); + private static final EELFLogger log = EELFManager.getInstance().getLogger(ContentLengthInterceptor.class); + + + /** + * Intercepter method to intercept requests before processing + */ + @Override + public boolean allowOrReject(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, + Map map) throws Exception { + + log.info("inside Interceptor allowOrReject content length checking before pub/sub"); + + JSONObject jsonObj = null; + int requestLength = 0; + setDefLength(System.getProperty("maxcontentlength")); + try { + // retrieving content length from message header + + if (null != httpservletrequest.getHeader("Content-Length")) { + requestLength = Integer.parseInt(httpservletrequest.getHeader("Content-Length")); + } + // retrieving encoding from message header + String transferEncoding = httpservletrequest.getHeader("Transfer-Encoding"); + // checking for no encoding, chunked and requestLength greater then + // default length + if (null != transferEncoding && !(transferEncoding.contains("chunked")) + && (requestLength > Integer.parseInt(getDefLength()))) { + jsonObj = new JSONObject().append("defaultlength", getDefLength()) + .append("requestlength", requestLength); + log.error("message length is greater than default"); + throw new CambriaApiException(jsonObj); + } + else if (null == transferEncoding && (requestLength > Integer.parseInt(getDefLength()))) + { + jsonObj = new JSONObject().append("defaultlength", getDefLength()).append( + "requestlength", requestLength); + log.error("Request message is not chunked or request length is greater than default length"); + throw new CambriaApiException(jsonObj); + + + } + else + { + //chain.doFilter(req, res); + return true; + } + + } catch (CambriaApiException | NumberFormatException | JSONException e) { + + log.info("Exception obj--"+e); + log.error("message size is greater then default"+e.getMessage()); + String messg=e.toString(); + if(jsonObj!=null){ + messg=jsonObj.toString(); + } + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_REQUEST_TOO_LONG, + DMaaPResponseCode.MSG_SIZE_EXCEEDS_MSG_LIMIT.getResponseCode(), System.getProperty("msg_size_exceeds") + + messg); + log.info(errRes.toString()); + + + map.put(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"test"); + httpservletresponse.setStatus(HttpStatus.SC_REQUEST_TOO_LONG); + if(httpservletresponse.getOutputStream()!=null){ + httpservletresponse.getOutputStream().write(errRes.toString().getBytes()); + } + return false; + } + + + + } + + + /** + * Get Default Content Length + * @return defLength + */ + public String getDefLength() { + return defLength; + } + /** + * Set Default Content Length + * @param defLength + */ + public void setDefLength(String defLength) { + this.defLength = defLength; + } + + + +} diff --git a/src/main/java/org/onap/dmaap/util/DMaaPAuthFilter.java b/src/main/java/org/onap/dmaap/util/DMaaPAuthFilter.java new file mode 100644 index 0000000..547c4cd --- /dev/null +++ b/src/main/java/org/onap/dmaap/util/DMaaPAuthFilter.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * ============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.util; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.onap.dmaap.dmf.mr.utils.Utils; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.springframework.stereotype.Component; + +import org.onap.aaf.cadi.filter.CadiFilter; +//import ajsc.external.plugins.cadi.AjscCadiFilter; +import javax.servlet.FilterConfig; + +/** + * This is a Servlet Filter class + * overriding the AjscCadiFilter + */ +@Component +public class DMaaPAuthFilter extends CadiFilter { + + //private Logger log = Logger.getLogger(DMaaPAuthFilter.class.toString()); + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPAuthFilter.class); + + public DMaaPAuthFilter() throws Exception { + super(); + } + + /* public void init(FilterConfig filterConfig) throws ServletException { + + super.init(filterConfig); + System.out.println("---------------------------- in init method"); + }*/ + + /** + * This method will disable Cadi Authentication + * if cambria headers are present in the request + * else continue with Cadi Authentication + */ + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, + ServletException { + log.info("inside servlet filter Cambria Auth Headers checking before doing other Authentication"); + HttpServletRequest request = (HttpServletRequest) req; + boolean forceAAF = Boolean.valueOf(System.getProperty("forceAAF")); + + //if (forceAAF || null != request.getHeader("Authorization") ){ + if (Utils.isCadiEnabled()&&(forceAAF || null != request.getHeader("Authorization") || + (null != request.getHeader("AppName") && request.getHeader("AppName").equalsIgnoreCase("invenio") && + null != request.getHeader("cookie")))){ + super.doFilter(req, res, chain); + + } else { + System.setProperty("CadiAuthN", "authentication-scheme-2"); + chain.doFilter(req, res); + + + } + + } + + } + diff --git a/src/main/java/org/onap/dmaap/util/ServicePropertiesMapBean.java b/src/main/java/org/onap/dmaap/util/ServicePropertiesMapBean.java new file mode 100644 index 0000000..1778182 --- /dev/null +++ b/src/main/java/org/onap/dmaap/util/ServicePropertiesMapBean.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * ============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.util; + +import org.onap.dmaap.filemonitor.ServicePropertiesMap; + +/** + * Class ServicePropertiesMapBean + * @author rajashree.khare + * + */ +public class ServicePropertiesMapBean { + /** + * get property + * @param propFileName propFileName + * @param propertyKey propertyKey + * @return str + */ + public static String getProperty(String propFileName, String propertyKey) { + return ServicePropertiesMap.getProperty(propFileName, propertyKey); + } +} diff --git a/src/main/test/com/att/nsa/dmaap/DummyTest.java b/src/main/test/com/att/nsa/dmaap/DummyTest.java index b979e31..17adcea 100644 --- a/src/main/test/com/att/nsa/dmaap/DummyTest.java +++ b/src/main/test/com/att/nsa/dmaap/DummyTest.java @@ -19,7 +19,7 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. * *******************************************************************************/ -package com.att.nsa.dmaap; + package org.onap.dmaap; import static org.junit.Assert.*; diff --git a/src/test/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapperTest.java b/src/test/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapperTest.java deleted file mode 100644 index 89c9400..0000000 --- a/src/test/java/com/att/nsa/dmaap/DMaaPCambriaExceptionMapperTest.java +++ /dev/null @@ -1,86 +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.dmaap; - -import static org.junit.Assert.assertTrue; - -import org.json.JSONObject; -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.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -@RunWith(PowerMockRunner.class) -public class DMaaPCambriaExceptionMapperTest { - - @InjectMocks - DMaaPCambriaExceptionMapper mapper; - - @Mock - private ErrorResponse errRes; - - @Mock - private DMaaPErrorMessages msgs; - - @Mock - CambriaApiException exc; - - @Mock - JSONObject json; - - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testToResponse() { - try { - mapper.toResponse(null); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - - @Test - public void testToResponseCambriaApiException2() { - PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); - try { - mapper.toResponse(new CambriaApiException(404,"Not found")); - } catch (NullPointerException e) { - assertTrue(true); - } - assertTrue(true); - } -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/DMaaPWebExceptionMapperTest.java b/src/test/java/com/att/nsa/dmaap/DMaaPWebExceptionMapperTest.java deleted file mode 100644 index 9e67dcd..0000000 --- a/src/test/java/com/att/nsa/dmaap/DMaaPWebExceptionMapperTest.java +++ /dev/null @@ -1,142 +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.dmaap; - -import static org.junit.Assert.*; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.NotAllowedException; -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.ServiceUnavailableException; - -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.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; - -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; - -@RunWith(PowerMockRunner.class) -public class DMaaPWebExceptionMapperTest { - - @InjectMocks - DMaaPWebExceptionMapper mapper; - - @Mock - DMaaPErrorMessages msgs; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testToResponse() { - - try { - mapper.toResponse(null); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testToResponseNotFoundException() { - PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); - try { - mapper.toResponse(new NotFoundException()); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testToResponseInternalServerErrorException() { - PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); - try { - mapper.toResponse(new InternalServerErrorException()); - - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testToResponseNotAuthorizedException() { - PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); - try { - mapper.toResponse(new NotAuthorizedException("Error", "Error")); - - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testToResponseBadRequestException() { - PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); - try { - mapper.toResponse(new BadRequestException()); - - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testToResponseNotAllowedException() { - PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); - try { - mapper.toResponse(new NotAllowedException("Not Allowed")); - - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testToResponseServiceUnavailableException() { - PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); - try { - mapper.toResponse(new ServiceUnavailableException()); - - } catch (NullPointerException e) { - assertTrue(true); - } - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/DummyTest.java b/src/test/java/com/att/nsa/dmaap/DummyTest.java deleted file mode 100644 index ea5bac9..0000000 --- a/src/test/java/com/att/nsa/dmaap/DummyTest.java +++ /dev/null @@ -1,45 +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.dmaap; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class DummyTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void test() { - assertTrue("Dummy test case", true); - } - -} diff --git a/src/test/java/com/att/nsa/dmaap/HelloWorldTest.java b/src/test/java/com/att/nsa/dmaap/HelloWorldTest.java deleted file mode 100644 index 6191cf1..0000000 --- a/src/test/java/com/att/nsa/dmaap/HelloWorldTest.java +++ /dev/null @@ -1,52 +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.dmaap; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class HelloWorldTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testToResponse() { - - HelloWorld hello = new HelloWorld(); - - try { - hello.speak(null); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/JUnitTestSuite.java b/src/test/java/com/att/nsa/dmaap/JUnitTestSuite.java deleted file mode 100644 index 576bc4a..0000000 --- a/src/test/java/com/att/nsa/dmaap/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.dmaap; - -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({ DMaaPCambriaExceptionMapperTest.class, DMaaPWebExceptionMapper.class, - JaxrsEchoServiceTest.class, HelloWorldTest.class, JaxrsUserServiceTest.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/dmaap/JaxrsEchoServiceTest.java b/src/test/java/com/att/nsa/dmaap/JaxrsEchoServiceTest.java deleted file mode 100644 index 96fba99..0000000 --- a/src/test/java/com/att/nsa/dmaap/JaxrsEchoServiceTest.java +++ /dev/null @@ -1,60 +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.dmaap; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class JaxrsEchoServiceTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testPing() { - - JaxrsEchoService service = new JaxrsEchoService(); - - service.ping("hello"); - - assertTrue(true); - - } - - @Test - public void testGetProperty() { - - JaxrsEchoService service = new JaxrsEchoService(); - - service.getProperty("filename", "hello"); - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/JaxrsUserServiceTest.java b/src/test/java/com/att/nsa/dmaap/JaxrsUserServiceTest.java deleted file mode 100644 index acff4de..0000000 --- a/src/test/java/com/att/nsa/dmaap/JaxrsUserServiceTest.java +++ /dev/null @@ -1,50 +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.dmaap; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class JaxrsUserServiceTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testLookupUser() { - - JaxrsUserService service = new JaxrsUserService(); - - service.lookupUser("userid"); - - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/TestRunner.java b/src/test/java/com/att/nsa/dmaap/TestRunner.java deleted file mode 100644 index 5c18a19..0000000 --- a/src/test/java/com/att/nsa/dmaap/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.dmaap; - -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/dmaap/filemonitor/JUnitTestSuite.java b/src/test/java/com/att/nsa/dmaap/filemonitor/JUnitTestSuite.java deleted file mode 100644 index 6aa031b..0000000 --- a/src/test/java/com/att/nsa/dmaap/filemonitor/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.dmaap.filemonitor; - -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({ ServicePropertiesListenerTest.class, ServicePropertiesMapTest.class, - ServicePropertyServiceTest.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/dmaap/filemonitor/ServicePropertiesListenerTest.java b/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesListenerTest.java deleted file mode 100644 index 210ecfd..0000000 --- a/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesListenerTest.java +++ /dev/null @@ -1,57 +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.dmaap.filemonitor; - -import static org.junit.Assert.*; - -import java.io.File; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ServicePropertiesListenerTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - //@Test - public void testUpdate() {/* - - ServicePropertiesListener listener = new ServicePropertiesListener(); - - try { - listener.update(new File(":/file")); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - */} - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMapTest.java b/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMapTest.java deleted file mode 100644 index 636f051..0000000 --- a/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertiesMapTest.java +++ /dev/null @@ -1,128 +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.dmaap.filemonitor; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.FileNotFoundException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; - -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.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(PowerMockRunner.class) -public class ServicePropertiesMapTest { - - @InjectMocks - ServicePropertiesMap map; - - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - /*@Test - public void testRefresh() { - - try { - map.refresh(new File(":/file")); - } catch (Exception e) { - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test() - public void testRefreshJsonFile() throws Exception { - //Path resourceDirectory = Paths.get("src/test/resources"); - // map.refresh(new File(resourceDirectory+"\\"+"test.json")); - ClassLoader classLoader = getClass().getClassLoader(); - map.refresh(new File(classLoader.getResource("test.json").getFile())); - - assertTrue(true); - } - - @Test - public void testRefreshPropsFile() throws Exception { - Path resourceDirectory = Paths.get("src/test/resources"); - map.refresh(new File(resourceDirectory+"\\"+"test.properties")); - ClassLoader classLoader = getClass().getClassLoader(); - map.refresh(new File(classLoader.getResource("test.json").getFile())); - assertTrue(true); - }*/ - - @Test - public void testGetProperty() { - - try { - map.getProperty("filename", "propertykey"); - } catch (Exception e) { - e.printStackTrace(); - } - - assertTrue(true); - } - - @Test - public void testGetProperties() { - - try { - map.getProperties("filename"); - } catch (Exception e) { - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testIfNullThenEmpty() { - - try { - map.getProperties("filename"); - } catch (Exception e) { - e.printStackTrace(); - } - - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertyServiceTest.java b/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertyServiceTest.java deleted file mode 100644 index e5f0cb8..0000000 --- a/src/test/java/com/att/nsa/dmaap/filemonitor/ServicePropertyServiceTest.java +++ /dev/null @@ -1,153 +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.dmaap.filemonitor; - -import static org.junit.Assert.*; - -import java.io.File; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ServicePropertyServiceTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testInit() { - - ServicePropertyService service = new ServicePropertyService(); - try { - service.init(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testsetLoadOnStartup() { - - ServicePropertyService service = new ServicePropertyService(); - try { - service.setLoadOnStartup(true); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testSetSsfFileMonitorPollingInterval() { - - ServicePropertyService service = new ServicePropertyService(); - try { - service.setSsfFileMonitorPollingInterval("interval"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testSetSsfFileMonitorThreadpoolSize() { - - ServicePropertyService service = new ServicePropertyService(); - try { - service.setSsfFileMonitorThreadpoolSize("threadPoolSize"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testIsLoadOnStartup() { - ServicePropertyService service = new ServicePropertyService(); - service.isLoadOnStartup(); - assertTrue(true); - - } - - @Test - public void testGetSsfFileMonitorPollingInterval() { - ServicePropertyService service = new ServicePropertyService(); - service.getSsfFileMonitorPollingInterval(); - assertTrue(true); - - } - - @Test - public void testGetSsfFileMonitorThreadpoolSize() { - ServicePropertyService service = new ServicePropertyService(); - service.getSsfFileMonitorThreadpoolSize(); - assertTrue(true); - - } - - @Test - public void testGetFileChangedListener() { - ServicePropertyService service = new ServicePropertyService(); - service.getFileChangedListener(); - assertTrue(true); - - } - - @Test - public void testSetFileChangedListener() { - ServicePropertyService service = new ServicePropertyService(); - service.setFileChangedListener(null); - assertTrue(true); - - } - - @Test - public void testGetFilePropertiesMap() { - ServicePropertyService service = new ServicePropertyService(); - service.getFilePropertiesMap(); - assertTrue(true); - - } - - @Test - public void testSetFilePropertiesMap() { - ServicePropertyService service = new ServicePropertyService(); - service.setFilePropertiesMap(null); - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/filemonitor/TestRunner.java b/src/test/java/com/att/nsa/dmaap/filemonitor/TestRunner.java deleted file mode 100644 index 267a6bf..0000000 --- a/src/test/java/com/att/nsa/dmaap/filemonitor/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.dmaap.filemonitor; - -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/dmaap/mmagent/CreateMirrorMakerTest.java b/src/test/java/com/att/nsa/dmaap/mmagent/CreateMirrorMakerTest.java deleted file mode 100644 index fde7ab4..0000000 --- a/src/test/java/com/att/nsa/dmaap/mmagent/CreateMirrorMakerTest.java +++ /dev/null @@ -1,82 +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.dmaap.mmagent; - -import org.onap.dmaap.dmf.mr.CambriaApiException; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - - -public class CreateMirrorMakerTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetCreateMirrorMaker() { - - CreateMirrorMaker mMaker = new CreateMirrorMaker(); - mMaker.getCreateMirrorMaker(); - - assertTrue(true); - - } - - @Test - public void testSetCreateMirrorMaker() throws CambriaApiException { - - CreateMirrorMaker mMaker = new CreateMirrorMaker(); - mMaker.setCreateMirrorMaker(new MirrorMaker()); - - assertTrue(true); - - } - - @Test - public void testGetMessageID() { - - CreateMirrorMaker mMaker = new CreateMirrorMaker(); - mMaker.getMessageID(); - - assertTrue(true); - - } - - @Test - public void testSetMessageID() { - - CreateMirrorMaker mMaker = new CreateMirrorMaker(); - mMaker.setMessageID("messageID"); - - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/mmagent/JUnitTestSuite.java b/src/test/java/com/att/nsa/dmaap/mmagent/JUnitTestSuite.java deleted file mode 100644 index b8087a7..0000000 --- a/src/test/java/com/att/nsa/dmaap/mmagent/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.dmaap.mmagent; - -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({ CreateMirrorMakerTest.class, MirrorMakerTest.class, - UpdateMirrorMakerTest.class, UpdateWhiteListTest.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/dmaap/mmagent/MirrorMakerTest.java b/src/test/java/com/att/nsa/dmaap/mmagent/MirrorMakerTest.java deleted file mode 100644 index ebcb61f..0000000 --- a/src/test/java/com/att/nsa/dmaap/mmagent/MirrorMakerTest.java +++ /dev/null @@ -1,142 +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.dmaap.mmagent; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class MirrorMakerTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetStatus() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.getStatus(); - - assertTrue(true); - - } - - @Test - public void testSetStatus() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.setStatus("status"); - - assertTrue(true); - - } - - @Test - public void testGetName() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.getName(); - - assertTrue(true); - - } - - @Test - public void testSetName() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.setName("name"); - - assertTrue(true); - - } - - - @Test - public void testGetConsumer() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.getConsumer(); - - assertTrue(true); - - } - - @Test - public void testSetConsumer() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.setConsumer("consumer"); - - assertTrue(true); - - } - - @Test - public void testGetProducer() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.getProducer(); - - assertTrue(true); - - } - - @Test - public void testSetProducer() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.setProducer("producer"); - - assertTrue(true); - - } - - - @Test - public void testGetWhitelist() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.getWhitelist(); - - assertTrue(true); - - } - - @Test - public void testSetWhitelist() { - - MirrorMaker mMaker = new MirrorMaker(); - mMaker.setWhitelist("whitelist"); - - assertTrue(true); - - } - - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/mmagent/TestRunner.java b/src/test/java/com/att/nsa/dmaap/mmagent/TestRunner.java deleted file mode 100644 index 63b128d..0000000 --- a/src/test/java/com/att/nsa/dmaap/mmagent/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.dmaap.mmagent; - -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/dmaap/mmagent/UpdateMirrorMakerTest.java b/src/test/java/com/att/nsa/dmaap/mmagent/UpdateMirrorMakerTest.java deleted file mode 100644 index 4e66d22..0000000 --- a/src/test/java/com/att/nsa/dmaap/mmagent/UpdateMirrorMakerTest.java +++ /dev/null @@ -1,81 +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.dmaap.mmagent; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class UpdateMirrorMakerTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetUpdateMirrorMaker() { - - UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); - mMaker.getUpdateMirrorMaker(); - - assertTrue(true); - - } - - @Test - public void testSetUpdateMirrorMaker() { - - UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); - mMaker.setUpdateMirrorMaker(new MirrorMaker()); - - assertTrue(true); - - } - - @Test - public void testGetMessageID() { - - UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); - mMaker.getMessageID(); - - assertTrue(true); - - } - - @Test - public void testSetMessageID() { - - UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); - mMaker.setMessageID("messageID"); - - assertTrue(true); - - } - - - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/mmagent/UpdateWhiteListTest.java b/src/test/java/com/att/nsa/dmaap/mmagent/UpdateWhiteListTest.java deleted file mode 100644 index 4e6d07a..0000000 --- a/src/test/java/com/att/nsa/dmaap/mmagent/UpdateWhiteListTest.java +++ /dev/null @@ -1,85 +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.dmaap.mmagent; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class UpdateWhiteListTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetUpdateWhiteList() { - - UpdateWhiteList wList = new UpdateWhiteList(); - wList.getUpdateWhiteList(); - - assertTrue(true); - - } - - @Test - public void testSetUpdateWhiteList() { - - UpdateWhiteList wList = new UpdateWhiteList(); - wList.setUpdateWhiteList(new MirrorMaker()); - - assertTrue(true); - - } - - @Test - public void testGetMessageID() { - - UpdateWhiteList wList = new UpdateWhiteList(); - wList.getMessageID(); - - assertTrue(true); - - } - - @Test - public void testSetMessageID() { - - UpdateWhiteList wList = new UpdateWhiteList(); - wList.setMessageID("messageID"); - - assertTrue(true); - - } - - - - - - - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/service/AdminRestServiceTest.java b/src/test/java/com/att/nsa/dmaap/service/AdminRestServiceTest.java deleted file mode 100644 index 5a05a73..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/AdminRestServiceTest.java +++ /dev/null @@ -1,295 +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.dmaap.service; - -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.onap.dmaap.dmf.mr.CambriaApiException; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; - -import java.io.IOException; -import java.util.Enumeration; -import org.onap.dmaap.dmf.mr.service.AdminService; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.powermock.core.classloader.annotations.PrepareForTest; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ ServiceUtil.class }) -public class AdminRestServiceTest { - - @InjectMocks - AdminRestService adminRestService; - - @Mock - AdminService adminService; - - @Mock - DMaaPContext dmaapContext; - - @Mock - HttpServletRequest httpServReq; - @Mock - private HttpServletResponse response; - - @Mock - Enumeration headerNames; - @Mock - private DMaaPContext dmaaPContext; - @Mock - private ConfigurationReader configReader; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetConsumerCache() throws CambriaApiException, AccessDeniedException { - adminRestService.getConsumerCache(); - - } - - @Test - public void testGetConsumerCache_error() throws CambriaApiException, AccessDeniedException, IOException { - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new IOException("error")).when(adminService).showConsumerCache(dmaaPContext); - try { - adminRestService.getConsumerCache(); - } catch (CambriaApiException e) { - assertTrue(true); - } - - } - - @Test - public void testDropConsumerCache() throws CambriaApiException, AccessDeniedException { - adminRestService.dropConsumerCache(); - - } - - @Test - public void testDropConsumerCach_error() throws CambriaApiException, AccessDeniedException ,IOException{ - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new IOException("error")).when(adminService).dropConsumerCache(dmaaPContext); - try { - adminRestService.dropConsumerCache(); - } - catch (CambriaApiException e) { - assertTrue(true); - } - - - } - @Test - public void testDropConsumerCach_error1() throws CambriaApiException, AccessDeniedException,IOException { - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).dropConsumerCache(dmaaPContext); - try { - adminRestService.dropConsumerCache(); - } - catch (CambriaApiException e) { - assertTrue(true); - } - - - } - - @Test - public void testGetBlacklist() throws CambriaApiException, AccessDeniedException { - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeaderNames()).thenReturn(headerNames); - when(headerNames.nextElement()).thenReturn("key"); - when(httpServReq.getHeader("key")).thenReturn("value"); - - adminRestService.getBlacklist(); - - } - - //@Test - public void testGetBlacklist_error() throws CambriaApiException, AccessDeniedException,IOException { - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new IOException("error")).when(adminService).getBlacklist(dmaaPContext); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeaderNames()).thenReturn(headerNames); - when(headerNames.nextElement()).thenReturn("key"); - when(httpServReq.getHeader("key")).thenReturn("value"); - when(headerNames.hasMoreElements()).thenReturn(false); - try { - adminRestService.getBlacklist(); - } - catch (CambriaApiException e) { - assertTrue(true); - } - - } - - ////@Test - public void testGetBlacklist_error1() throws CambriaApiException, AccessDeniedException,IOException { - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).getBlacklist(dmaaPContext); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeaderNames()).thenReturn(headerNames); - when(headerNames.nextElement()).thenReturn("key"); - when(httpServReq.getHeader("key")).thenReturn("value"); - when(headerNames.hasMoreElements()).thenReturn(false); - try { - adminRestService.getBlacklist(); - } - catch (CambriaApiException e) { - assertTrue(true); - } - - } - - @Test - public void testAddToBlacklist() throws CambriaApiException, AccessDeniedException { - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - - adminRestService.addToBlacklist("120.120.120.120"); - - } - - @Test - public void testAddToBlacklist_error() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException { - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).addToBlacklist(dmaaPContext,"120.120.120.120"); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - try { - adminRestService.addToBlacklist("120.120.120.120"); - }catch (CambriaApiException e) { - assertTrue(true); - } - - } - - @Test - public void testAddToBlacklist_error1() throws CambriaApiException, AccessDeniedException,IOException, ConfigDbException { - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new IOException("error")).when(adminService).addToBlacklist(dmaaPContext,"120.120.120.120"); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - try { - adminRestService.addToBlacklist("120.120.120.120"); - }catch (CambriaApiException e) { - assertTrue(true); - } - - } - - @Test - public void testRemoveFromBlacklist() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException { - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - - adminRestService.removeFromBlacklist("120.120.120.120"); - - } - - @Test - public void testRemoveFromBlacklist_error() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException{ - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new IOException("error")).when(adminService).removeFromBlacklist(dmaaPContext,"120.120.120.120"); - - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - try { - - adminRestService.removeFromBlacklist("120.120.120.120"); - }catch (CambriaApiException e) { - assertTrue(true); - } - catch (AccessDeniedException e) { - assertTrue(true); - } - catch (ConfigDbException e) { - assertTrue(true); - } - - } - - @Test - public void testRemoveFromBlacklist_error1() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException { - - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).removeFromBlacklist(dmaaPContext,"120.120.120.120"); - - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - try { - - adminRestService.removeFromBlacklist("120.120.120.120"); - }catch (CambriaApiException e) { - assertTrue(true); - } - catch (AccessDeniedException e) { - assertTrue(true); - } - catch (ConfigDbException e) { - assertTrue(true); - } - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/service/ApiKeysRestServiceTest.java b/src/test/java/com/att/nsa/dmaap/service/ApiKeysRestServiceTest.java deleted file mode 100644 index c784f90..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/ApiKeysRestServiceTest.java +++ /dev/null @@ -1,232 +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.dmaap.service; - -import static org.junit.Assert.*; - -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; -import org.junit.runner.RunWith; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.ApiKeyBean; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.json.JSONException; - -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; - -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.onap.dmaap.dmf.mr.service.ApiKeysService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.db.NsaApiDb.KeyExistsException; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ ServiceUtil.class }) -public class ApiKeysRestServiceTest { - - @InjectMocks - private ApiKeysRestService service; - - @Mock - ApiKeysService apiKeyService; - - @Mock - DMaaPContext dmaapContext; - - @Mock - HttpServletRequest httpServReq; - @Mock - private HttpServletResponse response; - @Mock - private ConfigurationReader configReader; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetAllApiKeys() { - - try { - service.getAllApiKeys(); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testGetAllApiKeys_error() throws ConfigDbException, IOException { - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); - PowerMockito.doThrow(new IOException("error")).when(apiKeyService).getAllApiKeys(dmaapContext); - try { - service.getAllApiKeys(); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - assertTrue(true); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testGetApiKey() { - - try { - service.getApiKey("apikeyName"); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testGetApiKey_error() throws ConfigDbException, IOException { - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); - PowerMockito.doThrow(new IOException("error")).when(apiKeyService).getApiKey(dmaapContext, "apikeyName"); - - try { - service.getApiKey("apikeyName"); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - assertTrue(true); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testCreateApiKey() { - - try { - service.createApiKey(new ApiKeyBean("hs647a@att.com", "test apikey")); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testCreateApiKey_error() - throws CambriaApiException, JSONException, KeyExistsException, ConfigDbException, IOException { - - ApiKeyBean bean = new ApiKeyBean("test@onap.com", "test apikey"); - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); - PowerMockito.doThrow(new IOException("error")).when(apiKeyService).createApiKey(dmaapContext, bean); - - try { - service.createApiKey(bean); - } catch (CambriaApiException e) { - assertTrue(true); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testUpdateApiKey() { - - try { - service.updateApiKey("apikeyName", new ApiKeyBean("hs647a@att.com", "test apikey")); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testUpdateApiKey_error() throws CambriaApiException, JSONException, KeyExistsException, - ConfigDbException, IOException, AccessDeniedException { - - ApiKeyBean bean = new ApiKeyBean("test@onap.com", "test apikey"); - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); - PowerMockito.doThrow(new IOException("error")).when(apiKeyService).updateApiKey(dmaapContext, "apikeyName", - bean); - try { - service.updateApiKey("apikeyName", bean); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - - @Test - public void testDeleteApiKey() { - - try { - service.deleteApiKey("apikeyName"); - } catch (CambriaApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NullPointerException e) { - assertTrue(true); - } - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/service/EventsRestServiceTest.java b/src/test/java/com/att/nsa/dmaap/service/EventsRestServiceTest.java deleted file mode 100644 index 985d38f..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/EventsRestServiceTest.java +++ /dev/null @@ -1,328 +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.dmaap.service; - -import java.util.Date; - -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.Mockito; -import org.mockito.MockitoAnnotations; -import static org.mockito.Matchers.any; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.api.mockito.PowerMockito; -import static org.mockito.Mockito.when; - -import com.att.ajsc.beans.PropertiesMapBean; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.service.EventsService; -import com.att.nsa.configs.ConfigDbException; -import org.onap.dmaap.dmf.mr.utils.Utils; -import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; - -import javax.servlet.ServletInputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; - -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; -import org.onap.dmaap.dmf.mr.exception.ErrorResponse; -import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PropertiesMapBean.class }) -public class EventsRestServiceTest { - - @InjectMocks - EventsRestService eventsRestRestService; - - @Mock - private EventsService eventsService; - - @Mock - ErrorResponse errorResponse; - - @Mock - DMaaPContext dmaapContext; - - @Mock - InputStream iStream; - - @Mock - ServletInputStream servletInputStream; - - @Mock - HttpServletRequest request; - - @Mock - private DMaaPErrorMessages errorMessages; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetEvents() throws CambriaApiException { - - eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); - - } - - @Test - public void testGetEvents_error() { - - try { - PowerMockito.doThrow(new IOException()).when(eventsService).getEvents(any(), any(), - any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | UnavailableException | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(eventsService).getEvents(any(), any(), - any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | UnavailableException | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new TopicExistsException("error")).when(eventsService).getEvents(any(), - any(), any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | UnavailableException | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - } - - @Test(expected = TopicExistsException.class) - public void testGetEvents_TopicExistException() throws CambriaApiException, ConfigDbException, TopicExistsException, - UnavailableException, IOException, AccessDeniedException { - - Mockito.doThrow(new TopicExistsException("topic exists")).when(eventsService).getEvents(any(), - any(), any(), any()); - - eventsService.getEvents(dmaapContext, "topicName", "consumergroup", "consumerid"); - - } - - @Test(expected = DMaaPAccessDeniedException.class) - public void testGetEvents_DMaaPAccessDeniedException() throws CambriaApiException, ConfigDbException, - TopicExistsException, UnavailableException, IOException, AccessDeniedException { - - Mockito.doThrow(new DMaaPAccessDeniedException(errorResponse)).when(eventsService).getEvents(any(), - any(), any(), any()); - - eventsService.getEvents(dmaapContext, "topicName", "consumergroup", "consumerid"); - - } - - /* - * @Test(expected = DMaaPAccessDeniedException.class) public void - * testGetEvents_DMaaPAccessDeniedException() throws CambriaApiException, - * ConfigDbException, TopicExistsException, UnavailableException, - * IOException, AccessDeniedException { - * - * Mockito.doThrow(new - * DMaaPAccessDeniedException(errorResponse)).when(eventsService).getEvents( - * dmaapContext, "topicName", "consumergroup", "consumerid"); - * - * eventsService.getEvents(dmaapContext, "topicName", "consumergroup", - * "consumerid"); - * - * } - */ - - @Test - public void testPushEvents() throws CambriaApiException { - - eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); - - } - - @Test - public void testPushEvents_error() { - - try { - PowerMockito.doThrow(new IOException()).when(eventsService).pushEvents(any(), any(), any(), - any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | missingReqdSetting | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(eventsService).pushEvents(any(), any(), - any(), any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | missingReqdSetting | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new TopicExistsException("error")).when(eventsService).pushEvents(any(), - any(), any(), any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | missingReqdSetting | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - } - - @Test - public void testPushEvents_TopicExistException() throws CambriaApiException { - - eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); - - } - - @Test - public void tesTPushEventsWithTransaction() throws CambriaApiException, IOException { - when(request.getInputStream()).thenReturn(servletInputStream); - eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); - - } - - @Test - public void tesTPushEventsWithTransaction_error() throws IOException { - when(request.getInputStream()).thenReturn(servletInputStream); - ServletInputStream stream = request.getInputStream(); - - try { - PowerMockito.doThrow(new TopicExistsException("error")).when(eventsService).pushEvents(any(), - any(), any(), any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | missingReqdSetting | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(eventsService).pushEvents(any(),any(), - any(), any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | missingReqdSetting | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new IOException()).when(eventsService).pushEvents(any(), any(), any(), - any(), any()); - } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException - | missingReqdSetting | IOException excp) { - assertTrue(false); - } catch (CambriaApiException e) { - assertTrue(false); - } - - try { - eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - } - -} diff --git a/src/test/java/com/att/nsa/dmaap/service/JUnitTestSuite.java b/src/test/java/com/att/nsa/dmaap/service/JUnitTestSuite.java deleted file mode 100644 index b01a33e..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/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.dmaap.service; - -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({ AdminRestServiceTest.class, ApiKeysRestServiceTest.class, - EventsRestServiceTest.class, MetricsRestServiceTest.class, MMRestServiceTest.class, - TopicRestServiceTest.class, TransactionRestServiceTest.class, UIRestServicesTest.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/dmaap/service/MMRestServiceTest.java b/src/test/java/com/att/nsa/dmaap/service/MMRestServiceTest.java deleted file mode 100644 index 29d6bc4..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/MMRestServiceTest.java +++ /dev/null @@ -1,384 +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.dmaap.service; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyString; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; - -//import static org.mockito.Matchers.anyString; -//import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.io.InputStream; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.After; -import org.junit.Assert; -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.ajsc.beans.PropertiesMapBean; -import com.att.ajsc.filemonitor.AJSCPropertiesMap; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker; -import org.onap.dmaap.dmf.mr.constants.CambriaConstants; -import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; -import org.onap.dmaap.dmf.mr.metabroker.Topic; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; -import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticator; -import org.onap.dmaap.dmf.mr.service.MMService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.dmaap.mmagent.CreateMirrorMaker; -import com.att.nsa.dmaap.mmagent.MirrorMaker; -import com.att.nsa.dmaap.mmagent.UpdateMirrorMaker; -import com.att.nsa.security.NsaAcl; -import com.att.nsa.security.NsaApiKey; -import com.att.nsa.security.db.simple.NsaSimpleApiKey; -import com.google.gson.Gson; - -//@RunWith(MockitoJUnitRunner.class) -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PropertiesMapBean.class, AJSCPropertiesMap.class }) -public class MMRestServiceTest { - - @InjectMocks - MMRestService mmRestService; - - @Mock - private MMService mmservice; - - @Mock - CreateMirrorMaker cMirroMaker; - - @Mock - UpdateMirrorMaker uMirroMaker; - - private TopicRestService service = new TopicRestService(); - @Mock - private DMaaPErrorMessages errorMessages; - - @Mock - DMaaPContext dmaapContext; - - @Mock - ConfigurationReader configReader; - - @Mock - ServletOutputStream oStream; - - @Mock - DMaaPAuthenticator dmaaPAuthenticator; - - @Mock - MirrorMaker mMaker; - - @Mock - DMaaPAAFAuthenticator dmaapAAFauthenticator; - - @Mock - DMaaPAAFAuthenticatorImpl impl; - - @Mock - NsaApiKey user; - - @Mock - NsaSimpleApiKey nsaSimpleApiKey; - - @Mock - HttpServletRequest httpServReq; - - @Mock - HttpServletResponse httpServRes; - - @Mock - InputStream iStream; - - @Mock - DMaaPKafkaMetaBroker dmaapKafkaMetaBroker; - - @Mock - Topic createdTopic; - - @Mock - NsaAcl nsaAcl; - - @Mock - JSONObject jsonObj; - - @Mock - JSONArray jsonArray; - - @Before - public void setUp() throws Exception { - - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCallCreateMirrorMaker() throws Exception { - prepareForTestCommon(); - - // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { - // name:\"test\", consumer:\"test\", producer:\"test\", - // whitelist:\"test\",status:\"test\" }}"; - String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); - - } - @Test - public void testCallCreateMirrorMaker_error4() throws Exception { - prepareForTestCommon(); - - // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { - // name:\"test\", consumer:\"test\", producer:\"test\", - // whitelist:\"test\",status:\"test\" }}"; - String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test@#\", consumer:\"test\", producer:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); - - } - @Test - public void testCallCreateMirrorMaker_3() throws Exception { - prepareForTestCommon(); - - // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { - // name:\"test\", consumer:\"test\", producer:\"test\", - // whitelist:\"test\",status:\"test\" }}"; - String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"\", consumer:\"test\", producer:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); - - } - @Test - public void testCallCreateMirrorMaker_error2() throws Exception { - prepareForTestCommon(); - - // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { - // name:\"test\", consumer:\"test\", producer:\"test\", - // whitelist:\"test\",status:\"test\" }}"; - String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\",whitelist:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); - - } - - @Test - public void testCallCreateMirrorMaker_error1() throws Exception { - prepareForTestCommon(); - - // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { - // name:\"test\", consumer:\"test\", producer:\"test\", - // whitelist:\"test\",status:\"test\" }}"; - String sampleJson = "{ messageID:\"test\"}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); - - } - - @Test - public void testCallListAllMirrorMaker() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callListAllMirrorMaker(inputSteam); - assertTrue(true); - } - - @Test - public void testCallUpdateMirrorMaker() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); - } - - @Test - public void testCallUpdateMirrorMaker_error1() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ messageID:\"test@1\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); - } - @Test - public void testCallUpdateMirrorMaker_error2() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"\", consumer:\"test\", producer:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); - } - @Test - public void testCallUpdateMirrorMaker_error3() throws Exception{ - prepareForTestCommon(); - - String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); - } - @Test - public void testCallUpdateMirrorMaker_error4() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ messageID:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); - } - - @Test - public void testCallDeleteMirrorMaker() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ messageID:\"test\", deleteMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callDeleteMirrorMaker(inputSteam); - assertTrue(true); - } - - @Test - public void testListWhiteList() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ name:\"test\", namespace:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.listWhiteList(inputSteam); - assertTrue(true); - } - - @Test - public void testCreateWhiteList() throws Exception { - prepareForTestCommon(); - String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - - mmRestService.createWhiteList(inputSteam); - assertTrue(true); - } - - @Test - public void testDeleteWhiteList() throws Exception { - prepareForTestCommon(); - - String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; - InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.deleteWhiteList(inputSteam); - assertTrue(true); - } - - private void prepareForTestCommon() throws Exception { - Assert.assertNotNull(mmRestService); - PowerMockito.when(dmaapContext.getRequest()).thenReturn(httpServReq); - PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin")).thenReturn(true); - PowerMockito.when(httpServReq.isUserInRole("admin")).thenReturn(true); - - PowerMockito.mockStatic(AJSCPropertiesMap.class); - - assertTrue(true); - - PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf")) - .thenReturn("admin"); - PowerMockito - .when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf.create")) - .thenReturn("aafcreate"); - - PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf")) - .thenReturn("admin"); - - PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout")) - .thenReturn("100"); - - PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic")) - .thenReturn("mirrormaker.topic"); - - PowerMockito - .when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup")) - .thenReturn("mirrormaker.consumergroup"); - - PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid")) - .thenReturn("mirrormaker.consumerid"); - - PowerMockito.when(dmaapContext.getRequest()).thenReturn(httpServReq); - - PowerMockito.when(httpServReq.isUserInRole("admin")).thenReturn(true); - - // PowerMockito.when(httpServReq.getHeader("Authorization")).thenReturn("Admin"); - PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin.aaf")).thenReturn(true); - PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin")).thenReturn(true); - PowerMockito.when(httpServReq.getHeader("Authorization")).thenReturn("Admin"); - PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin")).thenReturn(true); - PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "aafcreatetest|create")) - .thenReturn(true); - - PowerMockito.when(cMirroMaker.getCreateMirrorMaker()).thenReturn(mMaker); - - PowerMockito.when(mMaker.getName()).thenReturn("mirroMakerName"); - PowerMockito.when(dmaapContext.getConfigReader()).thenReturn(configReader); - PowerMockito.when(dmaapContext.getRequest()).thenReturn(httpServReq); - PowerMockito.when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); - - PowerMockito.when(dmaapContext.getResponse()).thenReturn(httpServRes); - PowerMockito.when(configReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker); - PowerMockito.when(httpServReq.getMethod()).thenReturn("HEAD"); - - PowerMockito.when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); - } - -} diff --git a/src/test/java/com/att/nsa/dmaap/service/MetricsRestServiceTest.java b/src/test/java/com/att/nsa/dmaap/service/MetricsRestServiceTest.java deleted file mode 100644 index 5f0669c..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/MetricsRestServiceTest.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.dmaap.service; - -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.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.ajsc.beans.PropertiesMapBean; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.service.MetricsService; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PropertiesMapBean.class }) -public class MetricsRestServiceTest { - - @InjectMocks - MetricsRestService metricsRestService; - - @Mock - private MetricsService metricsService; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetMetrics() throws CambriaApiException { - - metricsRestService.getMetrics(); - - } - - @Test - public void testGetMetricsByName() throws CambriaApiException { - - metricsRestService.getMetricsByName("metricsName"); - - } - - - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/service/TestRunner.java b/src/test/java/com/att/nsa/dmaap/service/TestRunner.java deleted file mode 100644 index 26a88bb..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/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.dmaap.service; - -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/dmaap/service/TopicRestServiceTest.java b/src/test/java/com/att/nsa/dmaap/service/TopicRestServiceTest.java deleted file mode 100644 index c805fcb..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/TopicRestServiceTest.java +++ /dev/null @@ -1,838 +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.dmaap.service; - -import static org.junit.Assert.*; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ConcurrentModificationException; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.After; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Assert; -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.ajsc.beans.PropertiesMapBean; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker; -import org.onap.dmaap.dmf.mr.beans.TopicBean; -import org.onap.dmaap.dmf.mr.constants.CambriaConstants; -import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; -import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; -import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; -import org.onap.dmaap.dmf.mr.metabroker.Topic; -import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; -import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticator; -import org.onap.dmaap.dmf.mr.service.TopicService; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.NsaAcl; -import com.att.nsa.security.NsaApiKey; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; -import com.att.nsa.security.db.simple.NsaSimpleApiKey; - -//@RunWith(MockitoJUnitRunner.class) -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PropertiesMapBean.class }) -public class TopicRestServiceTest { - - @InjectMocks - TopicRestService topicRestService; - - @Mock - private TopicService topicService; - - private TopicRestService service = new TopicRestService(); - @Mock - private DMaaPErrorMessages errorMessages; - - @Mock - DMaaPContext dmaapContext; - - @Mock - ConfigurationReader configReader; - - @Mock - ServletOutputStream oStream; - - @Mock - DMaaPAuthenticator dmaaPAuthenticator; - - @Mock - DMaaPAAFAuthenticator dmaapAAFauthenticator; - @Mock - NsaApiKey user; - - @Mock - NsaSimpleApiKey nsaSimpleApiKey; - - @Mock - HttpServletRequest httpServReq; - - @Mock - HttpServletResponse httpServRes; - - @Mock - DMaaPKafkaMetaBroker dmaapKafkaMetaBroker; - - @Mock - Topic createdTopic; - - @Mock - NsaAcl nsaAcl; - - @Mock - JSONObject jsonObj; - - @Mock - JSONArray jsonArray; - - @Before - public void setUp() throws Exception { - - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { - } - - @Test(expected = DMaaPAccessDeniedException.class) - public void testGetTopics() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, JSONException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) - .thenReturn("namespace"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - when(configReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker); - when(httpServReq.getMethod()).thenReturn("HEAD"); - - when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); - - topicRestService.getTopics(); - } - - @Test - public void testGetTopics_nullAuth() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, JSONException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) - .thenReturn("namespace"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn(null); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - String perms = "namespace" + "|" + "*" + "|" + "view"; - when(dmaapAAFauthenticator.aafAuthentication(httpServReq, perms)).thenReturn(true); - - when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); - - topicRestService.getTopics(); - } - - @Test - public void testGetTopics_error() throws DMaaPAccessDeniedException, TopicExistsException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) - .thenReturn("namespace"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn(null); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - String perms = "namespace" + "|" + "*" + "|" + "view"; - when(dmaapAAFauthenticator.aafAuthentication(httpServReq, perms)).thenReturn(true); - - when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); - try { - PowerMockito.doThrow(new IOException()).when(topicService).getTopics(any()); - } catch (JSONException | ConfigDbException | IOException excp) { - assertTrue(false); - } - - try { - topicRestService.getTopics(); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test(expected = DMaaPAccessDeniedException.class) - public void testGetAllTopics() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, JSONException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) - .thenReturn("namespace"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - - topicRestService.getAllTopics(); - } - - @Test - public void testGetAllTopics_nullAuth() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, JSONException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) - .thenReturn("namespace"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn(null); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - - topicRestService.getAllTopics(); - } - - @Test - public void testGetAllTopics_error() throws DMaaPAccessDeniedException, TopicExistsException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) - .thenReturn("namespace"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn(null); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).getAllTopics(any()); - } catch (JSONException | ConfigDbException | IOException excp) { - assertTrue(false); - } - - try { - topicRestService.getAllTopics(); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test(expected = DMaaPAccessDeniedException.class) - public void testGetTopic() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, JSONException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "enforced.topic.name.AAF")) - .thenReturn("enfTopicName"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - - topicRestService.getTopic("topicName"); - } - - @Test - public void testGetTopic_nullAuth() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, JSONException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "enforced.topic.name.AAF")) - .thenReturn("enfTopicName"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn(null); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - - topicRestService.getTopic("topicName"); - } - - @Test - public void testGetTopic_error() throws DMaaPAccessDeniedException, ConfigDbException { - - Assert.assertNotNull(topicRestService); - - PowerMockito.mockStatic(PropertiesMapBean.class); - - assertTrue(true); - when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "enforced.topic.name.AAF")) - .thenReturn("enfTopicName"); - - PowerMockito.mockStatic(DMaaPResponseBuilder.class); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeader("Authorization")).thenReturn(null); - - when(dmaapContext.getResponse()).thenReturn(httpServRes); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).getTopic(any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException excp) { - assertTrue(false); - } - - try { - topicRestService.getTopic("topicName"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test - public void testCreateTopic() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.createTopic(topicBean); - } - - @Test - public void testCreateTopic_error() { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).createTopic(any(), any()); - } catch (TopicExistsException | IOException | AccessDeniedException | DMaaPAccessDeniedException excp) { - assertTrue(false); - } catch (CambriaApiException excp) { - assertTrue(false); - } - - try { - topicRestService.createTopic(topicBean); - } catch (CambriaApiException excp) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new TopicExistsException("error")).when(topicService).createTopic(any(), any()); - } catch (TopicExistsException | IOException | AccessDeniedException | DMaaPAccessDeniedException excp) { - assertTrue(false); - } catch (CambriaApiException excp) { - assertTrue(false); - } - - try { - topicRestService.createTopic(topicBean); - } catch (CambriaApiException excp) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(topicService).createTopic(any(), any()); - } catch (TopicExistsException | IOException | AccessDeniedException | DMaaPAccessDeniedException excp) { - assertTrue(false); - } catch (CambriaApiException excp) { - assertTrue(false); - } - - try { - topicRestService.createTopic(topicBean); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test - public void testDeleteTopic() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.deleteTopic("enfTopicNamePlusExtra"); - } - - @Test - public void testDeleteTopic_error() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).deleteTopic(any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.deleteTopic("enfTopicNamePlusExtra"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(topicService).deleteTopic(any(), - any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.deleteTopic("enfTopicNamePlusExtra"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test - public void testGetPublishersByTopicName() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.getPublishersByTopicName("enfTopicNamePlusExtra"); - } - - @Test - public void testGetPublishersByTopicName_error() { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).getPublishersByTopicName(any(), - any()); - } catch (TopicExistsException | ConfigDbException | IOException e) { - assertTrue(false); - } - - try { - topicRestService.getPublishersByTopicName("enfTopicNamePlusExtra"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test - public void testPermitPublisherForTopic() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(any())).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.permitPublisherForTopic("enfTopicNamePlusExtra", "producerID"); - } - - @Test - public void testPermitPublisherForTopic_error() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).permitPublisherForTopic(any(), - any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.permitPublisherForTopic("enfTopicNamePlusExtra", "producerID"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(topicService).permitPublisherForTopic(any(), - any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.permitPublisherForTopic("enfTopicNamePlusExtra", "producerID"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test - public void testDenyPublisherForTopic() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.denyPublisherForTopic("enfTopicNamePlusExtra", "producerID"); - } - - @Test - public void testDenyPublisherForTopic_error() - throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).denyPublisherForTopic(any(), - any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.denyPublisherForTopic("enfTopicNamePlusExtra", "producerID"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(topicService).denyPublisherForTopic(any(), - any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.denyPublisherForTopic("enfTopicNamePlusExtra", "producerID"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - - } - - @Test - public void testGetConsumersByTopicName() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, AccessDeniedException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.getConsumersByTopicName("enfTopicNamePlusExtra"); - } - - @Test - public void testGetConsumersByTopicName_error() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, AccessDeniedException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).getConsumersByTopicName(any(), - any()); - } catch (TopicExistsException | ConfigDbException | IOException excp) { - assertTrue(false); - } - - try { - topicRestService.getConsumersByTopicName("enfTopicNamePlusExtra"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test - public void testPermitConsumerForTopic() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, AccessDeniedException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(any())).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.permitConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); - } - - @Test - public void testPermitConsumerForTopic_error() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, AccessDeniedException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(any())).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).permitConsumerForTopic(any(), - any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.permitConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - - @Test - public void testPermitConsumerForTopicWithException() throws DMaaPAccessDeniedException, CambriaApiException, - IOException, TopicExistsException, AccessDeniedException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.permitConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); - } - - @Test - public void testDenyConsumerForTopic() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, AccessDeniedException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - topicRestService.denyConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); - } - - @Test - public void testDenyConsumerForTopic_error() throws DMaaPAccessDeniedException, CambriaApiException, IOException, - TopicExistsException, AccessDeniedException { - - Assert.assertNotNull(topicRestService); - - when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); - when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); - when(dmaapContext.getConfigReader()).thenReturn(configReader); - - TopicBean topicBean = new TopicBean(); - topicBean.setTopicName("enfTopicNamePlusExtra"); - - try { - PowerMockito.doThrow(new IOException()).when(topicService).denyConsumerForTopic(any(), - any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.denyConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - - try { - PowerMockito.doThrow(new AccessDeniedException()).when(topicService).denyConsumerForTopic(any(), - any(), any()); - } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException - | DMaaPAccessDeniedException excp) { - assertTrue(false); - } - - try { - topicRestService.denyConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); - } catch (CambriaApiException excp) { - assertTrue(true); - } - } - -} diff --git a/src/test/java/com/att/nsa/dmaap/service/TransactionRestServiceTest.java b/src/test/java/com/att/nsa/dmaap/service/TransactionRestServiceTest.java deleted file mode 100644 index a5abb75..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/TransactionRestServiceTest.java +++ /dev/null @@ -1,123 +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.dmaap.service; - -import static org.junit.Assert.*; - -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; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.ajsc.beans.PropertiesMapBean; -import org.onap.dmaap.dmf.mr.CambriaApiException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.service.EventsService; -import org.onap.dmaap.dmf.mr.service.TransactionService; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; -import com.att.aft.dme2.internal.jettison.json.JSONException; -import org.powermock.api.mockito.PowerMockito; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PropertiesMapBean.class }) -public class TransactionRestServiceTest { - - @InjectMocks - TransactionRestService transactionRestService; - - @Mock - private TransactionService transactionService; - - @Mock - DMaaPContext dmaapContext; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetAllTransactionObjs() throws CambriaApiException { - - transactionRestService.getAllTransactionObjs(); - assertTrue(true); - - } - - @Test - public void testGetTransactionObj() throws CambriaApiException { - - transactionRestService.getTransactionObj("transactionId"); - assertTrue(true); - - } - - @Test - public void testGetAllTransactionObjsError() throws CambriaApiException { - - try { - PowerMockito.doThrow(new IOException()).when(transactionService).getAllTransactionObjs(dmaapContext); - } catch (ConfigDbException | IOException e) { - assertTrue(false); - } - - try { - transactionRestService.getAllTransactionObjs(); - } catch (CambriaApiException e) { - assertTrue(true); - } - - } - - @Test - public void testGetTransactionObjError() { - - try { - PowerMockito.doThrow(new IOException()).when(transactionService).getTransactionObj(dmaapContext, - "transactionId"); - } catch (ConfigDbException | JSONException | IOException e) { - assertTrue(false); - } - - try { - transactionRestService.getTransactionObj("transactionId"); - } catch (CambriaApiException e) { - assertTrue(true); - } - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/service/UIRestServicesTest.java b/src/test/java/com/att/nsa/dmaap/service/UIRestServicesTest.java deleted file mode 100644 index ea6535a..0000000 --- a/src/test/java/com/att/nsa/dmaap/service/UIRestServicesTest.java +++ /dev/null @@ -1,142 +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.dmaap.service; - -import static org.junit.Assert.*; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.onap.dmaap.dmf.mr.CambriaApiException; -import com.att.nsa.configs.ConfigDbException; -import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; - -public class UIRestServicesTest { - - private UIRestServices service = null; - - @Before - public void setUp() throws Exception { - service = new UIRestServices(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testHello() { - - try { - service.hello(); - } catch (NullPointerException e) { - assertTrue(true); - } - assertTrue(true); - } - - @Test - public void testGetApiKeysTable() { - - try { - service.getApiKeysTable(); - } catch (NullPointerException e) { - assertTrue(true); - } - assertTrue(true); - } - - - @Test - public void testGetApiKey() { - - try { - service.getApiKey("apikey"); - } catch (NullPointerException e) { - assertTrue(true); - } - assertTrue(true); - } - - @Test - public void testGetTopicsTable() { - - try { - service.getTopicsTable(); - } catch (NullPointerException e) { - assertTrue(true); - } - assertTrue(true); - } - - @Test - public void testGetTopic() { - - try { - service.getTopic("topicName"); - } catch (NullPointerException e) { - assertTrue(true); - } - assertTrue(true); - } - - @Test - public void testGetDmaapContext() { - Class clazz = null; - Method method = null; - try { - clazz = Class.forName("UIRestServices"); - Object obj = clazz.newInstance(); - method = clazz.getDeclaredMethod("getDmaapContext", null); - method.setAccessible(true); - method.invoke(obj, null); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - } - - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/tools/ConfigToolContextTest.java b/src/test/java/com/att/nsa/dmaap/tools/ConfigToolContextTest.java deleted file mode 100644 index 87da0d2..0000000 --- a/src/test/java/com/att/nsa/dmaap/tools/ConfigToolContextTest.java +++ /dev/null @@ -1,86 +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.dmaap.tools; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ConfigToolContextTest { - - private ConfigToolContext context; - @Before - public void setUp() throws Exception { - context = new ConfigToolContext(null, "connStr", null); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testRequestShutdown() { - - context.requestShutdown(); - - assertTrue(true); - - } - - @Test - public void testShouldContinue() { - - context.shouldContinue(); - - assertTrue(true); - - } - - @Test - public void testGetDb() { - - context.getDb(); - - assertTrue(true); - - } - - @Test - public void testGetMetrics() { - - context.getMetrics(); - - assertTrue(true); - - } - - @Test - public void testGetConnectionString() { - - context.getConnectionString(); - - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/tools/ConfigToolTest.java b/src/test/java/com/att/nsa/dmaap/tools/ConfigToolTest.java deleted file mode 100644 index 39a312d..0000000 --- a/src/test/java/com/att/nsa/dmaap/tools/ConfigToolTest.java +++ /dev/null @@ -1,523 +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.dmaap.tools; - -import static org.junit.Assert.*; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ConfigToolTest { - - private String[] parts = new String[5]; - - @Before - public void setUp() throws Exception { - - for (int i = 0; i < parts.length; i++) { - parts[i] = "string" + (i + 1); - } - } - - @After - public void tearDown() throws Exception { - } - - public void callMethodViaReflection(String outer, String inner, String methodName, Object... args) { - - String foreNameString = outer + "$" + inner; - Object parent = new ConfigTool(); - - Class innerClass; - try { - innerClass = Class.forName(foreNameString); - Constructor constructor = innerClass.getDeclaredConstructor(ConfigTool.class); - constructor.setAccessible(true); - Object child = constructor.newInstance(parent); - - // invoking method on inner class object - Method method = innerClass.getDeclaredMethod(methodName, null); - method.setAccessible(true);// in case of unaccessible method - method.invoke(child, args); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testGetMatches() { - - callMethodViaReflection("ConfigTool", "ListTopicCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - callMethodViaReflection("ConfigTool", "ListTopicCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute() { - - callMethodViaReflection("ConfigTool", "ListTopicCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp() { - - callMethodViaReflection("ConfigTool", "ListTopicCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches2() { - - callMethodViaReflection("ConfigTool", "WriteTopicCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady2() { - - callMethodViaReflection("ConfigTool", "WriteTopicCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute2() { - - callMethodViaReflection("ConfigTool", "WriteTopicCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp2() { - - callMethodViaReflection("ConfigTool", "WriteTopicCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches3() { - - callMethodViaReflection("ConfigTool", "ReadTopicCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady3() { - - callMethodViaReflection("ConfigTool", "ReadTopicCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute3() { - - callMethodViaReflection("ConfigTool", "ReadTopicCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp3() { - - callMethodViaReflection("ConfigTool", "ReadTopicCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches4() { - - callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady4() { - - callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute4() { - - callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp4() { - - callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches5() { - - callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady5() { - - callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute5() { - - callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp5() { - - callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches6() { - - callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady6() { - - callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute6() { - - callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp6() { - - callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches7() { - - callMethodViaReflection("ConfigTool", "PutApiCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady7() { - - callMethodViaReflection("ConfigTool", "PutApiCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute7() { - - callMethodViaReflection("ConfigTool", "PutApiCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp7() { - - callMethodViaReflection("ConfigTool", "PutApiCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches8() { - - callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady8() { - - callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute8() { - - callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp8() { - - callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches9() { - - callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady9() { - - callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute9() { - - callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp9() { - - callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches10() { - - callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady10() { - - callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute10() { - - callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp10() { - - callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches11() { - - callMethodViaReflection("ConfigTool", "NodeFetchCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady11() { - - callMethodViaReflection("ConfigTool", "NodeFetchCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute11() { - - callMethodViaReflection("ConfigTool", "NodeFetchCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp11() { - - callMethodViaReflection("ConfigTool", "NodeFetchCommand", "displayHelp", null); - - assertTrue(true); - - } - - @Test - public void testGetMatches12() { - - callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "getMatches"); - - assertTrue(true); - - } - - @Test - public void testCheckReady12() { - - callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "checkReady", null); - - assertTrue(true); - - } - - @Test - public void testExecute12() { - - callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "execute", parts, null, null); - - assertTrue(true); - - } - - @Test - public void testDisplayHelp12() { - - callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "displayHelp", null); - - assertTrue(true); - - } -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/tools/JUnitTestSuite.java b/src/test/java/com/att/nsa/dmaap/tools/JUnitTestSuite.java deleted file mode 100644 index c9b4427..0000000 --- a/src/test/java/com/att/nsa/dmaap/tools/JUnitTestSuite.java +++ /dev/null @@ -1,42 +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.dmaap.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({ ConfigToolTest.class, ConfigToolContextTest.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/dmaap/tools/TestRunner.java b/src/test/java/com/att/nsa/dmaap/tools/TestRunner.java deleted file mode 100644 index 5c9387a..0000000 --- a/src/test/java/com/att/nsa/dmaap/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.dmaap.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/dmaap/util/ContentLengthInterceptorTest.java b/src/test/java/com/att/nsa/dmaap/util/ContentLengthInterceptorTest.java deleted file mode 100644 index 2fe06a8..0000000 --- a/src/test/java/com/att/nsa/dmaap/util/ContentLengthInterceptorTest.java +++ /dev/null @@ -1,93 +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.dmaap.util; - -import static org.junit.Assert.assertTrue; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -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.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ System.class }) -public class ContentLengthInterceptorTest { - @InjectMocks - ContentLengthInterceptor interceptor = null; - - @Mock - Map map; - - @Mock - HttpServletRequest req; - - @Mock - HttpServletResponse res; - - @Before - public void setUp() throws Exception { - // interceptor = new ContentLengthInterceptor(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAllowOrReject() throws Exception { - PowerMockito.when(req.getHeader("Transfer-Encoding")).thenReturn("UTF-8"); - PowerMockito.when(req.getHeader("Content-Length")).thenReturn("1027"); - - interceptor.allowOrReject(req, res, map); - assertTrue(true); - } - - //@Test(expected = NullPointerException.class) - public void testAllowOrRejectWithException() throws Exception { - PowerMockito.when(req.getHeader("Transfer-Encoding")).thenThrow(new NumberFormatException()); - interceptor.allowOrReject(req, res, map); - assertTrue(true); - } - - - @Test - public void testGetDefLength() { - interceptor.getDefLength(); - assertTrue(true); - } - - @Test - public void testSetDefLength() { - interceptor.setDefLength("defLength"); - assertTrue(true); - - } -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/util/DMaaPAuthFilterTest.java b/src/test/java/com/att/nsa/dmaap/util/DMaaPAuthFilterTest.java deleted file mode 100644 index dc59f9c..0000000 --- a/src/test/java/com/att/nsa/dmaap/util/DMaaPAuthFilterTest.java +++ /dev/null @@ -1,100 +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.dmaap.util; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - -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.ajsc.beans.PropertiesMapBean; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PropertiesMapBean.class, DMaaPResponseCode.class }) -public class DMaaPAuthFilterTest { - - @InjectMocks - DMaaPAuthFilter filter; - - @Mock - HttpServletRequest req; - - @Mock - ServletResponse res; - - @Mock - FilterChain chain; - - @Mock - DMaaPContext dmaapContext; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { - } - - //@Test - public void testDoFilter() throws IOException, ServletException { - - PowerMockito.when(dmaapContext.getRequest()).thenReturn(req); - PowerMockito.when(req.getHeader("Authorization")).thenReturn("Authorization"); - // when(dmaapContext.getResponse()).thenReturn(res); - filter.doFilter(req, res, chain); - assertTrue(true); - - } - - //@Test - public void testDoFilter_nullAuth() throws IOException, ServletException { - - PowerMockito.when(dmaapContext.getRequest()).thenReturn(req); - PowerMockito.when(req.getHeader("Authorization")).thenReturn("Authorization"); - - // when(dmaapContext.getResponse()).thenReturn(res); - filter.doFilter(req, res, chain); - assertTrue(true); - - } - - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/util/JUnitTestSuite.java b/src/test/java/com/att/nsa/dmaap/util/JUnitTestSuite.java deleted file mode 100644 index 17a6bad..0000000 --- a/src/test/java/com/att/nsa/dmaap/util/JUnitTestSuite.java +++ /dev/null @@ -1,42 +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.dmaap.util; - -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({ ContentLengthInterceptorTest.class, DMaaPAuthFilterTest.class, ServicePropertiesMapBeanTest.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/dmaap/util/ServicePropertiesMapBeanTest.java b/src/test/java/com/att/nsa/dmaap/util/ServicePropertiesMapBeanTest.java deleted file mode 100644 index da3eaf0..0000000 --- a/src/test/java/com/att/nsa/dmaap/util/ServicePropertiesMapBeanTest.java +++ /dev/null @@ -1,53 +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.dmaap.util; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ServicePropertiesMapBeanTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetProperty() { - - try { - ServicePropertiesMapBean.getProperty(null, null); - } catch (Exception e) { - e.printStackTrace(); - } - - assertTrue(true); - - } - -} \ No newline at end of file diff --git a/src/test/java/com/att/nsa/dmaap/util/TestRunner.java b/src/test/java/com/att/nsa/dmaap/util/TestRunner.java deleted file mode 100644 index d0bec42..0000000 --- a/src/test/java/com/att/nsa/dmaap/util/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.dmaap.util; - -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/DMaaPCambriaExceptionMapperTest.java b/src/test/java/org/onap/dmaap/DMaaPCambriaExceptionMapperTest.java new file mode 100644 index 0000000..a66da07 --- /dev/null +++ b/src/test/java/org/onap/dmaap/DMaaPCambriaExceptionMapperTest.java @@ -0,0 +1,86 @@ +/*- + * ============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; + +import static org.junit.Assert.assertTrue; + +import org.json.JSONObject; +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.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +@RunWith(PowerMockRunner.class) +public class DMaaPCambriaExceptionMapperTest { + + @InjectMocks + DMaaPCambriaExceptionMapper mapper; + + @Mock + private ErrorResponse errRes; + + @Mock + private DMaaPErrorMessages msgs; + + @Mock + CambriaApiException exc; + + @Mock + JSONObject json; + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToResponse() { + try { + mapper.toResponse(null); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + + @Test + public void testToResponseCambriaApiException2() { + PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); + try { + mapper.toResponse(new CambriaApiException(404,"Not found")); + } catch (NullPointerException e) { + assertTrue(true); + } + assertTrue(true); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/DMaaPWebExceptionMapperTest.java b/src/test/java/org/onap/dmaap/DMaaPWebExceptionMapperTest.java new file mode 100644 index 0000000..78f67c2 --- /dev/null +++ b/src/test/java/org/onap/dmaap/DMaaPWebExceptionMapperTest.java @@ -0,0 +1,142 @@ +/*- + * ============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; + +import static org.junit.Assert.*; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.NotAllowedException; +import javax.ws.rs.NotAuthorizedException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.ServiceUnavailableException; + +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.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; + +@RunWith(PowerMockRunner.class) +public class DMaaPWebExceptionMapperTest { + + @InjectMocks + DMaaPWebExceptionMapper mapper; + + @Mock + DMaaPErrorMessages msgs; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToResponse() { + + try { + mapper.toResponse(null); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testToResponseNotFoundException() { + PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); + try { + mapper.toResponse(new NotFoundException()); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testToResponseInternalServerErrorException() { + PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); + try { + mapper.toResponse(new InternalServerErrorException()); + + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testToResponseNotAuthorizedException() { + PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); + try { + mapper.toResponse(new NotAuthorizedException("Error", "Error")); + + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testToResponseBadRequestException() { + PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); + try { + mapper.toResponse(new BadRequestException()); + + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testToResponseNotAllowedException() { + PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); + try { + mapper.toResponse(new NotAllowedException("Not Allowed")); + + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testToResponseServiceUnavailableException() { + PowerMockito.when(msgs.getNotFound()).thenReturn("Not found"); + try { + mapper.toResponse(new ServiceUnavailableException()); + + } catch (NullPointerException e) { + assertTrue(true); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/DummyTest.java b/src/test/java/org/onap/dmaap/DummyTest.java new file mode 100644 index 0000000..8b01f94 --- /dev/null +++ b/src/test/java/org/onap/dmaap/DummyTest.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * ============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; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class DummyTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + assertTrue("Dummy test case", true); + } + +} diff --git a/src/test/java/org/onap/dmaap/HelloWorldTest.java b/src/test/java/org/onap/dmaap/HelloWorldTest.java new file mode 100644 index 0000000..0067b8f --- /dev/null +++ b/src/test/java/org/onap/dmaap/HelloWorldTest.java @@ -0,0 +1,52 @@ +/*- + * ============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; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class HelloWorldTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToResponse() { + + HelloWorld hello = new HelloWorld(); + + try { + hello.speak(null); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/JUnitTestSuite.java new file mode 100644 index 0000000..d20d0d6 --- /dev/null +++ b/src/test/java/org/onap/dmaap/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; + +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({ DMaaPCambriaExceptionMapperTest.class, DMaaPWebExceptionMapper.class, + JaxrsEchoServiceTest.class, HelloWorldTest.class, JaxrsUserServiceTest.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/JaxrsEchoServiceTest.java b/src/test/java/org/onap/dmaap/JaxrsEchoServiceTest.java new file mode 100644 index 0000000..94a6b96 --- /dev/null +++ b/src/test/java/org/onap/dmaap/JaxrsEchoServiceTest.java @@ -0,0 +1,60 @@ +/*- + * ============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; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class JaxrsEchoServiceTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPing() { + + JaxrsEchoService service = new JaxrsEchoService(); + + service.ping("hello"); + + assertTrue(true); + + } + + @Test + public void testGetProperty() { + + JaxrsEchoService service = new JaxrsEchoService(); + + service.getProperty("filename", "hello"); + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/JaxrsUserServiceTest.java b/src/test/java/org/onap/dmaap/JaxrsUserServiceTest.java new file mode 100644 index 0000000..7d8ba47 --- /dev/null +++ b/src/test/java/org/onap/dmaap/JaxrsUserServiceTest.java @@ -0,0 +1,50 @@ +/*- + * ============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; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class JaxrsUserServiceTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testLookupUser() { + + JaxrsUserService service = new JaxrsUserService(); + + service.lookupUser("userid"); + + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/TestRunner.java b/src/test/java/org/onap/dmaap/TestRunner.java new file mode 100644 index 0000000..4542566 --- /dev/null +++ b/src/test/java/org/onap/dmaap/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; + +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/filemonitor/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/filemonitor/JUnitTestSuite.java new file mode 100644 index 0000000..9c87f24 --- /dev/null +++ b/src/test/java/org/onap/dmaap/filemonitor/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.filemonitor; + +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({ ServicePropertiesListenerTest.class, ServicePropertiesMapTest.class, + ServicePropertyServiceTest.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/filemonitor/ServicePropertiesListenerTest.java b/src/test/java/org/onap/dmaap/filemonitor/ServicePropertiesListenerTest.java new file mode 100644 index 0000000..cae0c68 --- /dev/null +++ b/src/test/java/org/onap/dmaap/filemonitor/ServicePropertiesListenerTest.java @@ -0,0 +1,57 @@ +/*- + * ============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.filemonitor; + +import static org.junit.Assert.*; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ServicePropertiesListenerTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + //@Test + public void testUpdate() {/* + + ServicePropertiesListener listener = new ServicePropertiesListener(); + + try { + listener.update(new File(":/file")); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + */} + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/filemonitor/ServicePropertiesMapTest.java b/src/test/java/org/onap/dmaap/filemonitor/ServicePropertiesMapTest.java new file mode 100644 index 0000000..1e8c9d7 --- /dev/null +++ b/src/test/java/org/onap/dmaap/filemonitor/ServicePropertiesMapTest.java @@ -0,0 +1,128 @@ +/*- + * ============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.filemonitor; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; + +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.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(PowerMockRunner.class) +public class ServicePropertiesMapTest { + + @InjectMocks + ServicePropertiesMap map; + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + /*@Test + public void testRefresh() { + + try { + map.refresh(new File(":/file")); + } catch (Exception e) { + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test() + public void testRefreshJsonFile() throws Exception { + //Path resourceDirectory = Paths.get("src/test/resources"); + // map.refresh(new File(resourceDirectory+"\\"+"test.json")); + ClassLoader classLoader = getClass().getClassLoader(); + map.refresh(new File(classLoader.getResource("test.json").getFile())); + + assertTrue(true); + } + + @Test + public void testRefreshPropsFile() throws Exception { + Path resourceDirectory = Paths.get("src/test/resources"); + map.refresh(new File(resourceDirectory+"\\"+"test.properties")); + ClassLoader classLoader = getClass().getClassLoader(); + map.refresh(new File(classLoader.getResource("test.json").getFile())); + assertTrue(true); + }*/ + + @Test + public void testGetProperty() { + + try { + map.getProperty("filename", "propertykey"); + } catch (Exception e) { + e.printStackTrace(); + } + + assertTrue(true); + } + + @Test + public void testGetProperties() { + + try { + map.getProperties("filename"); + } catch (Exception e) { + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testIfNullThenEmpty() { + + try { + map.getProperties("filename"); + } catch (Exception e) { + e.printStackTrace(); + } + + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/filemonitor/ServicePropertyServiceTest.java b/src/test/java/org/onap/dmaap/filemonitor/ServicePropertyServiceTest.java new file mode 100644 index 0000000..461ad60 --- /dev/null +++ b/src/test/java/org/onap/dmaap/filemonitor/ServicePropertyServiceTest.java @@ -0,0 +1,153 @@ +/*- + * ============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.filemonitor; + +import static org.junit.Assert.*; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ServicePropertyServiceTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testInit() { + + ServicePropertyService service = new ServicePropertyService(); + try { + service.init(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testsetLoadOnStartup() { + + ServicePropertyService service = new ServicePropertyService(); + try { + service.setLoadOnStartup(true); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testSetSsfFileMonitorPollingInterval() { + + ServicePropertyService service = new ServicePropertyService(); + try { + service.setSsfFileMonitorPollingInterval("interval"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testSetSsfFileMonitorThreadpoolSize() { + + ServicePropertyService service = new ServicePropertyService(); + try { + service.setSsfFileMonitorThreadpoolSize("threadPoolSize"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testIsLoadOnStartup() { + ServicePropertyService service = new ServicePropertyService(); + service.isLoadOnStartup(); + assertTrue(true); + + } + + @Test + public void testGetSsfFileMonitorPollingInterval() { + ServicePropertyService service = new ServicePropertyService(); + service.getSsfFileMonitorPollingInterval(); + assertTrue(true); + + } + + @Test + public void testGetSsfFileMonitorThreadpoolSize() { + ServicePropertyService service = new ServicePropertyService(); + service.getSsfFileMonitorThreadpoolSize(); + assertTrue(true); + + } + + @Test + public void testGetFileChangedListener() { + ServicePropertyService service = new ServicePropertyService(); + service.getFileChangedListener(); + assertTrue(true); + + } + + @Test + public void testSetFileChangedListener() { + ServicePropertyService service = new ServicePropertyService(); + service.setFileChangedListener(null); + assertTrue(true); + + } + + @Test + public void testGetFilePropertiesMap() { + ServicePropertyService service = new ServicePropertyService(); + service.getFilePropertiesMap(); + assertTrue(true); + + } + + @Test + public void testSetFilePropertiesMap() { + ServicePropertyService service = new ServicePropertyService(); + service.setFilePropertiesMap(null); + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/filemonitor/TestRunner.java b/src/test/java/org/onap/dmaap/filemonitor/TestRunner.java new file mode 100644 index 0000000..1af59c2 --- /dev/null +++ b/src/test/java/org/onap/dmaap/filemonitor/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.filemonitor; + +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/mmagent/CreateMirrorMakerTest.java b/src/test/java/org/onap/dmaap/mmagent/CreateMirrorMakerTest.java new file mode 100644 index 0000000..bad987d --- /dev/null +++ b/src/test/java/org/onap/dmaap/mmagent/CreateMirrorMakerTest.java @@ -0,0 +1,82 @@ +/*- + * ============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.mmagent; + +import org.onap.dmaap.dmf.mr.CambriaApiException; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + + +public class CreateMirrorMakerTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetCreateMirrorMaker() { + + CreateMirrorMaker mMaker = new CreateMirrorMaker(); + mMaker.getCreateMirrorMaker(); + + assertTrue(true); + + } + + @Test + public void testSetCreateMirrorMaker() throws CambriaApiException { + + CreateMirrorMaker mMaker = new CreateMirrorMaker(); + mMaker.setCreateMirrorMaker(new MirrorMaker()); + + assertTrue(true); + + } + + @Test + public void testGetMessageID() { + + CreateMirrorMaker mMaker = new CreateMirrorMaker(); + mMaker.getMessageID(); + + assertTrue(true); + + } + + @Test + public void testSetMessageID() { + + CreateMirrorMaker mMaker = new CreateMirrorMaker(); + mMaker.setMessageID("messageID"); + + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/mmagent/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mmagent/JUnitTestSuite.java new file mode 100644 index 0000000..909ecd8 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mmagent/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.mmagent; + +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({ CreateMirrorMakerTest.class, MirrorMakerTest.class, + UpdateMirrorMakerTest.class, UpdateWhiteListTest.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/mmagent/MirrorMakerTest.java b/src/test/java/org/onap/dmaap/mmagent/MirrorMakerTest.java new file mode 100644 index 0000000..192ed1d --- /dev/null +++ b/src/test/java/org/onap/dmaap/mmagent/MirrorMakerTest.java @@ -0,0 +1,142 @@ +/*- + * ============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.mmagent; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class MirrorMakerTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetStatus() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.getStatus(); + + assertTrue(true); + + } + + @Test + public void testSetStatus() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.setStatus("status"); + + assertTrue(true); + + } + + @Test + public void testGetName() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.getName(); + + assertTrue(true); + + } + + @Test + public void testSetName() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.setName("name"); + + assertTrue(true); + + } + + + @Test + public void testGetConsumer() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.getConsumer(); + + assertTrue(true); + + } + + @Test + public void testSetConsumer() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.setConsumer("consumer"); + + assertTrue(true); + + } + + @Test + public void testGetProducer() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.getProducer(); + + assertTrue(true); + + } + + @Test + public void testSetProducer() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.setProducer("producer"); + + assertTrue(true); + + } + + + @Test + public void testGetWhitelist() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.getWhitelist(); + + assertTrue(true); + + } + + @Test + public void testSetWhitelist() { + + MirrorMaker mMaker = new MirrorMaker(); + mMaker.setWhitelist("whitelist"); + + assertTrue(true); + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/mmagent/TestRunner.java b/src/test/java/org/onap/dmaap/mmagent/TestRunner.java new file mode 100644 index 0000000..3e4ece3 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mmagent/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.mmagent; + +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/mmagent/UpdateMirrorMakerTest.java b/src/test/java/org/onap/dmaap/mmagent/UpdateMirrorMakerTest.java new file mode 100644 index 0000000..1826026 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mmagent/UpdateMirrorMakerTest.java @@ -0,0 +1,81 @@ +/*- + * ============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.mmagent; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class UpdateMirrorMakerTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetUpdateMirrorMaker() { + + UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); + mMaker.getUpdateMirrorMaker(); + + assertTrue(true); + + } + + @Test + public void testSetUpdateMirrorMaker() { + + UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); + mMaker.setUpdateMirrorMaker(new MirrorMaker()); + + assertTrue(true); + + } + + @Test + public void testGetMessageID() { + + UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); + mMaker.getMessageID(); + + assertTrue(true); + + } + + @Test + public void testSetMessageID() { + + UpdateMirrorMaker mMaker = new UpdateMirrorMaker(); + mMaker.setMessageID("messageID"); + + assertTrue(true); + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/mmagent/UpdateWhiteListTest.java b/src/test/java/org/onap/dmaap/mmagent/UpdateWhiteListTest.java new file mode 100644 index 0000000..75a9104 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mmagent/UpdateWhiteListTest.java @@ -0,0 +1,85 @@ +/*- + * ============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.mmagent; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class UpdateWhiteListTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetUpdateWhiteList() { + + UpdateWhiteList wList = new UpdateWhiteList(); + wList.getUpdateWhiteList(); + + assertTrue(true); + + } + + @Test + public void testSetUpdateWhiteList() { + + UpdateWhiteList wList = new UpdateWhiteList(); + wList.setUpdateWhiteList(new MirrorMaker()); + + assertTrue(true); + + } + + @Test + public void testGetMessageID() { + + UpdateWhiteList wList = new UpdateWhiteList(); + wList.getMessageID(); + + assertTrue(true); + + } + + @Test + public void testSetMessageID() { + + UpdateWhiteList wList = new UpdateWhiteList(); + wList.setMessageID("messageID"); + + assertTrue(true); + + } + + + + + + + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java b/src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java new file mode 100644 index 0000000..0f99ff5 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java @@ -0,0 +1,295 @@ +/*- + * ============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.service; + +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.onap.dmaap.dmf.mr.CambriaApiException; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; + +import java.io.IOException; +import java.util.Enumeration; +import org.onap.dmaap.dmf.mr.service.AdminService; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import org.powermock.core.classloader.annotations.PrepareForTest; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ ServiceUtil.class }) +public class AdminRestServiceTest { + + @InjectMocks + AdminRestService adminRestService; + + @Mock + AdminService adminService; + + @Mock + DMaaPContext dmaapContext; + + @Mock + HttpServletRequest httpServReq; + @Mock + private HttpServletResponse response; + + @Mock + Enumeration headerNames; + @Mock + private DMaaPContext dmaaPContext; + @Mock + private ConfigurationReader configReader; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetConsumerCache() throws CambriaApiException, AccessDeniedException { + adminRestService.getConsumerCache(); + + } + + @Test + public void testGetConsumerCache_error() throws CambriaApiException, AccessDeniedException, IOException { + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new IOException("error")).when(adminService).showConsumerCache(dmaaPContext); + try { + adminRestService.getConsumerCache(); + } catch (CambriaApiException e) { + assertTrue(true); + } + + } + + @Test + public void testDropConsumerCache() throws CambriaApiException, AccessDeniedException { + adminRestService.dropConsumerCache(); + + } + + @Test + public void testDropConsumerCach_error() throws CambriaApiException, AccessDeniedException ,IOException{ + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new IOException("error")).when(adminService).dropConsumerCache(dmaaPContext); + try { + adminRestService.dropConsumerCache(); + } + catch (CambriaApiException e) { + assertTrue(true); + } + + + } + @Test + public void testDropConsumerCach_error1() throws CambriaApiException, AccessDeniedException,IOException { + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).dropConsumerCache(dmaaPContext); + try { + adminRestService.dropConsumerCache(); + } + catch (CambriaApiException e) { + assertTrue(true); + } + + + } + + @Test + public void testGetBlacklist() throws CambriaApiException, AccessDeniedException { + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeaderNames()).thenReturn(headerNames); + when(headerNames.nextElement()).thenReturn("key"); + when(httpServReq.getHeader("key")).thenReturn("value"); + + adminRestService.getBlacklist(); + + } + + //@Test + public void testGetBlacklist_error() throws CambriaApiException, AccessDeniedException,IOException { + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new IOException("error")).when(adminService).getBlacklist(dmaaPContext); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeaderNames()).thenReturn(headerNames); + when(headerNames.nextElement()).thenReturn("key"); + when(httpServReq.getHeader("key")).thenReturn("value"); + when(headerNames.hasMoreElements()).thenReturn(false); + try { + adminRestService.getBlacklist(); + } + catch (CambriaApiException e) { + assertTrue(true); + } + + } + + ////@Test + public void testGetBlacklist_error1() throws CambriaApiException, AccessDeniedException,IOException { + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).getBlacklist(dmaaPContext); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeaderNames()).thenReturn(headerNames); + when(headerNames.nextElement()).thenReturn("key"); + when(httpServReq.getHeader("key")).thenReturn("value"); + when(headerNames.hasMoreElements()).thenReturn(false); + try { + adminRestService.getBlacklist(); + } + catch (CambriaApiException e) { + assertTrue(true); + } + + } + + @Test + public void testAddToBlacklist() throws CambriaApiException, AccessDeniedException { + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + + adminRestService.addToBlacklist("120.120.120.120"); + + } + + @Test + public void testAddToBlacklist_error() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException { + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).addToBlacklist(dmaaPContext,"120.120.120.120"); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + try { + adminRestService.addToBlacklist("120.120.120.120"); + }catch (CambriaApiException e) { + assertTrue(true); + } + + } + + @Test + public void testAddToBlacklist_error1() throws CambriaApiException, AccessDeniedException,IOException, ConfigDbException { + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new IOException("error")).when(adminService).addToBlacklist(dmaaPContext,"120.120.120.120"); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + try { + adminRestService.addToBlacklist("120.120.120.120"); + }catch (CambriaApiException e) { + assertTrue(true); + } + + } + + @Test + public void testRemoveFromBlacklist() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException { + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + + adminRestService.removeFromBlacklist("120.120.120.120"); + + } + + @Test + public void testRemoveFromBlacklist_error() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException{ + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new IOException("error")).when(adminService).removeFromBlacklist(dmaaPContext,"120.120.120.120"); + + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + try { + + adminRestService.removeFromBlacklist("120.120.120.120"); + }catch (CambriaApiException e) { + assertTrue(true); + } + catch (AccessDeniedException e) { + assertTrue(true); + } + catch (ConfigDbException e) { + assertTrue(true); + } + + } + + @Test + public void testRemoveFromBlacklist_error1() throws CambriaApiException, AccessDeniedException, ConfigDbException,IOException { + + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); + PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).removeFromBlacklist(dmaaPContext,"120.120.120.120"); + + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + try { + + adminRestService.removeFromBlacklist("120.120.120.120"); + }catch (CambriaApiException e) { + assertTrue(true); + } + catch (AccessDeniedException e) { + assertTrue(true); + } + catch (ConfigDbException e) { + assertTrue(true); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/service/ApiKeysRestServiceTest.java b/src/test/java/org/onap/dmaap/service/ApiKeysRestServiceTest.java new file mode 100644 index 0000000..20438f3 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/ApiKeysRestServiceTest.java @@ -0,0 +1,232 @@ +/*- + * ============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.service; + +import static org.junit.Assert.*; + +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; +import org.junit.runner.RunWith; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.ApiKeyBean; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.json.JSONException; + +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; + +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import org.onap.dmaap.dmf.mr.service.ApiKeysService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.db.NsaApiDb.KeyExistsException; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ ServiceUtil.class }) +public class ApiKeysRestServiceTest { + + @InjectMocks + private ApiKeysRestService service; + + @Mock + ApiKeysService apiKeyService; + + @Mock + DMaaPContext dmaapContext; + + @Mock + HttpServletRequest httpServReq; + @Mock + private HttpServletResponse response; + @Mock + private ConfigurationReader configReader; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetAllApiKeys() { + + try { + service.getAllApiKeys(); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testGetAllApiKeys_error() throws ConfigDbException, IOException { + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); + PowerMockito.doThrow(new IOException("error")).when(apiKeyService).getAllApiKeys(dmaapContext); + try { + service.getAllApiKeys(); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + assertTrue(true); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testGetApiKey() { + + try { + service.getApiKey("apikeyName"); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testGetApiKey_error() throws ConfigDbException, IOException { + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); + PowerMockito.doThrow(new IOException("error")).when(apiKeyService).getApiKey(dmaapContext, "apikeyName"); + + try { + service.getApiKey("apikeyName"); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + assertTrue(true); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testCreateApiKey() { + + try { + service.createApiKey(new ApiKeyBean("hs647a@att.com", "test apikey")); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testCreateApiKey_error() + throws CambriaApiException, JSONException, KeyExistsException, ConfigDbException, IOException { + + ApiKeyBean bean = new ApiKeyBean("test@onap.com", "test apikey"); + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); + PowerMockito.doThrow(new IOException("error")).when(apiKeyService).createApiKey(dmaapContext, bean); + + try { + service.createApiKey(bean); + } catch (CambriaApiException e) { + assertTrue(true); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testUpdateApiKey() { + + try { + service.updateApiKey("apikeyName", new ApiKeyBean("hs647a@att.com", "test apikey")); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testUpdateApiKey_error() throws CambriaApiException, JSONException, KeyExistsException, + ConfigDbException, IOException, AccessDeniedException { + + ApiKeyBean bean = new ApiKeyBean("test@onap.com", "test apikey"); + PowerMockito.mockStatic(ServiceUtil.class); + PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaapContext); + PowerMockito.doThrow(new IOException("error")).when(apiKeyService).updateApiKey(dmaapContext, "apikeyName", + bean); + try { + service.updateApiKey("apikeyName", bean); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + @Test + public void testDeleteApiKey() { + + try { + service.deleteApiKey("apikeyName"); + } catch (CambriaApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java b/src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java new file mode 100644 index 0000000..7f30cf4 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java @@ -0,0 +1,328 @@ +/*- + * ============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.service; + +import java.util.Date; + +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.Mockito; +import org.mockito.MockitoAnnotations; +import static org.mockito.Matchers.any; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.api.mockito.PowerMockito; +import static org.mockito.Mockito.when; + +import com.att.ajsc.beans.PropertiesMapBean; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.service.EventsService; +import com.att.nsa.configs.ConfigDbException; +import org.onap.dmaap.dmf.mr.utils.Utils; +import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; + +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; + +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; +import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PropertiesMapBean.class }) +public class EventsRestServiceTest { + + @InjectMocks + EventsRestService eventsRestRestService; + + @Mock + private EventsService eventsService; + + @Mock + ErrorResponse errorResponse; + + @Mock + DMaaPContext dmaapContext; + + @Mock + InputStream iStream; + + @Mock + ServletInputStream servletInputStream; + + @Mock + HttpServletRequest request; + + @Mock + private DMaaPErrorMessages errorMessages; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetEvents() throws CambriaApiException { + + eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); + + } + + @Test + public void testGetEvents_error() { + + try { + PowerMockito.doThrow(new IOException()).when(eventsService).getEvents(any(), any(), + any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | UnavailableException | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(eventsService).getEvents(any(), any(), + any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | UnavailableException | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new TopicExistsException("error")).when(eventsService).getEvents(any(), + any(), any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | UnavailableException | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.getEvents("topicName", "consumergroup", "consumerid"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + } + + @Test(expected = TopicExistsException.class) + public void testGetEvents_TopicExistException() throws CambriaApiException, ConfigDbException, TopicExistsException, + UnavailableException, IOException, AccessDeniedException { + + Mockito.doThrow(new TopicExistsException("topic exists")).when(eventsService).getEvents(any(), + any(), any(), any()); + + eventsService.getEvents(dmaapContext, "topicName", "consumergroup", "consumerid"); + + } + + @Test(expected = DMaaPAccessDeniedException.class) + public void testGetEvents_DMaaPAccessDeniedException() throws CambriaApiException, ConfigDbException, + TopicExistsException, UnavailableException, IOException, AccessDeniedException { + + Mockito.doThrow(new DMaaPAccessDeniedException(errorResponse)).when(eventsService).getEvents(any(), + any(), any(), any()); + + eventsService.getEvents(dmaapContext, "topicName", "consumergroup", "consumerid"); + + } + + /* + * @Test(expected = DMaaPAccessDeniedException.class) public void + * testGetEvents_DMaaPAccessDeniedException() throws CambriaApiException, + * ConfigDbException, TopicExistsException, UnavailableException, + * IOException, AccessDeniedException { + * + * Mockito.doThrow(new + * DMaaPAccessDeniedException(errorResponse)).when(eventsService).getEvents( + * dmaapContext, "topicName", "consumergroup", "consumerid"); + * + * eventsService.getEvents(dmaapContext, "topicName", "consumergroup", + * "consumerid"); + * + * } + */ + + @Test + public void testPushEvents() throws CambriaApiException { + + eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); + + } + + @Test + public void testPushEvents_error() { + + try { + PowerMockito.doThrow(new IOException()).when(eventsService).pushEvents(any(), any(), any(), + any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | missingReqdSetting | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(eventsService).pushEvents(any(), any(), + any(), any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | missingReqdSetting | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new TopicExistsException("error")).when(eventsService).pushEvents(any(), + any(), any(), any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | missingReqdSetting | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + } + + @Test + public void testPushEvents_TopicExistException() throws CambriaApiException { + + eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); + + } + + @Test + public void tesTPushEventsWithTransaction() throws CambriaApiException, IOException { + when(request.getInputStream()).thenReturn(servletInputStream); + eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); + + } + + @Test + public void tesTPushEventsWithTransaction_error() throws IOException { + when(request.getInputStream()).thenReturn(servletInputStream); + ServletInputStream stream = request.getInputStream(); + + try { + PowerMockito.doThrow(new TopicExistsException("error")).when(eventsService).pushEvents(any(), + any(), any(), any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | missingReqdSetting | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(eventsService).pushEvents(any(),any(), + any(), any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | missingReqdSetting | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new IOException()).when(eventsService).pushEvents(any(), any(), any(), + any(), any()); + } catch (TopicExistsException | DMaaPAccessDeniedException | AccessDeniedException | ConfigDbException + | missingReqdSetting | IOException excp) { + assertTrue(false); + } catch (CambriaApiException e) { + assertTrue(false); + } + + try { + eventsRestRestService.pushEventsWithTransaction("topicName", "partitionKey"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + } + +} diff --git a/src/test/java/org/onap/dmaap/service/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/service/JUnitTestSuite.java new file mode 100644 index 0000000..c1518af --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/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.service; + +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({ AdminRestServiceTest.class, ApiKeysRestServiceTest.class, + EventsRestServiceTest.class, MetricsRestServiceTest.class, MMRestServiceTest.class, + TopicRestServiceTest.class, TransactionRestServiceTest.class, UIRestServicesTest.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/service/MMRestServiceTest.java b/src/test/java/org/onap/dmaap/service/MMRestServiceTest.java new file mode 100644 index 0000000..4832d84 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/MMRestServiceTest.java @@ -0,0 +1,384 @@ +/*- + * ============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.service; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.anyString; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; + +//import static org.mockito.Matchers.anyString; +//import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.InputStream; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.IOUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +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.ajsc.beans.PropertiesMapBean; +import com.att.ajsc.filemonitor.AJSCPropertiesMap; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker; +import org.onap.dmaap.dmf.mr.constants.CambriaConstants; +import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; +import org.onap.dmaap.dmf.mr.metabroker.Topic; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; +import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticator; +import org.onap.dmaap.dmf.mr.service.MMService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import com.att.nsa.configs.ConfigDbException; +import org.onap.dmaap.mmagent.CreateMirrorMaker; +import org.onap.dmaap.mmagent.MirrorMaker; +import org.onap.dmaap.mmagent.UpdateMirrorMaker; +import com.att.nsa.security.NsaAcl; +import com.att.nsa.security.NsaApiKey; +import com.att.nsa.security.db.simple.NsaSimpleApiKey; +import com.google.gson.Gson; + +//@RunWith(MockitoJUnitRunner.class) +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PropertiesMapBean.class, AJSCPropertiesMap.class }) +public class MMRestServiceTest { + + @InjectMocks + MMRestService mmRestService; + + @Mock + private MMService mmservice; + + @Mock + CreateMirrorMaker cMirroMaker; + + @Mock + UpdateMirrorMaker uMirroMaker; + + private TopicRestService service = new TopicRestService(); + @Mock + private DMaaPErrorMessages errorMessages; + + @Mock + DMaaPContext dmaapContext; + + @Mock + ConfigurationReader configReader; + + @Mock + ServletOutputStream oStream; + + @Mock + DMaaPAuthenticator dmaaPAuthenticator; + + @Mock + MirrorMaker mMaker; + + @Mock + DMaaPAAFAuthenticator dmaapAAFauthenticator; + + @Mock + DMaaPAAFAuthenticatorImpl impl; + + @Mock + NsaApiKey user; + + @Mock + NsaSimpleApiKey nsaSimpleApiKey; + + @Mock + HttpServletRequest httpServReq; + + @Mock + HttpServletResponse httpServRes; + + @Mock + InputStream iStream; + + @Mock + DMaaPKafkaMetaBroker dmaapKafkaMetaBroker; + + @Mock + Topic createdTopic; + + @Mock + NsaAcl nsaAcl; + + @Mock + JSONObject jsonObj; + + @Mock + JSONArray jsonArray; + + @Before + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCallCreateMirrorMaker() throws Exception { + prepareForTestCommon(); + + // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { + // name:\"test\", consumer:\"test\", producer:\"test\", + // whitelist:\"test\",status:\"test\" }}"; + String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callCreateMirrorMaker(inputSteam); + assertTrue(true); + + } + @Test + public void testCallCreateMirrorMaker_error4() throws Exception { + prepareForTestCommon(); + + // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { + // name:\"test\", consumer:\"test\", producer:\"test\", + // whitelist:\"test\",status:\"test\" }}"; + String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test@#\", consumer:\"test\", producer:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callCreateMirrorMaker(inputSteam); + assertTrue(true); + + } + @Test + public void testCallCreateMirrorMaker_3() throws Exception { + prepareForTestCommon(); + + // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { + // name:\"test\", consumer:\"test\", producer:\"test\", + // whitelist:\"test\",status:\"test\" }}"; + String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"\", consumer:\"test\", producer:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callCreateMirrorMaker(inputSteam); + assertTrue(true); + + } + @Test + public void testCallCreateMirrorMaker_error2() throws Exception { + prepareForTestCommon(); + + // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { + // name:\"test\", consumer:\"test\", producer:\"test\", + // whitelist:\"test\",status:\"test\" }}"; + String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\",whitelist:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callCreateMirrorMaker(inputSteam); + assertTrue(true); + + } + + @Test + public void testCallCreateMirrorMaker_error1() throws Exception { + prepareForTestCommon(); + + // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { + // name:\"test\", consumer:\"test\", producer:\"test\", + // whitelist:\"test\",status:\"test\" }}"; + String sampleJson = "{ messageID:\"test\"}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callCreateMirrorMaker(inputSteam); + assertTrue(true); + + } + + @Test + public void testCallListAllMirrorMaker() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callListAllMirrorMaker(inputSteam); + assertTrue(true); + } + + @Test + public void testCallUpdateMirrorMaker() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callUpdateMirrorMaker(inputSteam); + assertTrue(true); + } + + @Test + public void testCallUpdateMirrorMaker_error1() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ messageID:\"test@1\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callUpdateMirrorMaker(inputSteam); + assertTrue(true); + } + @Test + public void testCallUpdateMirrorMaker_error2() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"\", consumer:\"test\", producer:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callUpdateMirrorMaker(inputSteam); + assertTrue(true); + } + @Test + public void testCallUpdateMirrorMaker_error3() throws Exception{ + prepareForTestCommon(); + + String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callUpdateMirrorMaker(inputSteam); + assertTrue(true); + } + @Test + public void testCallUpdateMirrorMaker_error4() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ messageID:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callUpdateMirrorMaker(inputSteam); + assertTrue(true); + } + + @Test + public void testCallDeleteMirrorMaker() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ messageID:\"test\", deleteMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.callDeleteMirrorMaker(inputSteam); + assertTrue(true); + } + + @Test + public void testListWhiteList() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.listWhiteList(inputSteam); + assertTrue(true); + } + + @Test + public void testCreateWhiteList() throws Exception { + prepareForTestCommon(); + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + + mmRestService.createWhiteList(inputSteam); + assertTrue(true); + } + + @Test + public void testDeleteWhiteList() throws Exception { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + mmRestService.deleteWhiteList(inputSteam); + assertTrue(true); + } + + private void prepareForTestCommon() throws Exception { + Assert.assertNotNull(mmRestService); + PowerMockito.when(dmaapContext.getRequest()).thenReturn(httpServReq); + PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin")).thenReturn(true); + PowerMockito.when(httpServReq.isUserInRole("admin")).thenReturn(true); + + PowerMockito.mockStatic(AJSCPropertiesMap.class); + + assertTrue(true); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf")) + .thenReturn("admin"); + PowerMockito + .when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf.create")) + .thenReturn("aafcreate"); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf")) + .thenReturn("admin"); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout")) + .thenReturn("100"); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic")) + .thenReturn("mirrormaker.topic"); + + PowerMockito + .when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup")) + .thenReturn("mirrormaker.consumergroup"); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid")) + .thenReturn("mirrormaker.consumerid"); + + PowerMockito.when(dmaapContext.getRequest()).thenReturn(httpServReq); + + PowerMockito.when(httpServReq.isUserInRole("admin")).thenReturn(true); + + // PowerMockito.when(httpServReq.getHeader("Authorization")).thenReturn("Admin"); + PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin.aaf")).thenReturn(true); + PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin")).thenReturn(true); + PowerMockito.when(httpServReq.getHeader("Authorization")).thenReturn("Admin"); + PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin")).thenReturn(true); + PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "aafcreatetest|create")) + .thenReturn(true); + + PowerMockito.when(cMirroMaker.getCreateMirrorMaker()).thenReturn(mMaker); + + PowerMockito.when(mMaker.getName()).thenReturn("mirroMakerName"); + PowerMockito.when(dmaapContext.getConfigReader()).thenReturn(configReader); + PowerMockito.when(dmaapContext.getRequest()).thenReturn(httpServReq); + PowerMockito.when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); + + PowerMockito.when(dmaapContext.getResponse()).thenReturn(httpServRes); + PowerMockito.when(configReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker); + PowerMockito.when(httpServReq.getMethod()).thenReturn("HEAD"); + + PowerMockito.when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); + } + +} diff --git a/src/test/java/org/onap/dmaap/service/MetricsRestServiceTest.java b/src/test/java/org/onap/dmaap/service/MetricsRestServiceTest.java new file mode 100644 index 0000000..1188945 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/MetricsRestServiceTest.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.service; + +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.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.ajsc.beans.PropertiesMapBean; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.service.MetricsService; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PropertiesMapBean.class }) +public class MetricsRestServiceTest { + + @InjectMocks + MetricsRestService metricsRestService; + + @Mock + private MetricsService metricsService; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetMetrics() throws CambriaApiException { + + metricsRestService.getMetrics(); + + } + + @Test + public void testGetMetricsByName() throws CambriaApiException { + + metricsRestService.getMetricsByName("metricsName"); + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/service/TestRunner.java b/src/test/java/org/onap/dmaap/service/TestRunner.java new file mode 100644 index 0000000..0441645 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/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.service; + +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/service/TopicRestServiceTest.java b/src/test/java/org/onap/dmaap/service/TopicRestServiceTest.java new file mode 100644 index 0000000..0c563b4 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/TopicRestServiceTest.java @@ -0,0 +1,838 @@ +/*- + * ============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.service; + +import static org.junit.Assert.*; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ConcurrentModificationException; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Assert; +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.ajsc.beans.PropertiesMapBean; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker; +import org.onap.dmaap.dmf.mr.beans.TopicBean; +import org.onap.dmaap.dmf.mr.constants.CambriaConstants; +import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; +import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; +import org.onap.dmaap.dmf.mr.metabroker.Topic; +import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; +import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticator; +import org.onap.dmaap.dmf.mr.service.TopicService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; +import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.NsaAcl; +import com.att.nsa.security.NsaApiKey; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; +import com.att.nsa.security.db.simple.NsaSimpleApiKey; + +//@RunWith(MockitoJUnitRunner.class) +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PropertiesMapBean.class }) +public class TopicRestServiceTest { + + @InjectMocks + TopicRestService topicRestService; + + @Mock + private TopicService topicService; + + private TopicRestService service = new TopicRestService(); + @Mock + private DMaaPErrorMessages errorMessages; + + @Mock + DMaaPContext dmaapContext; + + @Mock + ConfigurationReader configReader; + + @Mock + ServletOutputStream oStream; + + @Mock + DMaaPAuthenticator dmaaPAuthenticator; + + @Mock + DMaaPAAFAuthenticator dmaapAAFauthenticator; + @Mock + NsaApiKey user; + + @Mock + NsaSimpleApiKey nsaSimpleApiKey; + + @Mock + HttpServletRequest httpServReq; + + @Mock + HttpServletResponse httpServRes; + + @Mock + DMaaPKafkaMetaBroker dmaapKafkaMetaBroker; + + @Mock + Topic createdTopic; + + @Mock + NsaAcl nsaAcl; + + @Mock + JSONObject jsonObj; + + @Mock + JSONArray jsonArray; + + @Before + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() throws Exception { + } + + @Test(expected = DMaaPAccessDeniedException.class) + public void testGetTopics() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, JSONException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) + .thenReturn("namespace"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + when(configReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker); + when(httpServReq.getMethod()).thenReturn("HEAD"); + + when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); + + topicRestService.getTopics(); + } + + @Test + public void testGetTopics_nullAuth() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, JSONException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) + .thenReturn("namespace"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn(null); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + String perms = "namespace" + "|" + "*" + "|" + "view"; + when(dmaapAAFauthenticator.aafAuthentication(httpServReq, perms)).thenReturn(true); + + when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); + + topicRestService.getTopics(); + } + + @Test + public void testGetTopics_error() throws DMaaPAccessDeniedException, TopicExistsException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) + .thenReturn("namespace"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn(null); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + String perms = "namespace" + "|" + "*" + "|" + "view"; + when(dmaapAAFauthenticator.aafAuthentication(httpServReq, perms)).thenReturn(true); + + when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); + try { + PowerMockito.doThrow(new IOException()).when(topicService).getTopics(any()); + } catch (JSONException | ConfigDbException | IOException excp) { + assertTrue(false); + } + + try { + topicRestService.getTopics(); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test(expected = DMaaPAccessDeniedException.class) + public void testGetAllTopics() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, JSONException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) + .thenReturn("namespace"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + + topicRestService.getAllTopics(); + } + + @Test + public void testGetAllTopics_nullAuth() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, JSONException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) + .thenReturn("namespace"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn(null); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + + topicRestService.getAllTopics(); + } + + @Test + public void testGetAllTopics_error() throws DMaaPAccessDeniedException, TopicExistsException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.namespace.aaf")) + .thenReturn("namespace"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn(null); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).getAllTopics(any()); + } catch (JSONException | ConfigDbException | IOException excp) { + assertTrue(false); + } + + try { + topicRestService.getAllTopics(); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test(expected = DMaaPAccessDeniedException.class) + public void testGetTopic() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, JSONException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "enforced.topic.name.AAF")) + .thenReturn("enfTopicName"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn("Authorization"); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + + topicRestService.getTopic("topicName"); + } + + @Test + public void testGetTopic_nullAuth() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, JSONException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "enforced.topic.name.AAF")) + .thenReturn("enfTopicName"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn(null); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + + topicRestService.getTopic("topicName"); + } + + @Test + public void testGetTopic_error() throws DMaaPAccessDeniedException, ConfigDbException { + + Assert.assertNotNull(topicRestService); + + PowerMockito.mockStatic(PropertiesMapBean.class); + + assertTrue(true); + when(PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "enforced.topic.name.AAF")) + .thenReturn("enfTopicName"); + + PowerMockito.mockStatic(DMaaPResponseBuilder.class); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(httpServReq.getHeader("Authorization")).thenReturn(null); + + when(dmaapContext.getResponse()).thenReturn(httpServRes); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).getTopic(any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException excp) { + assertTrue(false); + } + + try { + topicRestService.getTopic("topicName"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test + public void testCreateTopic() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.createTopic(topicBean); + } + + @Test + public void testCreateTopic_error() { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).createTopic(any(), any()); + } catch (TopicExistsException | IOException | AccessDeniedException | DMaaPAccessDeniedException excp) { + assertTrue(false); + } catch (CambriaApiException excp) { + assertTrue(false); + } + + try { + topicRestService.createTopic(topicBean); + } catch (CambriaApiException excp) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new TopicExistsException("error")).when(topicService).createTopic(any(), any()); + } catch (TopicExistsException | IOException | AccessDeniedException | DMaaPAccessDeniedException excp) { + assertTrue(false); + } catch (CambriaApiException excp) { + assertTrue(false); + } + + try { + topicRestService.createTopic(topicBean); + } catch (CambriaApiException excp) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(topicService).createTopic(any(), any()); + } catch (TopicExistsException | IOException | AccessDeniedException | DMaaPAccessDeniedException excp) { + assertTrue(false); + } catch (CambriaApiException excp) { + assertTrue(false); + } + + try { + topicRestService.createTopic(topicBean); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test + public void testDeleteTopic() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.deleteTopic("enfTopicNamePlusExtra"); + } + + @Test + public void testDeleteTopic_error() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).deleteTopic(any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.deleteTopic("enfTopicNamePlusExtra"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(topicService).deleteTopic(any(), + any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.deleteTopic("enfTopicNamePlusExtra"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test + public void testGetPublishersByTopicName() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.getPublishersByTopicName("enfTopicNamePlusExtra"); + } + + @Test + public void testGetPublishersByTopicName_error() { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).getPublishersByTopicName(any(), + any()); + } catch (TopicExistsException | ConfigDbException | IOException e) { + assertTrue(false); + } + + try { + topicRestService.getPublishersByTopicName("enfTopicNamePlusExtra"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test + public void testPermitPublisherForTopic() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(any())).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.permitPublisherForTopic("enfTopicNamePlusExtra", "producerID"); + } + + @Test + public void testPermitPublisherForTopic_error() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).permitPublisherForTopic(any(), + any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.permitPublisherForTopic("enfTopicNamePlusExtra", "producerID"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(topicService).permitPublisherForTopic(any(), + any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.permitPublisherForTopic("enfTopicNamePlusExtra", "producerID"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test + public void testDenyPublisherForTopic() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.denyPublisherForTopic("enfTopicNamePlusExtra", "producerID"); + } + + @Test + public void testDenyPublisherForTopic_error() + throws DMaaPAccessDeniedException, CambriaApiException, IOException, TopicExistsException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).denyPublisherForTopic(any(), + any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.denyPublisherForTopic("enfTopicNamePlusExtra", "producerID"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(topicService).denyPublisherForTopic(any(), + any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.denyPublisherForTopic("enfTopicNamePlusExtra", "producerID"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + + } + + @Test + public void testGetConsumersByTopicName() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, AccessDeniedException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.getConsumersByTopicName("enfTopicNamePlusExtra"); + } + + @Test + public void testGetConsumersByTopicName_error() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, AccessDeniedException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).getConsumersByTopicName(any(), + any()); + } catch (TopicExistsException | ConfigDbException | IOException excp) { + assertTrue(false); + } + + try { + topicRestService.getConsumersByTopicName("enfTopicNamePlusExtra"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test + public void testPermitConsumerForTopic() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, AccessDeniedException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(any())).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.permitConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); + } + + @Test + public void testPermitConsumerForTopic_error() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, AccessDeniedException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(any())).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).permitConsumerForTopic(any(), + any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.permitConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + + @Test + public void testPermitConsumerForTopicWithException() throws DMaaPAccessDeniedException, CambriaApiException, + IOException, TopicExistsException, AccessDeniedException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.permitConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); + } + + @Test + public void testDenyConsumerForTopic() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, AccessDeniedException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + topicRestService.denyConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); + } + + @Test + public void testDenyConsumerForTopic_error() throws DMaaPAccessDeniedException, CambriaApiException, IOException, + TopicExistsException, AccessDeniedException { + + Assert.assertNotNull(topicRestService); + + when(dmaapContext.getRequest()).thenReturn(httpServReq); + when(dmaaPAuthenticator.authenticate(dmaapContext)).thenReturn(nsaSimpleApiKey); + when(configReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator); + when(dmaapContext.getConfigReader()).thenReturn(configReader); + + TopicBean topicBean = new TopicBean(); + topicBean.setTopicName("enfTopicNamePlusExtra"); + + try { + PowerMockito.doThrow(new IOException()).when(topicService).denyConsumerForTopic(any(), + any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.denyConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + + try { + PowerMockito.doThrow(new AccessDeniedException()).when(topicService).denyConsumerForTopic(any(), + any(), any()); + } catch (TopicExistsException | ConfigDbException | IOException | AccessDeniedException + | DMaaPAccessDeniedException excp) { + assertTrue(false); + } + + try { + topicRestService.denyConsumerForTopic("enfTopicNamePlusExtra", "consumerID"); + } catch (CambriaApiException excp) { + assertTrue(true); + } + } + +} diff --git a/src/test/java/org/onap/dmaap/service/TransactionRestServiceTest.java b/src/test/java/org/onap/dmaap/service/TransactionRestServiceTest.java new file mode 100644 index 0000000..b849daa --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/TransactionRestServiceTest.java @@ -0,0 +1,123 @@ +/*- + * ============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.service; + +import static org.junit.Assert.*; + +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; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.ajsc.beans.PropertiesMapBean; +import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.service.EventsService; +import org.onap.dmaap.dmf.mr.service.TransactionService; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; +import com.att.aft.dme2.internal.jettison.json.JSONException; +import org.powermock.api.mockito.PowerMockito; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PropertiesMapBean.class }) +public class TransactionRestServiceTest { + + @InjectMocks + TransactionRestService transactionRestService; + + @Mock + private TransactionService transactionService; + + @Mock + DMaaPContext dmaapContext; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetAllTransactionObjs() throws CambriaApiException { + + transactionRestService.getAllTransactionObjs(); + assertTrue(true); + + } + + @Test + public void testGetTransactionObj() throws CambriaApiException { + + transactionRestService.getTransactionObj("transactionId"); + assertTrue(true); + + } + + @Test + public void testGetAllTransactionObjsError() throws CambriaApiException { + + try { + PowerMockito.doThrow(new IOException()).when(transactionService).getAllTransactionObjs(dmaapContext); + } catch (ConfigDbException | IOException e) { + assertTrue(false); + } + + try { + transactionRestService.getAllTransactionObjs(); + } catch (CambriaApiException e) { + assertTrue(true); + } + + } + + @Test + public void testGetTransactionObjError() { + + try { + PowerMockito.doThrow(new IOException()).when(transactionService).getTransactionObj(dmaapContext, + "transactionId"); + } catch (ConfigDbException | JSONException | IOException e) { + assertTrue(false); + } + + try { + transactionRestService.getTransactionObj("transactionId"); + } catch (CambriaApiException e) { + assertTrue(true); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/service/UIRestServicesTest.java b/src/test/java/org/onap/dmaap/service/UIRestServicesTest.java new file mode 100644 index 0000000..3024484 --- /dev/null +++ b/src/test/java/org/onap/dmaap/service/UIRestServicesTest.java @@ -0,0 +1,142 @@ +/*- + * ============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.service; + +import static org.junit.Assert.*; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.onap.dmaap.dmf.mr.CambriaApiException; +import com.att.nsa.configs.ConfigDbException; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; + +public class UIRestServicesTest { + + private UIRestServices service = null; + + @Before + public void setUp() throws Exception { + service = new UIRestServices(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testHello() { + + try { + service.hello(); + } catch (NullPointerException e) { + assertTrue(true); + } + assertTrue(true); + } + + @Test + public void testGetApiKeysTable() { + + try { + service.getApiKeysTable(); + } catch (NullPointerException e) { + assertTrue(true); + } + assertTrue(true); + } + + + @Test + public void testGetApiKey() { + + try { + service.getApiKey("apikey"); + } catch (NullPointerException e) { + assertTrue(true); + } + assertTrue(true); + } + + @Test + public void testGetTopicsTable() { + + try { + service.getTopicsTable(); + } catch (NullPointerException e) { + assertTrue(true); + } + assertTrue(true); + } + + @Test + public void testGetTopic() { + + try { + service.getTopic("topicName"); + } catch (NullPointerException e) { + assertTrue(true); + } + assertTrue(true); + } + + @Test + public void testGetDmaapContext() { + Class clazz = null; + Method method = null; + try { + clazz = Class.forName("UIRestServices"); + Object obj = clazz.newInstance(); + method = clazz.getDeclaredMethod("getDmaapContext", null); + method.setAccessible(true); + method.invoke(obj, null); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + } + + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/tools/ConfigToolContextTest.java b/src/test/java/org/onap/dmaap/tools/ConfigToolContextTest.java new file mode 100644 index 0000000..0dad4af --- /dev/null +++ b/src/test/java/org/onap/dmaap/tools/ConfigToolContextTest.java @@ -0,0 +1,86 @@ +/*- + * ============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.tools; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ConfigToolContextTest { + + private ConfigToolContext context; + @Before + public void setUp() throws Exception { + context = new ConfigToolContext(null, "connStr", null); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testRequestShutdown() { + + context.requestShutdown(); + + assertTrue(true); + + } + + @Test + public void testShouldContinue() { + + context.shouldContinue(); + + assertTrue(true); + + } + + @Test + public void testGetDb() { + + context.getDb(); + + assertTrue(true); + + } + + @Test + public void testGetMetrics() { + + context.getMetrics(); + + assertTrue(true); + + } + + @Test + public void testGetConnectionString() { + + context.getConnectionString(); + + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/tools/ConfigToolTest.java b/src/test/java/org/onap/dmaap/tools/ConfigToolTest.java new file mode 100644 index 0000000..85b41dc --- /dev/null +++ b/src/test/java/org/onap/dmaap/tools/ConfigToolTest.java @@ -0,0 +1,523 @@ +/*- + * ============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.tools; + +import static org.junit.Assert.*; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ConfigToolTest { + + private String[] parts = new String[5]; + + @Before + public void setUp() throws Exception { + + for (int i = 0; i < parts.length; i++) { + parts[i] = "string" + (i + 1); + } + } + + @After + public void tearDown() throws Exception { + } + + public void callMethodViaReflection(String outer, String inner, String methodName, Object... args) { + + String foreNameString = outer + "$" + inner; + Object parent = new ConfigTool(); + + Class innerClass; + try { + innerClass = Class.forName(foreNameString); + Constructor constructor = innerClass.getDeclaredConstructor(ConfigTool.class); + constructor.setAccessible(true); + Object child = constructor.newInstance(parent); + + // invoking method on inner class object + Method method = innerClass.getDeclaredMethod(methodName, null); + method.setAccessible(true);// in case of unaccessible method + method.invoke(child, args); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testGetMatches() { + + callMethodViaReflection("ConfigTool", "ListTopicCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + callMethodViaReflection("ConfigTool", "ListTopicCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute() { + + callMethodViaReflection("ConfigTool", "ListTopicCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp() { + + callMethodViaReflection("ConfigTool", "ListTopicCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches2() { + + callMethodViaReflection("ConfigTool", "WriteTopicCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady2() { + + callMethodViaReflection("ConfigTool", "WriteTopicCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute2() { + + callMethodViaReflection("ConfigTool", "WriteTopicCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp2() { + + callMethodViaReflection("ConfigTool", "WriteTopicCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches3() { + + callMethodViaReflection("ConfigTool", "ReadTopicCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady3() { + + callMethodViaReflection("ConfigTool", "ReadTopicCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute3() { + + callMethodViaReflection("ConfigTool", "ReadTopicCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp3() { + + callMethodViaReflection("ConfigTool", "ReadTopicCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches4() { + + callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady4() { + + callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute4() { + + callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp4() { + + callMethodViaReflection("ConfigTool", "InitSecureTopicCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches5() { + + callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady5() { + + callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute5() { + + callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp5() { + + callMethodViaReflection("ConfigTool", "SetTopicOwnerCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches6() { + + callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady6() { + + callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute6() { + + callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp6() { + + callMethodViaReflection("ConfigTool", "ListApiKeysCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches7() { + + callMethodViaReflection("ConfigTool", "PutApiCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady7() { + + callMethodViaReflection("ConfigTool", "PutApiCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute7() { + + callMethodViaReflection("ConfigTool", "PutApiCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp7() { + + callMethodViaReflection("ConfigTool", "PutApiCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches8() { + + callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady8() { + + callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute8() { + + callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp8() { + + callMethodViaReflection("ConfigTool", "writeApiKeyCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches9() { + + callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady9() { + + callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute9() { + + callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp9() { + + callMethodViaReflection("ConfigTool", "EncryptApiKeysCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches10() { + + callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady10() { + + callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute10() { + + callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp10() { + + callMethodViaReflection("ConfigTool", "DecryptApiKeysCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches11() { + + callMethodViaReflection("ConfigTool", "NodeFetchCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady11() { + + callMethodViaReflection("ConfigTool", "NodeFetchCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute11() { + + callMethodViaReflection("ConfigTool", "NodeFetchCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp11() { + + callMethodViaReflection("ConfigTool", "NodeFetchCommand", "displayHelp", null); + + assertTrue(true); + + } + + @Test + public void testGetMatches12() { + + callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "getMatches"); + + assertTrue(true); + + } + + @Test + public void testCheckReady12() { + + callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "checkReady", null); + + assertTrue(true); + + } + + @Test + public void testExecute12() { + + callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "execute", parts, null, null); + + assertTrue(true); + + } + + @Test + public void testDisplayHelp12() { + + callMethodViaReflection("ConfigTool", "DropOldConsumerGroupsCommand", "displayHelp", null); + + assertTrue(true); + + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/tools/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/tools/JUnitTestSuite.java new file mode 100644 index 0000000..b50c950 --- /dev/null +++ b/src/test/java/org/onap/dmaap/tools/JUnitTestSuite.java @@ -0,0 +1,42 @@ +/*- + * ============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.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({ ConfigToolTest.class, ConfigToolContextTest.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/tools/TestRunner.java b/src/test/java/org/onap/dmaap/tools/TestRunner.java new file mode 100644 index 0000000..2266be0 --- /dev/null +++ b/src/test/java/org/onap/dmaap/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.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/util/ContentLengthInterceptorTest.java b/src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java new file mode 100644 index 0000000..0608d2e --- /dev/null +++ b/src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java @@ -0,0 +1,93 @@ +/*- + * ============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.util; + +import static org.junit.Assert.assertTrue; + +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +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.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ System.class }) +public class ContentLengthInterceptorTest { + @InjectMocks + ContentLengthInterceptor interceptor = null; + + @Mock + Map map; + + @Mock + HttpServletRequest req; + + @Mock + HttpServletResponse res; + + @Before + public void setUp() throws Exception { + // interceptor = new ContentLengthInterceptor(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAllowOrReject() throws Exception { + PowerMockito.when(req.getHeader("Transfer-Encoding")).thenReturn("UTF-8"); + PowerMockito.when(req.getHeader("Content-Length")).thenReturn("1027"); + + interceptor.allowOrReject(req, res, map); + assertTrue(true); + } + + //@Test(expected = NullPointerException.class) + public void testAllowOrRejectWithException() throws Exception { + PowerMockito.when(req.getHeader("Transfer-Encoding")).thenThrow(new NumberFormatException()); + interceptor.allowOrReject(req, res, map); + assertTrue(true); + } + + + @Test + public void testGetDefLength() { + interceptor.getDefLength(); + assertTrue(true); + } + + @Test + public void testSetDefLength() { + interceptor.setDefLength("defLength"); + assertTrue(true); + + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/util/DMaaPAuthFilterTest.java b/src/test/java/org/onap/dmaap/util/DMaaPAuthFilterTest.java new file mode 100644 index 0000000..ad94441 --- /dev/null +++ b/src/test/java/org/onap/dmaap/util/DMaaPAuthFilterTest.java @@ -0,0 +1,100 @@ +/*- + * ============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.util; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +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.ajsc.beans.PropertiesMapBean; +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PropertiesMapBean.class, DMaaPResponseCode.class }) +public class DMaaPAuthFilterTest { + + @InjectMocks + DMaaPAuthFilter filter; + + @Mock + HttpServletRequest req; + + @Mock + ServletResponse res; + + @Mock + FilterChain chain; + + @Mock + DMaaPContext dmaapContext; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() throws Exception { + } + + //@Test + public void testDoFilter() throws IOException, ServletException { + + PowerMockito.when(dmaapContext.getRequest()).thenReturn(req); + PowerMockito.when(req.getHeader("Authorization")).thenReturn("Authorization"); + // when(dmaapContext.getResponse()).thenReturn(res); + filter.doFilter(req, res, chain); + assertTrue(true); + + } + + //@Test + public void testDoFilter_nullAuth() throws IOException, ServletException { + + PowerMockito.when(dmaapContext.getRequest()).thenReturn(req); + PowerMockito.when(req.getHeader("Authorization")).thenReturn("Authorization"); + + // when(dmaapContext.getResponse()).thenReturn(res); + filter.doFilter(req, res, chain); + assertTrue(true); + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/util/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/util/JUnitTestSuite.java new file mode 100644 index 0000000..9de79ab --- /dev/null +++ b/src/test/java/org/onap/dmaap/util/JUnitTestSuite.java @@ -0,0 +1,42 @@ +/*- + * ============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.util; + +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({ ContentLengthInterceptorTest.class, DMaaPAuthFilterTest.class, ServicePropertiesMapBeanTest.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/util/ServicePropertiesMapBeanTest.java b/src/test/java/org/onap/dmaap/util/ServicePropertiesMapBeanTest.java new file mode 100644 index 0000000..036bd13 --- /dev/null +++ b/src/test/java/org/onap/dmaap/util/ServicePropertiesMapBeanTest.java @@ -0,0 +1,53 @@ +/*- + * ============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.util; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ServicePropertiesMapBeanTest { + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetProperty() { + + try { + ServicePropertiesMapBean.getProperty(null, null); + } catch (Exception e) { + e.printStackTrace(); + } + + assertTrue(true); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/util/TestRunner.java b/src/test/java/org/onap/dmaap/util/TestRunner.java new file mode 100644 index 0000000..72a77a1 --- /dev/null +++ b/src/test/java/org/onap/dmaap/util/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.util; + +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()); + } + +} -- cgit 1.2.3-korg