From 11ee6836d6f25a1becdea60a322a72fbffd4b8b6 Mon Sep 17 00:00:00 2001 From: Arthur Martella Date: Thu, 26 Sep 2019 16:40:58 -0400 Subject: Split music src into music-core and music-rest Separating music into two directories to build with two pom files. Hopefully this should allow both jars to be deployed in nexus. Do not merge without careful review!!! Issue-ID: MUSIC-505 Signed-off-by: Martella, Arthur Change-Id: I9dd2074e7f4499216c2bcd00095829dd43e2d0f9 --- music-core/pom.xml | 571 ++++++++++ music-core/src/main/java/LICENSE.txt | 24 + .../java/org/onap/music/datastore/Condition.java | 53 + .../org/onap/music/datastore/MusicDataStore.java | 523 +++++++++ .../onap/music/datastore/MusicDataStoreHandle.java | 124 +++ .../onap/music/datastore/PreparedQueryObject.java | 176 +++ .../music/datastore/jsonobjects/JSONObject.java | 37 + .../music/datastore/jsonobjects/JsonDelete.java | 313 ++++++ .../music/datastore/jsonobjects/JsonIndex.java | 120 ++ .../music/datastore/jsonobjects/JsonInsert.java | 420 +++++++ .../music/datastore/jsonobjects/JsonKeySpace.java | 163 +++ .../datastore/jsonobjects/JsonLeasedLock.java | 44 + .../onap/music/datastore/jsonobjects/JsonLock.java | 49 + .../music/datastore/jsonobjects/JsonSelect.java | 208 ++++ .../music/datastore/jsonobjects/JsonTable.java | 381 +++++++ .../music/datastore/jsonobjects/JsonUpdate.java | 416 +++++++ .../music/eelf/healthcheck/MusicHealthCheck.java | 130 +++ .../music/eelf/logging/EELFLoggerDelegate.java | 381 +++++++ .../music/eelf/logging/format/AppMessages.java | 188 ++++ .../onap/music/eelf/logging/format/ErrorCodes.java | 107 ++ .../music/eelf/logging/format/ErrorSeverity.java | 38 + .../onap/music/eelf/logging/format/ErrorTypes.java | 46 + .../music/exceptions/MusicDeadlockException.java | 75 ++ .../music/exceptions/MusicLockingException.java | 75 ++ .../exceptions/MusicPolicyVoilationException.java | 82 ++ .../onap/music/exceptions/MusicQueryException.java | 90 ++ .../music/exceptions/MusicServiceException.java | 88 ++ .../lockingservice/cassandra/CassaLockStore.java | 604 ++++++++++ .../music/lockingservice/cassandra/LockType.java | 30 + .../lockingservice/cassandra/MusicLockState.java | 141 +++ .../main/java/org/onap/music/main/CipherUtil.java | 271 +++++ .../org/onap/music/main/CorePropertiesLoader.java | 122 ++ .../org/onap/music/main/DeadlockDetectionUtil.java | 148 +++ .../main/java/org/onap/music/main/MusicCore.java | 260 +++++ .../main/java/org/onap/music/main/MusicUtil.java | 820 ++++++++++++++ .../main/java/org/onap/music/main/ResultType.java | 42 + .../main/java/org/onap/music/main/ReturnType.java | 75 ++ .../org/onap/music/service/MusicCoreService.java | 181 +++ .../onap/music/service/impl/MusicCassaCore.java | 1149 +++++++++++++++++++ music-core/src/main/resources/LICENSE.txt | 24 + music-core/src/main/resources/Resources.properties | 50 + .../src/main/resources/application.properties | 9 + music-core/src/main/resources/logback.xml | 273 +++++ music-core/src/main/resources/project.properties | 5 + music-core/src/main/webapp/WEB-INF/.gitignore | 1 + music-core/src/test/java/LICENSE.txt | 24 + .../music/datastore/PreparedQueryObjectTest.java | 101 ++ .../music/eelf/logging/format/AppMessagesTest.java | 65 ++ .../exceptions/MusicLockingExceptionTest.java | 104 ++ .../MusicPolicyVoilationExceptionTest.java | 106 ++ .../music/exceptions/MusicQueryExceptionTest.java | 118 ++ .../exceptions/MusicServiceExceptionTest.java | 145 +++ .../org/onap/music/unittests/CassandraCQL.java | 247 +++++ .../org/onap/music/unittests/MusicUtilTest.java | 332 ++++++ .../org/onap/music/unittests/ResultTypeTest.java | 43 + .../org/onap/music/unittests/ReturnTypeTest.java | 84 ++ .../unittests/jsonobjects/JSONObjectTest.java | 44 + .../unittests/jsonobjects/JsonDeleteTest.java | 86 ++ .../unittests/jsonobjects/JsonInsertTest.java | 111 ++ .../unittests/jsonobjects/JsonKeySpaceTest.java | 73 ++ .../unittests/jsonobjects/JsonLeasedLockTest.java | 47 + .../unittests/jsonobjects/JsonSelectTest.java | 56 + .../music/unittests/jsonobjects/JsonTableTest.java | 100 ++ .../unittests/jsonobjects/JsonUpdateTest.java | 111 ++ .../jsonobjects/MusicHealthCheckTest.java | 48 + music-core/src/test/resources/LICENSE.txt | 24 + music-core/src/test/resources/Resources.properties | 50 + .../src/test/resources/application.properties | 2 + music-core/src/test/resources/cache.ccf | 62 ++ music-core/src/test/resources/logback.xml | 302 +++++ .../org.mockito.plugins.MockMaker | 1 + .../org.mockito.plugins.StackTraceCleanerProvider | 1 + music-core/src/test/resources/project.properties | 4 + music-rest/pom.xml | 274 +++++ music-rest/src/main/java/LICENSE.txt | 24 + .../src/main/java/org/onap/music/JerseyConfig.java | 87 ++ .../main/java/org/onap/music/MusicApplication.java | 203 ++++ .../org/onap/music/authentication/AuthUtil.java | 276 +++++ .../music/authentication/AuthorizationError.java | 55 + .../onap/music/authentication/CadiAuthFilter.java | 65 ++ .../authentication/MusicAuthorizationFilter.java | 122 ++ .../conductor/conditionals/JsonConditional.java | 90 ++ .../conductor/conditionals/MusicConditional.java | 379 +++++++ .../conditionals/RestMusicConditionalAPI.java | 205 ++++ .../conductor/conditionals/UpdateDataObject.java | 119 ++ .../music/eelf/healthcheck/MusicHealthCheck.java | 130 +++ .../music/eelf/logging/MusicContainerFilter.java | 68 ++ .../eelf/logging/MusicLoggingServletFilter.java | 207 ++++ .../exceptions/MusicAuthenticationException.java | 75 ++ .../music/exceptions/MusicExceptionMapper.java | 56 + .../java/org/onap/music/main/PropertiesLoader.java | 295 +++++ .../music/response/jsonobjects/JsonResponse.java | 322 ++++++ .../main/java/org/onap/music/rest/Application.java | 79 ++ .../java/org/onap/music/rest/RestMusicDataAPI.java | 1052 ++++++++++++++++++ .../onap/music/rest/RestMusicHealthCheckAPI.java | 124 +++ .../org/onap/music/rest/RestMusicLocksAPI.java | 632 +++++++++++ .../java/org/onap/music/rest/RestMusicQAPI.java | 441 ++++++++ .../java/org/onap/music/rest/RestMusicTestAPI.java | 70 ++ .../org/onap/music/rest/RestMusicVersionAPI.java | 82 ++ music-rest/src/main/resources/key.properties | 1 + music-rest/src/test/java/LICENSE.txt | 24 + .../music/exceptions/MusicExceptionMapperTest.java | 61 + .../java/org/onap/music/rest/ApplicationTest.java | 94 ++ .../org/onap/music/unittests/CassandraCQL.java | 247 +++++ .../org/onap/music/unittests/JsonResponseTest.java | 167 +++ .../onap/music/unittests/MusicDataStoreTest.java | 170 +++ .../onap/music/unittests/TestRestMusicQAPI.java | 975 ++++++++++++++++ .../onap/music/unittests/TestsUsingCassandra.java | 116 ++ .../unittests/TstRestMusicConditionalAPI.java | 373 +++++++ .../onap/music/unittests/TstRestMusicDataAPI.java | 1161 ++++++++++++++++++++ .../onap/music/unittests/TstRestMusicLockAPI.java | 768 +++++++++++++ .../unittests/authentication/AuthUtilTest.java | 123 +++ .../authentication/AuthorizationErrorTest.java | 51 + music-rest/src/test/resources/logback.xml | 302 +++++ pom.xml | 458 +------- src/main/java/LICENSE.txt | 24 - src/main/java/org/onap/music/JerseyConfig.java | 87 -- src/main/java/org/onap/music/MusicApplication.java | 203 ---- .../org/onap/music/authentication/AuthUtil.java | 276 ----- .../music/authentication/AuthorizationError.java | 55 - .../onap/music/authentication/CadiAuthFilter.java | 65 -- .../authentication/MusicAuthorizationFilter.java | 122 -- .../conductor/conditionals/JsonConditional.java | 90 -- .../conductor/conditionals/MusicConditional.java | 379 ------- .../conditionals/RestMusicConditionalAPI.java | 205 ---- .../conductor/conditionals/UpdateDataObject.java | 119 -- .../java/org/onap/music/datastore/Condition.java | 53 - .../org/onap/music/datastore/MusicDataStore.java | 523 --------- .../onap/music/datastore/MusicDataStoreHandle.java | 124 --- .../onap/music/datastore/PreparedQueryObject.java | 176 --- .../music/datastore/jsonobjects/JSONObject.java | 37 - .../music/datastore/jsonobjects/JsonDelete.java | 313 ------ .../music/datastore/jsonobjects/JsonIndex.java | 120 -- .../music/datastore/jsonobjects/JsonInsert.java | 420 ------- .../music/datastore/jsonobjects/JsonKeySpace.java | 163 --- .../datastore/jsonobjects/JsonLeasedLock.java | 44 - .../onap/music/datastore/jsonobjects/JsonLock.java | 49 - .../music/datastore/jsonobjects/JsonSelect.java | 208 ---- .../music/datastore/jsonobjects/JsonTable.java | 381 ------- .../music/datastore/jsonobjects/JsonUpdate.java | 416 ------- .../music/eelf/healthcheck/MusicHealthCheck.java | 130 --- .../music/eelf/logging/EELFLoggerDelegate.java | 381 ------- .../music/eelf/logging/MusicContainerFilter.java | 68 -- .../eelf/logging/MusicLoggingServletFilter.java | 207 ---- .../music/eelf/logging/format/AppMessages.java | 188 ---- .../onap/music/eelf/logging/format/ErrorCodes.java | 107 -- .../music/eelf/logging/format/ErrorSeverity.java | 38 - .../onap/music/eelf/logging/format/ErrorTypes.java | 46 - .../exceptions/MusicAuthenticationException.java | 75 -- .../music/exceptions/MusicDeadlockException.java | 75 -- .../music/exceptions/MusicExceptionMapper.java | 56 - .../music/exceptions/MusicLockingException.java | 75 -- .../exceptions/MusicPolicyVoilationException.java | 82 -- .../onap/music/exceptions/MusicQueryException.java | 90 -- .../music/exceptions/MusicServiceException.java | 88 -- .../lockingservice/cassandra/CassaLockStore.java | 604 ---------- .../music/lockingservice/cassandra/LockType.java | 30 - .../lockingservice/cassandra/MusicLockState.java | 141 --- src/main/java/org/onap/music/main/CipherUtil.java | 271 ----- .../org/onap/music/main/DeadlockDetectionUtil.java | 148 --- src/main/java/org/onap/music/main/MusicCore.java | 260 ----- src/main/java/org/onap/music/main/MusicUtil.java | 820 -------------- .../java/org/onap/music/main/PropertiesLoader.java | 295 ----- src/main/java/org/onap/music/main/ResultType.java | 42 - src/main/java/org/onap/music/main/ReturnType.java | 75 -- .../music/response/jsonobjects/JsonResponse.java | 322 ------ src/main/java/org/onap/music/rest/Application.java | 79 -- .../java/org/onap/music/rest/RestMusicDataAPI.java | 1052 ------------------ .../onap/music/rest/RestMusicHealthCheckAPI.java | 124 --- .../org/onap/music/rest/RestMusicLocksAPI.java | 632 ----------- .../java/org/onap/music/rest/RestMusicQAPI.java | 441 -------- .../java/org/onap/music/rest/RestMusicTestAPI.java | 70 -- .../org/onap/music/rest/RestMusicVersionAPI.java | 82 -- .../org/onap/music/service/MusicCoreService.java | 181 --- .../onap/music/service/impl/MusicCassaCore.java | 1149 ------------------- src/main/resources/LICENSE.txt | 24 - src/main/resources/Resources.properties | 50 - src/main/resources/application.properties | 9 - src/main/resources/key.properties | 1 - src/main/resources/logback.xml | 273 ----- src/main/resources/project.properties | 5 - src/test/java/LICENSE.txt | 24 - .../music/datastore/PreparedQueryObjectTest.java | 101 -- .../music/eelf/logging/format/AppMessagesTest.java | 65 -- .../music/exceptions/MusicExceptionMapperTest.java | 61 - .../exceptions/MusicLockingExceptionTest.java | 104 -- .../MusicPolicyVoilationExceptionTest.java | 106 -- .../music/exceptions/MusicQueryExceptionTest.java | 118 -- .../exceptions/MusicServiceExceptionTest.java | 145 --- .../java/org/onap/music/rest/ApplicationTest.java | 94 -- .../org/onap/music/unittests/CassandraCQL.java | 247 ----- .../org/onap/music/unittests/JsonResponseTest.java | 167 --- .../onap/music/unittests/MusicDataStoreTest.java | 170 --- .../org/onap/music/unittests/MusicUtilTest.java | 332 ------ .../org/onap/music/unittests/ResultTypeTest.java | 43 - .../org/onap/music/unittests/ReturnTypeTest.java | 84 -- .../onap/music/unittests/TestRestMusicQAPI.java | 975 ---------------- .../onap/music/unittests/TestsUsingCassandra.java | 116 -- .../unittests/TstRestMusicConditionalAPI.java | 373 ------- .../onap/music/unittests/TstRestMusicDataAPI.java | 1161 -------------------- .../onap/music/unittests/TstRestMusicLockAPI.java | 768 ------------- .../unittests/authentication/AuthUtilTest.java | 123 --- .../authentication/AuthorizationErrorTest.java | 51 - .../unittests/jsonobjects/JSONObjectTest.java | 44 - .../unittests/jsonobjects/JsonDeleteTest.java | 86 -- .../unittests/jsonobjects/JsonInsertTest.java | 111 -- .../unittests/jsonobjects/JsonKeySpaceTest.java | 73 -- .../unittests/jsonobjects/JsonLeasedLockTest.java | 47 - .../unittests/jsonobjects/JsonSelectTest.java | 56 - .../music/unittests/jsonobjects/JsonTableTest.java | 100 -- .../unittests/jsonobjects/JsonUpdateTest.java | 111 -- .../jsonobjects/MusicHealthCheckTest.java | 48 - src/test/resources/LICENSE.txt | 24 - src/test/resources/Resources.properties | 50 - src/test/resources/application.properties | 2 - src/test/resources/cache.ccf | 62 -- src/test/resources/logback.xml | 302 ----- .../org.mockito.plugins.MockMaker | 1 - .../org.mockito.plugins.StackTraceCleanerProvider | 1 - src/test/resources/project.properties | 4 - 220 files changed, 21790 insertions(+), 20539 deletions(-) create mode 100755 music-core/pom.xml create mode 100644 music-core/src/main/java/LICENSE.txt create mode 100644 music-core/src/main/java/org/onap/music/datastore/Condition.java create mode 100755 music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/PreparedQueryObject.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java create mode 100644 music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java create mode 100644 music-core/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java create mode 100644 music-core/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java create mode 100644 music-core/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java create mode 100644 music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java create mode 100644 music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java create mode 100644 music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java create mode 100644 music-core/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java create mode 100644 music-core/src/main/java/org/onap/music/exceptions/MusicLockingException.java create mode 100644 music-core/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java create mode 100644 music-core/src/main/java/org/onap/music/exceptions/MusicQueryException.java create mode 100644 music-core/src/main/java/org/onap/music/exceptions/MusicServiceException.java create mode 100644 music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java create mode 100644 music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockType.java create mode 100644 music-core/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java create mode 100644 music-core/src/main/java/org/onap/music/main/CipherUtil.java create mode 100644 music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java create mode 100644 music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java create mode 100644 music-core/src/main/java/org/onap/music/main/MusicCore.java create mode 100644 music-core/src/main/java/org/onap/music/main/MusicUtil.java create mode 100644 music-core/src/main/java/org/onap/music/main/ResultType.java create mode 100644 music-core/src/main/java/org/onap/music/main/ReturnType.java create mode 100644 music-core/src/main/java/org/onap/music/service/MusicCoreService.java create mode 100644 music-core/src/main/java/org/onap/music/service/impl/MusicCassaCore.java create mode 100644 music-core/src/main/resources/LICENSE.txt create mode 100644 music-core/src/main/resources/Resources.properties create mode 100755 music-core/src/main/resources/application.properties create mode 100644 music-core/src/main/resources/logback.xml create mode 100644 music-core/src/main/resources/project.properties create mode 100644 music-core/src/main/webapp/WEB-INF/.gitignore create mode 100644 music-core/src/test/java/LICENSE.txt create mode 100644 music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java create mode 100644 music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java create mode 100644 music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java create mode 100644 music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java create mode 100644 music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java create mode 100644 music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/CassandraCQL.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/MusicUtilTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/ResultTypeTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/ReturnTypeTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java create mode 100644 music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java create mode 100644 music-core/src/test/resources/LICENSE.txt create mode 100644 music-core/src/test/resources/Resources.properties create mode 100644 music-core/src/test/resources/application.properties create mode 100644 music-core/src/test/resources/cache.ccf create mode 100644 music-core/src/test/resources/logback.xml create mode 100644 music-core/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker create mode 100644 music-core/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider create mode 100644 music-core/src/test/resources/project.properties create mode 100755 music-rest/pom.xml create mode 100644 music-rest/src/main/java/LICENSE.txt create mode 100755 music-rest/src/main/java/org/onap/music/JerseyConfig.java create mode 100755 music-rest/src/main/java/org/onap/music/MusicApplication.java create mode 100644 music-rest/src/main/java/org/onap/music/authentication/AuthUtil.java create mode 100644 music-rest/src/main/java/org/onap/music/authentication/AuthorizationError.java create mode 100644 music-rest/src/main/java/org/onap/music/authentication/CadiAuthFilter.java create mode 100644 music-rest/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java create mode 100644 music-rest/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java create mode 100644 music-rest/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java create mode 100644 music-rest/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java create mode 100644 music-rest/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java create mode 100644 music-rest/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java create mode 100644 music-rest/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java create mode 100644 music-rest/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java create mode 100644 music-rest/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java create mode 100644 music-rest/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java create mode 100644 music-rest/src/main/java/org/onap/music/main/PropertiesLoader.java create mode 100644 music-rest/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java create mode 100644 music-rest/src/main/java/org/onap/music/rest/Application.java create mode 100755 music-rest/src/main/java/org/onap/music/rest/RestMusicDataAPI.java create mode 100644 music-rest/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java create mode 100644 music-rest/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java create mode 100755 music-rest/src/main/java/org/onap/music/rest/RestMusicQAPI.java create mode 100644 music-rest/src/main/java/org/onap/music/rest/RestMusicTestAPI.java create mode 100644 music-rest/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java create mode 100644 music-rest/src/main/resources/key.properties create mode 100644 music-rest/src/test/java/LICENSE.txt create mode 100644 music-rest/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java create mode 100644 music-rest/src/test/java/org/onap/music/rest/ApplicationTest.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java create mode 100644 music-rest/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java create mode 100644 music-rest/src/test/resources/logback.xml delete mode 100644 src/main/java/LICENSE.txt delete mode 100755 src/main/java/org/onap/music/JerseyConfig.java delete mode 100755 src/main/java/org/onap/music/MusicApplication.java delete mode 100644 src/main/java/org/onap/music/authentication/AuthUtil.java delete mode 100644 src/main/java/org/onap/music/authentication/AuthorizationError.java delete mode 100644 src/main/java/org/onap/music/authentication/CadiAuthFilter.java delete mode 100644 src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java delete mode 100644 src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java delete mode 100644 src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java delete mode 100644 src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java delete mode 100644 src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java delete mode 100644 src/main/java/org/onap/music/datastore/Condition.java delete mode 100755 src/main/java/org/onap/music/datastore/MusicDataStore.java delete mode 100644 src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java delete mode 100644 src/main/java/org/onap/music/datastore/PreparedQueryObject.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java delete mode 100644 src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java delete mode 100644 src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java delete mode 100644 src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java delete mode 100644 src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java delete mode 100644 src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java delete mode 100644 src/main/java/org/onap/music/eelf/logging/format/AppMessages.java delete mode 100644 src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java delete mode 100644 src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java delete mode 100644 src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java delete mode 100644 src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java delete mode 100644 src/main/java/org/onap/music/exceptions/MusicDeadlockException.java delete mode 100644 src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java delete mode 100644 src/main/java/org/onap/music/exceptions/MusicLockingException.java delete mode 100644 src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java delete mode 100644 src/main/java/org/onap/music/exceptions/MusicQueryException.java delete mode 100644 src/main/java/org/onap/music/exceptions/MusicServiceException.java delete mode 100644 src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java delete mode 100644 src/main/java/org/onap/music/lockingservice/cassandra/LockType.java delete mode 100644 src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java delete mode 100644 src/main/java/org/onap/music/main/CipherUtil.java delete mode 100644 src/main/java/org/onap/music/main/DeadlockDetectionUtil.java delete mode 100644 src/main/java/org/onap/music/main/MusicCore.java delete mode 100755 src/main/java/org/onap/music/main/MusicUtil.java delete mode 100644 src/main/java/org/onap/music/main/PropertiesLoader.java delete mode 100644 src/main/java/org/onap/music/main/ResultType.java delete mode 100644 src/main/java/org/onap/music/main/ReturnType.java delete mode 100644 src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java delete mode 100644 src/main/java/org/onap/music/rest/Application.java delete mode 100755 src/main/java/org/onap/music/rest/RestMusicDataAPI.java delete mode 100644 src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java delete mode 100644 src/main/java/org/onap/music/rest/RestMusicLocksAPI.java delete mode 100755 src/main/java/org/onap/music/rest/RestMusicQAPI.java delete mode 100644 src/main/java/org/onap/music/rest/RestMusicTestAPI.java delete mode 100644 src/main/java/org/onap/music/rest/RestMusicVersionAPI.java delete mode 100644 src/main/java/org/onap/music/service/MusicCoreService.java delete mode 100644 src/main/java/org/onap/music/service/impl/MusicCassaCore.java delete mode 100644 src/main/resources/LICENSE.txt delete mode 100644 src/main/resources/Resources.properties delete mode 100755 src/main/resources/application.properties delete mode 100644 src/main/resources/key.properties delete mode 100644 src/main/resources/logback.xml delete mode 100644 src/main/resources/project.properties delete mode 100644 src/test/java/LICENSE.txt delete mode 100644 src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java delete mode 100644 src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java delete mode 100644 src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java delete mode 100644 src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java delete mode 100644 src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java delete mode 100644 src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java delete mode 100644 src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java delete mode 100644 src/test/java/org/onap/music/rest/ApplicationTest.java delete mode 100644 src/test/java/org/onap/music/unittests/CassandraCQL.java delete mode 100644 src/test/java/org/onap/music/unittests/JsonResponseTest.java delete mode 100644 src/test/java/org/onap/music/unittests/MusicDataStoreTest.java delete mode 100644 src/test/java/org/onap/music/unittests/MusicUtilTest.java delete mode 100644 src/test/java/org/onap/music/unittests/ResultTypeTest.java delete mode 100644 src/test/java/org/onap/music/unittests/ReturnTypeTest.java delete mode 100644 src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java delete mode 100644 src/test/java/org/onap/music/unittests/TestsUsingCassandra.java delete mode 100644 src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java delete mode 100644 src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java delete mode 100644 src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java delete mode 100644 src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java delete mode 100644 src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java delete mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java delete mode 100644 src/test/resources/LICENSE.txt delete mode 100644 src/test/resources/Resources.properties delete mode 100644 src/test/resources/application.properties delete mode 100644 src/test/resources/cache.ccf delete mode 100644 src/test/resources/logback.xml delete mode 100644 src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker delete mode 100644 src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider delete mode 100644 src/test/resources/project.properties diff --git a/music-core/pom.xml b/music-core/pom.xml new file mode 100755 index 00000000..ae50e643 --- /dev/null +++ b/music-core/pom.xml @@ -0,0 +1,571 @@ + + + + 4.0.0 + org.onap.music + MUSIC-core + jar + 3.2.37-SNAPSHOT + + This is the MUSIC core interface, packaged as a jar file. + + music-core + + + org.onap.music + MUSIC + 3.2.37-SNAPSHOT + + + + UTF-8 + UTF-8 + UTF-8 + 1.8 + 2.0.1 + 3.6.0 + + + + + + + + + + + + + onap-releases + ONAP - Release Repository + ${nexusproxy}/${releaseNexusPath} + + + onap-staging + ONAP - Staging Repository + ${nexusproxy}/${stagingNexusPath} + + + onap-snapshots + ONAP - Snapshot Repository + ${nexusproxy}/${snapshotNexusPath} + + + onap-public + ONAP public Repository + ${nexusproxy}/content/groups/public + + + + + ${project.artifactId} + src/main/java + src/main/webapp/WEB-INF/classes + src/test/java + target/test-classes + validate + + + src/main/resources + true + + **/*.properties + **/*.xml + **/*.ccf + + + + + + ${project.basedir}/src/test/resources + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + ${maven.check.skip} + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + make-a-jar + compile + + jar + + + + + **/Sample* + + + + + + + org.apache.maven.plugins + maven-install-plugin + 2.4 + + + core + install + + install-file + + + jar + ${project.artifactId} + ${project.groupId} + ${project.version} + ${project.build.directory}/${project.artifactId}.jar + + + + + + + + + + + javax.servlet + servlet-api + 2.4 + provided + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + + + ch.qos.logback + logback-core + 1.2.3 + + + org.slf4j + slf4j-log4j12 + + + + + ch.qos.logback + logback-classic + 1.2.3 + + + org.slf4j + slf4j-log4j12 + + + + + com.att.eelf + eelf-core + 1.0.1-oss + + + org.powermock + powermock-api-mockito + + + org.powermock + powermock-module-junit4 + + + + + + + io.dropwizard.metrics + metrics-core + 4.1.0-rc3 + + + com.datastax.cassandra + cassandra-driver-core + ${cassandra.version} + + + com.datastax.cassandra + cassandra-driver-extras + ${cassandra.version} + + + org.apache.commons + commons-jcs-core + 2.2 + + + commons-codec + commons-codec + 1.11 + + + org.apache.commons + commons-lang3 + 3.8 + + + + + junit + junit + 4.12 + test + + + org.cassandraunit + cassandra-unit-spring + 3.5.0.1 + test + + + org.slf4j + slf4j-log4j12 + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + + + org.cassandraunit + cassandra-unit + + + io.dropwizard.metrics + metrics-core + + + com.addthis.metrics + reporter-config-base + + + + + org.cassandraunit + cassandra-unit-shaded + 3.5.0.1 + test + + + org.mockito + mockito-core + 2.23.4 + test + + + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.9.9 + + + com.fasterxml.jackson.core + jackson-databind + 2.9.9.2 + + + com.fasterxml.jackson.core + jackson-core + 2.9.9 + + + com.fasterxml.jackson.core + jackson-annotations + 2.9.9 + + + org.apache.httpcomponents + httpclient + + + io.swagger + swagger-jersey-jaxrs + 1.5.22 + + + com.google.guava + guava + + + de.svenkubiak + jBCrypt + 0.4.1 + + + io.netty + netty-handler + 4.1.33.Final + + + io.netty + netty-buffer + 4.1.33.Final + + + io.netty + netty-codec + 4.1.33.Final + + + io.netty + netty-common + 4.1.33.Final + + + io.netty + netty-resolver + 4.1.33.Final + + + io.netty + netty-transport + 4.1.33.Final + + + org.onap.aaf.authz + aaf-cadi-aaf + 2.1.7 + + + log4j + log4j + + + + + org.onap.aaf.authz + aaf-cadi-client + 2.1.7 + + + org.onap.aaf.authz + aaf-cadi-core + 2.1.7 + + + com.google.code.gson + gson + 2.8.5 + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + true + true + true + + https://docs.oracle.com/javase/7/docs/api/ + https://tomcat.apache.org/tomcat-7.0-doc/jspapi/ + http://docs.oracle.com/javaee/7/api/ + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + docker + + + + io.fabric8 + docker-maven-plugin + 0.19.1 + + true + 1.23 + nexus3.onap.org:10003 + + + + onap/music/music_sb + docker_music + + true + + ${docker.tag} + ${docker.latest.tag} + + ${project.basedir}/distribution/music + + + + + + onap/music/cassandra_3_11 + docker_cassandra_sec + + true + + ${docker.tag} + ${docker.latest.tag} + + ${project.basedir}/distribution/cassandra + + + + + onap/music/cassandra_job + docker_cassandra_job + + true + + ${docker.tag} + ${docker.latest.tag} + + ${project.basedir}/distribution/cassandra_job + + + + + + + + + clean-images + pre-clean + + remove + + + true + music + + + + generate-images + package + + build + + + + push-images + deploy + + push + + + onap/music/music + + + + + + + + + default + + + + + ecomp-releases + Release Repository + ${nexusproxy}/${releaseNexusPath} + + + ecomp-snapshots + Snapshot Repository + ${nexusproxy}/${snapshotNexusPath} + + + + ecomp-site + dav:${nexusproxy}${sitePath} + + + diff --git a/music-core/src/main/java/LICENSE.txt b/music-core/src/main/java/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/music-core/src/main/java/LICENSE.txt @@ -0,0 +1,24 @@ + +The following license applies to all files in this and sub-directories. Licenses +are included in individual source files where appropriate, and if it differs +from this text, it supersedes this. Any file that does not have license text +defaults to being covered by this text; not all files support the addition of +licenses. +# +# ------------------------------------------------------------------------- +# Copyright (c) 2017 AT&T Intellectual Property +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +# \ No newline at end of file diff --git a/music-core/src/main/java/org/onap/music/datastore/Condition.java b/music-core/src/main/java/org/onap/music/datastore/Condition.java new file mode 100644 index 00000000..6587748e --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/Condition.java @@ -0,0 +1,53 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.datastore; + +import java.util.Map; + +import org.onap.music.main.MusicCore; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +public class Condition { + private Map conditions; + private PreparedQueryObject selectQueryForTheRow; + + public Condition(Map conditions, PreparedQueryObject selectQueryForTheRow) { + this.conditions = conditions; + this.selectQueryForTheRow = selectQueryForTheRow; + } + + public boolean testCondition() throws Exception { + // first generate the row + ResultSet results = MusicCore.quorumGet(selectQueryForTheRow); + Row row = null; + if(results != null) { + row = results.one(); + } + if(row == null) { + throw new Exception(" No data found to update"); + } + return MusicDataStoreHandle.getDSHandle().doesRowSatisfyCondition(row, conditions); + } + } \ No newline at end of file diff --git a/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java b/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java new file mode 100755 index 00000000..5a658688 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java @@ -0,0 +1,523 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018-2019 IBM + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.datastore; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.main.CipherUtil; +import org.onap.music.main.MusicUtil; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.ColumnDefinitions; +import com.datastax.driver.core.ColumnDefinitions.Definition; +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.HostDistance; +import com.datastax.driver.core.KeyspaceMetadata; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.PoolingOptions; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.TableMetadata; +import com.datastax.driver.core.TypeCodec; +import com.datastax.driver.core.exceptions.AlreadyExistsException; +import com.datastax.driver.core.exceptions.InvalidQueryException; +import com.datastax.driver.core.exceptions.NoHostAvailableException; +import com.datastax.driver.extras.codecs.enums.EnumNameCodec; +import com.datastax.driver.extras.codecs.enums.EnumOrdinalCodec; + +/** + * @author nelson24 + * + */ +public class MusicDataStore { + + public static final String CONSISTENCY_LEVEL_ONE = "ONE"; + public static final String CONSISTENCY_LEVEL_QUORUM = "QUORUM"; + private Session session; + private Cluster cluster; + + + /** + * @param session + */ + public void setSession(Session session) { + this.session = session; + } + + /** + * @param session + */ + public Session getSession() { + return session; + } + + /** + * @param cluster + */ + public void setCluster(Cluster cluster) { + this.cluster = cluster; + } + + public Cluster getCluster() { + return this.cluster; + } + + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class); + + /** + * Connect to default Cassandra address + */ + public MusicDataStore() { + try { + connectToCassaCluster(MusicUtil.getMyCassaHost()); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); + } + } + + + /** + * @param cluster + * @param session + */ + public MusicDataStore(Cluster cluster, Session session) { + this.session = session; + this.cluster = cluster; + } + + /** + * + * @param remoteIp + * @throws MusicServiceException + */ + public MusicDataStore(String remoteIp) { + try { + connectToCassaCluster(remoteIp); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); + } + } + + /** + * + */ + public void close() { + session.close(); + } + + /** + * This method connects to cassandra cluster on specific address. + * + * @param address + */ + private void connectToCassaCluster(String address) throws MusicServiceException { + String[] addresses = null; + addresses = address.split(","); + PoolingOptions poolingOptions = new PoolingOptions(); + poolingOptions + .setConnectionsPerHost(HostDistance.LOCAL, 4, 10) + .setConnectionsPerHost(HostDistance.REMOTE, 2, 4); + + if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) { + String cassPwd = CipherUtil.decryptPKC(MusicUtil.getCassPwd()); + logger.info(EELFLoggerDelegate.applicationLogger, + "Building with credentials "+MusicUtil.getCassName()+" & "+ MusicUtil.getCassPwd()); + cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort()) + .withCredentials(MusicUtil.getCassName(), cassPwd) + //.withLoadBalancingPolicy(new RoundRobinPolicy()) + .withoutJMXReporting() + .withPoolingOptions(poolingOptions) + .addContactPoints(addresses).build(); + } else { + cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort()) + .withoutJMXReporting() + .withPoolingOptions(poolingOptions) + .addContactPoints(addresses) + .build(); + } + + + Metadata metadata = cluster.getMetadata(); + logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster " + + metadata.getClusterName() + " at " + address); + + EnumNameCodec lockTypeCodec = new EnumNameCodec(LockType.class); + cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec); + + try { + session = cluster.connect(); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY, + ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE, ex); + throw new MusicServiceException( + "Error while connecting to Cassandra cluster.. " + ex.getMessage()); + } + } + + /** + * + * @param keyspace + * @param tableName + * @param columnName + * @return DataType + */ + public DataType returnColumnDataType(String keyspace, String tableName, String columnName) { + KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace); + TableMetadata table = ks.getTable(tableName); + return table.getColumn(columnName).getType(); + + } + + /** + * + * @param keyspace + * @param tableName + * @return TableMetadata + */ + public TableMetadata returnColumnMetadata(String keyspace, String tableName) { + KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace); + return ks.getTable(tableName); + } + + /** + * + * @param keyspace + * @param tableName + * @return TableMetadata + */ + public KeyspaceMetadata returnKeyspaceMetadata(String keyspace) { + return cluster.getMetadata().getKeyspace(keyspace); + } + + + /** + * Utility function to return the Java specific object type. + * + * @param row + * @param colName + * @param colType + * @return + */ + public Object getColValue(Row row, String colName, DataType colType) { + + switch (colType.getName()) { + case VARCHAR: + return row.getString(colName); + case UUID: + return row.getUUID(colName); + case VARINT: + return row.getVarint(colName); + case BIGINT: + return row.getLong(colName); + case INT: + return row.getInt(colName); + case FLOAT: + return row.getFloat(colName); + case DOUBLE: + return row.getDouble(colName); + case BOOLEAN: + return row.getBool(colName); + case MAP: + return row.getMap(colName, String.class, String.class); + case LIST: + return row.getList(colName, String.class); + default: + return null; + } + } + + public byte[] getBlobValue(Row row, String colName, DataType colType) { + ByteBuffer bb = row.getBytes(colName); + return bb.array(); + } + + public boolean doesRowSatisfyCondition(Row row, Map condition) throws Exception { + ColumnDefinitions colInfo = row.getColumnDefinitions(); + + for (Map.Entry entry : condition.entrySet()) { + String colName = entry.getKey(); + DataType colType = colInfo.getType(colName); + Object columnValue = getColValue(row, colName, colType); + Object conditionValue = MusicUtil.convertToActualDataType(colType, entry.getValue()); + if (columnValue.equals(conditionValue) == false) + return false; + } + return true; + } + + /** + * Utility function to store ResultSet values in to a MAP for output. + * + * @param results + * @return MAP + */ + public Map> marshalData(ResultSet results) { + Map> resultMap = + new HashMap<>(); + int counter = 0; + for (Row row : results) { + ColumnDefinitions colInfo = row.getColumnDefinitions(); + HashMap resultOutput = new HashMap<>(); + for (Definition definition : colInfo) { + if (!(("vector_ts").equals(definition.getName()))) { + if(definition.getType().toString().toLowerCase().contains("blob")) { + resultOutput.put(definition.getName(), + getBlobValue(row, definition.getName(), definition.getType())); + } else { + resultOutput.put(definition.getName(), + getColValue(row, definition.getName(), definition.getType())); + } + } + } + resultMap.put("row " + counter, resultOutput); + counter++; + } + return resultMap; + } + + + // Prepared Statements 1802 additions + + public boolean executePut(PreparedQueryObject queryObject, String consistency) + throws MusicServiceException, MusicQueryException { + return executePut(queryObject, consistency, 0); + } + /** + * This Method performs DDL and DML operations on Cassandra using specified consistency level + * + * @param queryObject Object containing cassandra prepared query and values. + * @param consistency Specify consistency level for data synchronization across cassandra + * replicas + * @return Boolean Indicates operation success or failure + * @throws MusicServiceException + * @throws MusicQueryException + */ + public boolean executePut(PreparedQueryObject queryObject, String consistency,long timeSlot) + throws MusicServiceException, MusicQueryException { + + boolean result = false; + long timeOfWrite = System.currentTimeMillis(); + if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { + logger.error(EELFLoggerDelegate.errorLogger, queryObject.getQuery(),AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicQueryException("Ill formed queryObject for the request = " + "[" + + queryObject.getQuery() + "]"); + } + logger.debug(EELFLoggerDelegate.applicationLogger, + "In preprared Execute Put: the actual insert query:" + + queryObject.getQuery() + "; the values" + + queryObject.getValues()); + SimpleStatement preparedInsert = null; + + try { + preparedInsert = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray()); + if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + logger.info(EELFLoggerDelegate.applicationLogger, "Executing critical put query"); + preparedInsert.setConsistencyLevel(ConsistencyLevel.QUORUM); + } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { + logger.info(EELFLoggerDelegate.applicationLogger, "Executing simple put query"); + if(queryObject.getConsistency() == null) + preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE); + else + preparedInsert.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency())); + } else if (consistency.equalsIgnoreCase(MusicUtil.ONE)) { + preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE); + } else if (consistency.equalsIgnoreCase(MusicUtil.QUORUM)) { + preparedInsert.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); + } else if (consistency.equalsIgnoreCase(MusicUtil.ALL)) { + preparedInsert.setConsistencyLevel(ConsistencyLevel.ALL); + } + long timestamp = MusicUtil.v2sTimeStampInMicroseconds(timeSlot, timeOfWrite); + preparedInsert.setDefaultTimestamp(timestamp); + + ResultSet rs = session.execute(preparedInsert); + result = rs.wasApplied(); + + } + catch (AlreadyExistsException ae) { + // logger.error(EELFLoggerDelegate.errorLogger,"AlreadExistsException: " + ae.getMessage(),AppMessages.QUERYERROR, + // ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicQueryException("AlreadyExistsException: " + ae.getMessage(),ae); + } catch ( InvalidQueryException e ) { + // logger.error(EELFLoggerDelegate.errorLogger,"InvalidQueryException: " + e.getMessage(),AppMessages.SESSIONFAILED + " [" + // + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicQueryException("InvalidQueryException: " + e.getMessage(),e); + } catch (Exception e) { + // logger.error(EELFLoggerDelegate.errorLogger,e.getClass().toString() + ":" + e.getMessage(),AppMessages.SESSIONFAILED + " [" + // + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR, e); + throw new MusicServiceException("Executing Session Failure for Request = " + "[" + + queryObject.getQuery() + "]" + " Reason = " + e.getMessage(),e); + } + return result; + } + + /* *//** + * This method performs DDL operations on Cassandra using consistency level ONE. + * + * @param queryObject Object containing cassandra prepared query and values. + * @return ResultSet + * @throws MusicServiceException + * @throws MusicQueryException + *//* + public ResultSet executeEventualGet(PreparedQueryObject queryObject) + throws MusicServiceException, MusicQueryException { + CacheAccess queryBank = CachingUtil.getStatementBank(); + PreparedStatement preparedEventualGet = null; + if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { + logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicQueryException("Ill formed queryObject for the request = " + "[" + + queryObject.getQuery() + "]"); + } + logger.info(EELFLoggerDelegate.applicationLogger, + "Executing Eventual get query:" + queryObject.getQuery()); + + ResultSet results = null; + try { + if(queryBank.get(queryObject.getQuery()) != null ) + preparedEventualGet=queryBank.get(queryObject.getQuery()); + else { + preparedEventualGet = session.prepare(queryObject.getQuery()); + CachingUtil.updateStatementBank(queryObject.getQuery(), preparedEventualGet); + } + if(queryObject.getConsistency() == null) { + preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE); + } else { + preparedEventualGet.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency())); + } + results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray())); + + } catch (Exception ex) { + logger.error("Exception", ex); + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicServiceException(ex.getMessage()); + } + return results; + } + + *//** + * + * This method performs DDL operation on Cassandra using consistency level QUORUM. + * + * @param queryObject Object containing cassandra prepared query and values. + * @return ResultSet + * @throws MusicServiceException + * @throws MusicQueryException + *//* + public ResultSet executeCriticalGet(PreparedQueryObject queryObject) + throws MusicServiceException, MusicQueryException { + if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { + logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "[" + + queryObject.getQuery() + "]"); + } + logger.info(EELFLoggerDelegate.applicationLogger, + "Executing Critical get query:" + queryObject.getQuery()); + PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery()); + preparedEventualGet.setConsistencyLevel(ConsistencyLevel.QUORUM); + ResultSet results = null; + try { + results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray())); + } catch (Exception ex) { + logger.error("Exception", ex); + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicServiceException(ex.getMessage()); + } + return results; + + } + */ + public ResultSet executeGet(PreparedQueryObject queryObject,String consistencyLevel) throws MusicQueryException, MusicServiceException { + if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { + logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "[" + + queryObject.getQuery() + "]"); + } + ResultSet results = null; + try { + SimpleStatement statement = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray()); + + if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_ONE)) { + if(queryObject.getConsistency() == null) { + statement.setConsistencyLevel(ConsistencyLevel.ONE); + } else { + statement.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency())); + } + } + else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_QUORUM)) { + statement.setConsistencyLevel(ConsistencyLevel.QUORUM); + } + + results = session.execute(statement); + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Execute Get Error" + ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject + .getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR, ex); + throw new MusicServiceException("Execute Get Error" + ex.getMessage()); + } + + return results; + + } + + /** + * This method performs DDL operations on Cassandra using consistency level ONE. + * + * @param queryObject Object containing cassandra prepared query and values. + */ + public ResultSet executeOneConsistencyGet(PreparedQueryObject queryObject) + throws MusicServiceException, MusicQueryException { + return executeGet(queryObject, CONSISTENCY_LEVEL_ONE); + } + + /** + * + * This method performs DDL operation on Cassandra using consistency level QUORUM. + * + * @param queryObject Object containing cassandra prepared query and values. + */ + public ResultSet executeQuorumConsistencyGet(PreparedQueryObject queryObject) + throws MusicServiceException, MusicQueryException { + return executeGet(queryObject, CONSISTENCY_LEVEL_QUORUM); + } + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java b/music-core/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java new file mode 100644 index 00000000..92457d07 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java @@ -0,0 +1,124 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.datastore; + +import java.util.HashMap; +import java.util.Map; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; + +import com.datastax.driver.core.KeyspaceMetadata; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.TableMetadata; + +public class MusicDataStoreHandle { + + private static MusicDataStore mDstoreHandle = null; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStoreHandle.class); + + private MusicDataStoreHandle(){ + throw new IllegalStateException("Utility class"); + } + + /** + * + * @param remoteIp + * @return + */ + public static MusicDataStore getDSHandle(String remoteIp) { + logger.info(EELFLoggerDelegate.metricsLogger,"Acquiring data store handle"); + long start = System.currentTimeMillis(); + if (mDstoreHandle == null) { + mDstoreHandle = new MusicDataStore(remoteIp); + } + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.metricsLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); + return mDstoreHandle; + } + + /** + * + * @return + * @throws MusicServiceException + */ + public static MusicDataStore getDSHandle() throws MusicServiceException { + logger.info(EELFLoggerDelegate.metricsLogger,"Acquiring data store handle"); + long start = System.currentTimeMillis(); + if (mDstoreHandle == null) { + // Quick Fix - Best to put this into every call to getDSHandle? + if (!"localhost".equals(MusicUtil.getMyCassaHost())) { + mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost()); + } else { + mDstoreHandle = new MusicDataStore(); + } + } + if(mDstoreHandle.getSession() == null) { + String message = "Connection to Cassandra has not been enstablished." + + " Please check connection properites and reboot."; + logger.info(EELFLoggerDelegate.applicationLogger, message); + throw new MusicServiceException(message); + } + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.metricsLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); + return mDstoreHandle; + } + + + /** + * + * @param keyspace + * @param tablename + * @return + * @throws MusicServiceException + */ + public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException { + return getDSHandle().returnColumnMetadata(keyspace, tablename); + } + + /** + * + * @param keyspace + * @param tablename + * @return + * @throws MusicServiceException + */ + public static KeyspaceMetadata returnkeyspaceMetadata(String keyspace) throws MusicServiceException { + return getDSHandle().returnKeyspaceMetadata(keyspace); + } + + /** + * + * @param results + * @return + * @throws MusicServiceException + */ + public static Map> marshallResults(ResultSet results) throws MusicServiceException { + return getDSHandle().marshalData(results); + } + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/PreparedQueryObject.java b/music-core/src/main/java/org/onap/music/datastore/PreparedQueryObject.java new file mode 100644 index 00000000..fdac50be --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/PreparedQueryObject.java @@ -0,0 +1,176 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017-2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.datastore; + +import java.util.ArrayList; +import java.util.List; + +/** + * + * @author srupane + * + */ +public class PreparedQueryObject { + + + private List values; + private StringBuilder query; + private String consistency; + private String keyspaceName; + private String tableName; + private String operation; + private String primaryKeyValue; + + + /** + * Create PreparedQueryObject + */ + public PreparedQueryObject() { + this.values = new ArrayList<>(); + this.query = new StringBuilder(); + } + + /** + * Create PreparedQueryObject + * @param query query portion of the prepared query + */ + public PreparedQueryObject(String query) { + this.values = new ArrayList<>(); + this.query = new StringBuilder(query); + } + + /** + * Create PreparedQueryObject + * @param query query portion of the prepared query + * @param values to be added to the query string as prepared query + */ + public PreparedQueryObject(String query, Object...values) { + this.query = new StringBuilder(query); + this.values = new ArrayList<>(); + for (Object value: values) { + this.values.add(value); + } + } + + public String getKeyspaceName() { + return keyspaceName; + } + + public void setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public String getOperation() { + if (operation!=null) return operation; + if (query.length()==0) return null; + String queryStr = query.toString().toLowerCase(); + String firstOp = null; + int firstOpChar = query.length(); + if (queryStr.indexOf("insert")>-1 && queryStr.indexOf("insert")-1 && queryStr.indexOf("update")-1 && queryStr.indexOf("delete")-1 && queryStr.indexOf("select") getValues() { + return values; + } + + /** + * @param o object to be added as a value to the prepared query, in order + */ + public void addValue(Object o) { + this.values.add(o); + } + + /** + * Add values to the preparedQuery + * @param objs ordered list of objects to be added as values to the prepared query + */ + public void addValues(Object... objs) { + for (Object obj: objs) { + this.values.add(obj); + } + } + + /** + * @param s + */ + public void appendQueryString(String s) { + this.query.append(s); + } + public void replaceQueryString(String s) { + this.query.replace(0, query.length(), s); + } + + /** + * @return the query + */ + public String getQuery() { + return this.query.toString(); + } +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java new file mode 100644 index 00000000..a1524cc6 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java @@ -0,0 +1,37 @@ +package org.onap.music.datastore.jsonobjects; +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + + +public class JSONObject { + + private String data; + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java new file mode 100644 index 00000000..988ba3a8 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java @@ -0,0 +1,313 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.datastore.jsonobjects; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TableMetadata; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "JsonTable", description = "Json model for delete") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonDelete { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonDelete.class); + + private List columns = null; + private Map consistencyInfo; + private Map conditions; + private String ttl; + private String timestamp; + private String keyspaceName; + private String tableName; + private StringBuilder rowIdString; + private String primarKeyValue; + + + @ApiModelProperty(value = "Conditions") + public Map getConditions() { + return conditions; + } + + public void setConditions(Map conditions) { + this.conditions = conditions; + } + + @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") + public Map getConsistencyInfo() { + return consistencyInfo; + } + + public void setConsistencyInfo(Map consistencyInfo) { + this.consistencyInfo = consistencyInfo; + } + + @ApiModelProperty(value = "Column values") + public List getColumns() { + return columns; + } + + public void setColumns(List columns) { + this.columns = columns; + } + + + @ApiModelProperty(value = "Time to live information") + public String getTtl() { + return ttl; + } + + public void setTtl(String ttl) { + this.ttl = ttl; + } + + @ApiModelProperty(value = "Time stamp") + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public String getKeyspaceName() { + return keyspaceName; + } + + public void setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public StringBuilder getRowIdString() { + return rowIdString; + } + + public void setRowIdString(StringBuilder rowIdString) { + this.rowIdString = rowIdString; + } + + public String getPrimarKeyValue() { + return primarKeyValue; + } + + public void setPrimarKeyValue(String primarKeyValue) { + this.primarKeyValue = primarKeyValue; + } + + + public PreparedQueryObject genDeletePreparedQueryObj(MultivaluedMap rowParams) throws MusicQueryException { + if (logger.isDebugEnabled()) { + logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getKeyspaceName()); + logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getTableName()); + } + + PreparedQueryObject queryObject = new PreparedQueryObject(); + + if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) + || (this.getTableName() == null || this.getTableName().isEmpty())){ + + + throw new MusicQueryException("one or more path parameters are not set, please check and try again", + Status.BAD_REQUEST.getStatusCode()); + } + + EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) "); + + if(this == null) { + logger.error(EELFLoggerDelegate.errorLogger,"Required HTTP Request body is missing.", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); + + throw new MusicQueryException("Required HTTP Request body is missing.", + Status.BAD_REQUEST.getStatusCode()); + } + StringBuilder columnString = new StringBuilder(); + + int counter = 0; + List columnList = this.getColumns(); + if (columnList != null) { + for (String column : columnList) { + columnString.append(column); + if (counter != columnList.size() - 1) + columnString.append(","); + counter = counter + 1; + } + } + + // get the row specifier + RowIdentifier rowId = null; + try { + rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject); + this.setRowIdString(rowId.rowIdString); + this.setPrimarKeyValue(rowId.primarKeyValue); + if(rowId == null || rowId.primarKeyValue.isEmpty()) { + + throw new MusicQueryException("Mandatory WHERE clause is missing. Please check the input request.", + Status.BAD_REQUEST.getStatusCode()); + } + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes + .GENERALSERVICEERROR, ex); + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();*/ + throw new MusicQueryException(AppMessages.UNKNOWNERROR.toString(), Status.BAD_REQUEST.getStatusCode()); + } + String rowSpec = rowId.rowIdString.toString(); + + if ((columnList != null) && (!rowSpec.isEmpty())) { + queryObject.appendQueryString("DELETE " + columnString + " FROM " + this.getKeyspaceName() + "." + + this.getTableName() + " WHERE " + rowSpec + ";"); + } + + if ((columnList == null) && (!rowSpec.isEmpty())) { + queryObject.appendQueryString("DELETE FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " + + rowSpec + ";"); + } + + if ((columnList != null) && (rowSpec.isEmpty())) { + queryObject.appendQueryString( + "DELETE " + columnString + " FROM " + this.getKeyspaceName() + "." + rowSpec + ";"); + } + // get the conditional, if any + Condition conditionInfo; + if (this.getConditions() == null) { + conditionInfo = null; + } else { + // to avoid parsing repeatedly, just send the select query to + // obtain row + PreparedQueryObject selectQuery = new PreparedQueryObject(); + selectQuery.appendQueryString("SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " + + rowId.rowIdString + ";"); + selectQuery.addValue(rowId.primarKeyValue); + conditionInfo = new Condition(this.getConditions(), selectQuery); + } + + String consistency = this.getConsistencyInfo().get("type"); + + + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency")!=null) { + if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { + queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); + } else { + throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode()); + } + } + + queryObject.setOperation("delete"); + + return queryObject; + } + + + /** + * + * @param keyspace + * @param tablename + * @param rowParams + * @param queryObject + * @return + * @throws MusicServiceException + */ + private RowIdentifier getRowIdentifier(String keyspace, String tablename, + MultivaluedMap rowParams, PreparedQueryObject queryObject) + throws MusicServiceException { + StringBuilder rowSpec = new StringBuilder(); + int counter = 0; + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + if (tableInfo == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + throw new MusicServiceException( + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + } + StringBuilder primaryKey = new StringBuilder(); + for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { + String keyName = entry.getKey(); + List valueList = entry.getValue(); + String indValue = valueList.get(0); + DataType colType = null; + Object formattedValue = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e); + } + if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { + primaryKey.append(indValue); + } + rowSpec.append(keyName + "= ?"); + queryObject.addValue(formattedValue); + if (counter != rowParams.size() - 1) { + rowSpec.append(" AND "); + } + counter = counter + 1; + } + return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); + } + + private class RowIdentifier { + private String primarKeyValue; + private StringBuilder rowIdString; + @SuppressWarnings("unused") + public PreparedQueryObject queryObject; // the string with all the row + // identifiers separated by AND + + public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, + PreparedQueryObject queryObject) { + this.primarKeyValue = primaryKeyValue; + this.rowIdString = rowIdString; + this.queryObject = queryObject; + } + } +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java new file mode 100644 index 00000000..a06e8ea9 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java @@ -0,0 +1,120 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ +package org.onap.music.datastore.jsonobjects; + +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ApiModel(value = "JsonIndex", description = "Index Object") +public class JsonIndex { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonIndex.class); + + private String indexName; + private String keyspaceName; + private String tableName; + private String fieldName; + + public JsonIndex(String indexName,String keyspaceName,String tableName,String fieldName) { + this.indexName = indexName; + this.keyspaceName= keyspaceName; + this.tableName = tableName; + this.fieldName = fieldName; + } + + @ApiModelProperty(value = "Index Name") + public String getIndexName() { + return indexName; + } + + public JsonIndex setIndexName(String indexName) { + this.indexName = indexName; + return this; + } + + @ApiModelProperty(value = "Keyspace name") + public String getKeyspaceName() { + return keyspaceName; + } + + public JsonIndex setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + return this; + } + + public JsonIndex setTableName(String tableName) { + this.tableName = tableName; + return this; + } + + @ApiModelProperty(value = "Table name") + public String getTableName() { + return tableName; + } + + public JsonIndex setFieldName(String fieldName) { + this.fieldName = fieldName; + return this; + } + + @ApiModelProperty(value = "Field name") + public String getFieldName() { + return fieldName; + } + + public PreparedQueryObject genCreateIndexQuery() { + + if (logger.isDebugEnabled()) { + logger.debug("Came inside genCreateIndexQuery method"); + } + + logger.info("genCreateIndexQuery indexName ::" + indexName); + logger.info("genCreateIndexQuery keyspaceName ::" + keyspaceName); + logger.info("genCreateIndexQuery tableName ::" + tableName); + logger.info("genCreateIndexQuery fieldName ::" + fieldName); + + long start = System.currentTimeMillis(); + + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString("Create index if not exists " + this.getIndexName() + " on " + this.getKeyspaceName() + "." + + this.getTableName() + " (" + this.getFieldName() + ");"); + + long end = System.currentTimeMillis(); + + logger.info(EELFLoggerDelegate.applicationLogger, + "Time taken for setting up query in create index:" + (end - start)); + + logger.info(EELFLoggerDelegate.applicationLogger, + " create index query :" + query.getQuery()); + + return query; + } + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java new file mode 100644 index 00000000..57ff245a --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java @@ -0,0 +1,420 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.datastore.jsonobjects; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TableMetadata; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "InsertTable", description = "Json model for table vlaues insert") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonInsert implements Serializable { + private static final long serialVersionUID = 1L; + private String keyspaceName; + private String tableName; + private transient Map values; + private String ttl; + private String timestamp; + private transient Map rowSpecification; + private Map consistencyInfo; + private Map objectMap; + private String primaryKeyVal; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonInsert.class); + + @ApiModelProperty(value = "objectMap",hidden = true) + public Map getObjectMap() { + return objectMap; + } + + public void setObjectMap(Map objectMap) { + this.objectMap = objectMap; + } + + @ApiModelProperty(value = "keyspace") + public String getKeyspaceName() { + return keyspaceName; + } + + public void setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + } + + @ApiModelProperty(value = "Table name") + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") + public Map getConsistencyInfo() { + return consistencyInfo; + } + + public void setConsistencyInfo(Map consistencyInfo) { + this.consistencyInfo = consistencyInfo; + } + + @ApiModelProperty(value = "Columns and tables support an optional " + + "expiration period called TTL (time-to-live) in seconds.", + notes="TTL precision is one second, which is calculated by the coordinator " + + "node. When using TTL, ensure that all nodes in the cluster have synchronized clocks.",allowEmptyValue = true) + public String getTtl() { + return ttl; + } + + public void setTtl(String ttl) { + this.ttl = ttl; + } + + @ApiModelProperty(value = "Time stamp (epoch_in_microseconds)", + notes = "Marks inserted data (write time) with TIMESTAMP. " + + "Enter the time since epoch (January 1, 1970) in microseconds." + + "By default, the actual time of write is used.", allowEmptyValue = true) + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + @ApiModelProperty(value = "Json Object of key/values", notes="Where key is the column name and value is the data value for that column.", + example = "{'emp_id': 'df98a3d40cd6','emp_name': 'john'," + + "'emp_salary': 50,'address':{'street' : '1 Some way','city' : 'New York'}}") + public Map getValues() { + return values; + } + + public void setValues(Map values) { + this.values = values; + } + + @ApiModelProperty(value = "Information for selecting specific rows for insert",hidden = true) + public Map getRowSpecification() { + return rowSpecification; + } + + public void setRowSpecification(Map rowSpecification) { + this.rowSpecification = rowSpecification; + } + + public String getPrimaryKeyVal() { + return primaryKeyVal; + } + + public void setPrimaryKeyVal(String primaryKeyVal) { + this.primaryKeyVal = primaryKeyVal; + } + + public byte[] serialize() { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutput out = null; + try { + out = new ObjectOutputStream(bos); + out.writeObject(this); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.DATAERROR); + } + return bos.toByteArray(); + } + + /** + * Generate TableInsertQuery + * @return + * @throws MusicQueryException + */ + public PreparedQueryObject genInsertPreparedQueryObj() throws MusicQueryException { + if (logger.isDebugEnabled()) { + logger.debug("Coming inside genTableInsertQuery method " + this.getKeyspaceName()); + logger.debug("Coming inside genTableInsertQuery method " + this.getTableName()); + } + + PreparedQueryObject queryObject = new PreparedQueryObject(); + TableMetadata tableInfo = null; + try { + tableInfo = MusicDataStoreHandle.returnColumnMetadata(this.getKeyspaceName(), this.getTableName()); + if(tableInfo == null) { + throw new MusicQueryException("Table name doesn't exists. Please check the table name.", + Status.BAD_REQUEST.getStatusCode()); + } + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + throw new MusicQueryException(e.getMessage(),Status.BAD_REQUEST.getStatusCode()); + + } + String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); + StringBuilder fieldsString = new StringBuilder("(vector_ts,"); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + StringBuilder valueString = new StringBuilder("(" + "?" + ","); + queryObject.addValue(vectorTs); + + Map valuesMap = this.getValues(); + if (valuesMap==null) { + throw new MusicQueryException("Nothing to insert. No values provided in request.", + Status.BAD_REQUEST.getStatusCode()); + } + int counter = 0; + String primaryKey = ""; + for (Map.Entry entry : valuesMap.entrySet()) { + fieldsString.append("" + entry.getKey()); + Object valueObj = entry.getValue(); + if (primaryKeyName.equals(entry.getKey())) { + primaryKey = entry.getValue() + ""; + primaryKey = primaryKey.replace("'", "''"); + } + DataType colType = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + } catch(NullPointerException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey + (), AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR, ex); + throw new MusicQueryException("Invalid column name : " + entry.getKey(), + Status.BAD_REQUEST.getStatusCode()); + } + + Object formattedValue = null; + try { + formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e); + } + valueString.append("?"); + + queryObject.addValue(formattedValue); + + if (counter == valuesMap.size() - 1) { + fieldsString.append(")"); + valueString.append(")"); + } else { + fieldsString.append(","); + valueString.append(","); + } + counter = counter + 1; + } + + //blobs.. + Map objectMap = this.getObjectMap(); + if(objectMap != null) { + for (Map.Entry entry : objectMap.entrySet()) { + if(counter > 0) { + fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ","); + valueString.replace(valueString.length()-1, valueString.length(), ","); + } + fieldsString.append("" + entry.getKey()); + byte[] valueObj = entry.getValue(); + if (primaryKeyName.equals(entry.getKey())) { + primaryKey = entry.getValue() + ""; + primaryKey = primaryKey.replace("'", "''"); + } + DataType colType = tableInfo.getColumn(entry.getKey()).getType(); + ByteBuffer formattedValue = null; + if(colType.toString().toLowerCase().contains("blob")) { + formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + } + valueString.append("?"); + queryObject.addValue(formattedValue); + counter = counter + 1; + fieldsString.append(","); + valueString.append(","); + } + } + this.setPrimaryKeyVal(primaryKey); + if(primaryKey == null || primaryKey.length() <= 0) { + logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName ); + throw new MusicQueryException("Some required partition key parts are missing: " + primaryKeyName, + Status.BAD_REQUEST.getStatusCode()); + } + + fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")"); + valueString.replace(valueString.length()-1, valueString.length(), ")"); + + queryObject.appendQueryString("INSERT INTO " + this.getKeyspaceName() + "." + this.getTableName() + " " + + fieldsString + " VALUES " + valueString); + + String ttl = this.getTtl(); + String timestamp = this.getTimestamp(); + + if ((ttl != null) && (timestamp != null)) { + logger.info(EELFLoggerDelegate.applicationLogger, "both there"); + queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); + queryObject.addValue(Integer.parseInt(ttl)); + queryObject.addValue(Long.parseLong(timestamp)); + } + + if ((ttl != null) && (timestamp == null)) { + logger.info(EELFLoggerDelegate.applicationLogger, "ONLY TTL there"); + queryObject.appendQueryString(" USING TTL ?"); + queryObject.addValue(Integer.parseInt(ttl)); + } + + if ((ttl == null) && (timestamp != null)) { + logger.info(EELFLoggerDelegate.applicationLogger, "ONLY timestamp there"); + queryObject.appendQueryString(" USING TIMESTAMP ?"); + queryObject.addValue(Long.parseLong(timestamp)); + } + + queryObject.appendQueryString(";"); + + String consistency = this.getConsistencyInfo().get("type"); + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency") != null) { + if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { + queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); + } else { + throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode()); + } + } + queryObject.setOperation("insert"); + + logger.info("Data insert Query ::::: " + queryObject.getQuery()); + + return queryObject; + } + + /** + * + * @param rowParams + * @return + * @throws MusicQueryException + */ + public PreparedQueryObject genSelectCriticalPreparedQueryObj(MultivaluedMap rowParams) throws MusicQueryException { + + PreparedQueryObject queryObject = new PreparedQueryObject(); + + if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) + || (this.getTableName() == null || this.getTableName().isEmpty())){ + throw new MusicQueryException("one or more path parameters are not set, please check and try again", + Status.BAD_REQUEST.getStatusCode()); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) "); + RowIdentifier rowId = null; + try { + rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject); + this.setPrimaryKeyVal(rowId.primarKeyValue); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes + .GENERALSERVICEERROR, ex); + throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode()); + } + + queryObject.appendQueryString( + "SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " + rowId.rowIdString + ";"); + + return queryObject; + } + + private class RowIdentifier { + public String primarKeyValue; + public StringBuilder rowIdString; + @SuppressWarnings("unused") + public PreparedQueryObject queryObject; // the string with all the row + // identifiers separated by AND + + public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, + PreparedQueryObject queryObject) { + this.primarKeyValue = primaryKeyValue; + this.rowIdString = rowIdString; + this.queryObject = queryObject; + } + } + + /** + * + * @param keyspace + * @param tablename + * @param rowParams + * @param queryObject + * @return + * @throws MusicServiceException + */ + private RowIdentifier getRowIdentifier(String keyspace, String tablename, + MultivaluedMap rowParams, PreparedQueryObject queryObject) + throws MusicServiceException { + StringBuilder rowSpec = new StringBuilder(); + int counter = 0; + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + if (tableInfo == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + throw new MusicServiceException( + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + } + StringBuilder primaryKey = new StringBuilder(); + for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { + String keyName = entry.getKey(); + List valueList = entry.getValue(); + String indValue = valueList.get(0); + DataType colType = null; + Object formattedValue = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e); + } + if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { + primaryKey.append(indValue); + } + rowSpec.append(keyName + "= ?"); + queryObject.addValue(formattedValue); + if (counter != rowParams.size() - 1) { + rowSpec.append(" AND "); + } + counter = counter + 1; + } + return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); + } + + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java new file mode 100644 index 00000000..cada1c00 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java @@ -0,0 +1,163 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.datastore.jsonobjects; + +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.main.MusicUtil; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "JsonTable", description = "Json model creating new keyspace") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonKeySpace { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonKeySpace.class); + private String keyspaceName; + private Map replicationInfo; + private String durabilityOfWrites; + private Map consistencyInfo; + + @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") + public Map getConsistencyInfo() { + return consistencyInfo; + } + + public void setConsistencyInfo(Map consistencyInfo) { + this.consistencyInfo = consistencyInfo; + } + + @ApiModelProperty(value = "Replication information") + public Map getReplicationInfo() { + return replicationInfo; + } + + public void setReplicationInfo(Map replicationInfo) { + this.replicationInfo = replicationInfo; + } + + @ApiModelProperty(value = "Durability", allowableValues = "true,false") + public String getDurabilityOfWrites() { + return durabilityOfWrites; + } + + public void setDurabilityOfWrites(String durabilityOfWrites) { + this.durabilityOfWrites = durabilityOfWrites; + } + + @ApiModelProperty(value = "Keyspace name") + public String getKeyspaceName() { + return keyspaceName; + } + + public void setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + } + + /** + * Will generate query to create Keyspacce. + * + * @throws MusicQueryException + */ + @SuppressWarnings("deprecation") + public PreparedQueryObject genCreateKeyspaceQuery() throws MusicQueryException { + + if (logger.isDebugEnabled()) { + logger.debug("Came inside createKeyspace method"); + } + + String keyspaceName = this.getKeyspaceName(); + String durabilityOfWrites = this.getDurabilityOfWrites(); + String consistency = MusicUtil.EVENTUAL; + + logger.info("genCreateKeyspaceQuery keyspaceName ::" + keyspaceName); + logger.info("genCreateKeyspaceQuery class :: " + this.getReplicationInfo().get("class")); + logger.info("genCreateKeyspaceQuery replication_factor :: " + this.getReplicationInfo().get("replication_factor")); + logger.info("genCreateKeyspaceQuery durabilityOfWrites :: " + durabilityOfWrites); + + PreparedQueryObject queryObject = new PreparedQueryObject(); + + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency") != null) { + if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { + queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); + }else { + throw new MusicQueryException("Invalid Consistency type",Status.BAD_REQUEST.getStatusCode()); + } + } + + long start = System.currentTimeMillis(); + Map replicationInfo = this.getReplicationInfo(); + String repString = null; + try { + repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}"; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + } + queryObject.appendQueryString("CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString); + if (this.getDurabilityOfWrites() != null) { + queryObject.appendQueryString(" AND durable_writes = " + this.getDurabilityOfWrites()); + } + queryObject.appendQueryString(";"); + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger, + "Time taken for setting up query in create keyspace:" + (end - start)); + + return queryObject; + } + + /** + * Will generate Query to drop a keyspace. + * + * @return + */ + public PreparedQueryObject genDropKeyspaceQuery() { + if (logger.isDebugEnabled()) { + logger.debug("Coming inside genDropKeyspaceQuery method "+this.getKeyspaceName()); + } + + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("DROP KEYSPACE " + this.getKeyspaceName() + ";"); + + return queryObject; + } + + @Override + public String toString() { + return "CassaKeyspaceObject [keyspaceName=" + keyspaceName + ", replicationInfo=" + replicationInfo + + "durabilityOfWrites=" + durabilityOfWrites + "]"; + } + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java new file mode 100644 index 00000000..86bbe3dc --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.datastore.jsonobjects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "Json Leasesd Lock", description = "model for leased lock") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonLeasedLock { + private long leasePeriod; + + @ApiModelProperty(value = "Lease period") + public long getLeasePeriod() { + return leasePeriod; + } + + public void setLeasePeriod(long leasePeriod) { + this.leasePeriod = leasePeriod; + } + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java new file mode 100644 index 00000000..f353c018 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.datastore.jsonobjects; + +import org.onap.music.lockingservice.cassandra.LockType; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "Json Lock Type", description = "Model for Lock Type") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonLock { + private LockType locktype; + + @ApiModelProperty( + value = "Type of music lock", + name = "lockType", + allowEmptyValue = false, + allowableValues = "READ|WRITE") + public LockType getLocktype() { + return this.locktype; + } + + public void setLockType(LockType locktype) { + this.locktype = locktype; + } +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java new file mode 100644 index 00000000..e354b4b0 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java @@ -0,0 +1,208 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.datastore.jsonobjects; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TableMetadata; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonSelect implements Serializable { + private Map consistencyInfo; + private String keyspaceName; + private String tableName; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonSelect.class); + + + + public Map getConsistencyInfo() { + return consistencyInfo; + } + + public void setConsistencyInfo(Map consistencyInfo) { + this.consistencyInfo = consistencyInfo; + } + + public String getKeyspaceName() { + return keyspaceName; + } + + public void setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public byte[] serialize() { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutput out = null; + try { + out = new ObjectOutputStream(bos); + out.writeObject(this); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); + } + return bos.toByteArray(); + } + + /** + * genSelectQuery + * + * @return + * @throws MusicQueryException + */ + public PreparedQueryObject genSelectQuery(MultivaluedMap rowParams) throws MusicQueryException { + + if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) + || (this.getTableName() == null || this.getTableName().isEmpty())){ + throw new MusicQueryException("one or more path parameters are not set, please check and try again", + Status.BAD_REQUEST.getStatusCode()); + } + EELFLoggerDelegate.mdcPut("keyspace", "( " + this.getKeyspaceName() + " ) "); + PreparedQueryObject queryObject = new PreparedQueryObject(); + + if (rowParams.isEmpty()) { // select all + queryObject.appendQueryString("SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + ";"); + } else { + int limit = -1; // do not limit the number of results + try { + queryObject = selectSpecificQuery(this.getKeyspaceName(), this.getTableName(), rowParams, limit); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, + ErrorTypes.GENERALSERVICEERROR, ex); + + throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode()); + } + } + + return queryObject; + } + + public PreparedQueryObject selectSpecificQuery(String keyspace, + String tablename, MultivaluedMap rowParams, int limit) + throws MusicServiceException { + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder rowIdString = getRowIdentifier(keyspace, + tablename,rowParams,queryObject).rowIdString; + queryObject.appendQueryString( + "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowIdString); + if (limit != -1) { + queryObject.appendQueryString(" LIMIT " + limit); + } + queryObject.appendQueryString(";"); + return queryObject; + } + + private class RowIdentifier { + public String primarKeyValue; + public StringBuilder rowIdString; + @SuppressWarnings("unused") + public PreparedQueryObject queryObject; // the string with all the row + // identifiers separated by AND + + public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, + PreparedQueryObject queryObject) { + this.primarKeyValue = primaryKeyValue; + this.rowIdString = rowIdString; + this.queryObject = queryObject; + } + } + + /** + * + * @param keyspace + * @param tablename + * @param rowParams + * @param queryObject + * @return + * @throws MusicServiceException + */ + private RowIdentifier getRowIdentifier(String keyspace, String tablename, + MultivaluedMap rowParams, PreparedQueryObject queryObject) + throws MusicServiceException { + StringBuilder rowSpec = new StringBuilder(); + int counter = 0; + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + if (tableInfo == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + throw new MusicServiceException( + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + } + StringBuilder primaryKey = new StringBuilder(); + for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { + String keyName = entry.getKey(); + List valueList = entry.getValue(); + String indValue = valueList.get(0); + DataType colType = null; + Object formattedValue = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e); + } + if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { + primaryKey.append(indValue); + } + rowSpec.append(keyName + "= ?"); + queryObject.addValue(formattedValue); + if (counter != rowParams.size() - 1) { + rowSpec.append(" AND "); + } + counter = counter + 1; + } + return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); + } + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java new file mode 100644 index 00000000..ef560144 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java @@ -0,0 +1,381 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.datastore.jsonobjects; + +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.apache.commons.lang3.StringUtils; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.main.MusicUtil; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "JsonTable", description = "Defines the Json for Creating a new Table.") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonTable { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonTable.class); + + private String keyspaceName; + private String tableName; + + private Map fields; + private Map properties; + private String primaryKey; + private String partitionKey; + private String clusteringKey; + private String filteringKey; + private String clusteringOrder; + private Map consistencyInfo; + + @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") + public Map getConsistencyInfo() { + return consistencyInfo; + } + + public void setConsistencyInfo(Map consistencyInfo) { + this.consistencyInfo = consistencyInfo; + } + + @ApiModelProperty(value = "Properties") + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + @ApiModelProperty(value = "Fields") + public Map getFields() { + return fields; + } + + public void setFields(Map fields) { + this.fields = fields; + } + + @ApiModelProperty(value = "KeySpace Name") + public String getKeyspaceName() { + return keyspaceName; + } + + public void setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + } + + @ApiModelProperty(value = "Table Name") + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + @ApiModelProperty(value = "Clustering Order", notes = "") + public String getClusteringOrder() { + return clusteringOrder; + } + + public void setClusteringOrder(String clusteringOrder) { + this.clusteringOrder = clusteringOrder; + } + + @ApiModelProperty(value = "Primary Key") + public String getPrimaryKey() { + return primaryKey; + } + + public void setPrimaryKey(String primaryKey) { + this.primaryKey = primaryKey; + } + + public String getClusteringKey() { + return clusteringKey; + } + + public void setClusteringKey(String clusteringKey) { + this.clusteringKey = clusteringKey; + } + + public String getFilteringKey() { + return filteringKey; + } + + public void setFilteringKey(String filteringKey) { + this.filteringKey = filteringKey; + } + + public String getPartitionKey() { + return partitionKey; + } + + public void setPartitionKey(String partitionKey) { + this.partitionKey = partitionKey; + } + + public PreparedQueryObject genCreateTableQuery() throws MusicQueryException { + if (logger.isDebugEnabled()) { + logger.debug("Coming inside genCreateTableQuery method " + this.getKeyspaceName()); + logger.debug("Coming inside genCreateTableQuery method " + this.getTableName()); + } + + String primaryKey = null; + String partitionKey = this.getPartitionKey(); + String clusterKey = this.getClusteringKey(); + String filteringKey = this.getFilteringKey(); + if (filteringKey != null) { + clusterKey = clusterKey + "," + filteringKey; + } + primaryKey = this.getPrimaryKey(); // get primaryKey if available + + PreparedQueryObject queryObject = new PreparedQueryObject(); + // first read the information about the table fields + Map fields = this.getFields(); + if (fields == null) { + throw new MusicQueryException( + "Create Table Error: No fields in request", Status.BAD_REQUEST.getStatusCode()); + } + StringBuilder fieldsString = new StringBuilder("(vector_ts text,"); + int counter = 0; + for (Map.Entry entry : fields.entrySet()) { + if (entry.getKey().equals("PRIMARY KEY")) { + primaryKey = entry.getValue(); // replaces primaryKey + primaryKey = primaryKey.trim(); + } else { + if (counter == 0 ) fieldsString.append("" + entry.getKey() + " " + entry.getValue() + ""); + else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + ""); + } + + if (counter != (fields.size() - 1) ) { + counter = counter + 1; + } else { + + if((primaryKey != null) && (partitionKey == null)) { + primaryKey = primaryKey.trim(); + int count1 = StringUtils.countMatches(primaryKey, ')'); + int count2 = StringUtils.countMatches(primaryKey, '('); + if (count1 != count2) { + throw new MusicQueryException( + "Create Table Error: primary key '(' and ')' do not match, primary key=" + primaryKey, + Status.BAD_REQUEST.getStatusCode()); + } + + if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) ) { + if (primaryKey.contains(",") ) { + partitionKey= primaryKey.substring(0,primaryKey.indexOf(',')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + clusterKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index + clusterKey=clusterKey.replaceAll("[)]+", ""); + } else { + partitionKey=primaryKey; + partitionKey=partitionKey.replaceAll("[\\)]+",""); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + clusterKey=""; + } + } else { // not null and has ) before the last char + partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + partitionKey = partitionKey.trim(); + clusterKey= primaryKey.substring(primaryKey.indexOf(')')); + clusterKey=clusterKey.replaceAll("[\\(]+",""); + clusterKey=clusterKey.replaceAll("[\\)]+",""); + clusterKey = clusterKey.trim(); + if (clusterKey.indexOf(',') == 0) { + clusterKey=clusterKey.substring(1); + } + clusterKey = clusterKey.trim(); + if (clusterKey.equals(",") ) clusterKey=""; // print error if needed ( ... ),) + } + + if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) + && (partitionKey.equalsIgnoreCase(clusterKey) || + clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) { + logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey + " and primary key=" + primaryKey ); + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( + "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ") of" + + " primary key=" + primaryKey) + .toMap()).build();*/ + throw new MusicQueryException("Create Table primary key error: clusterKey(" + clusterKey + + ") equals/contains/overlaps partitionKey(" + partitionKey + ") of" + " primary key=" + + primaryKey, Status.BAD_REQUEST.getStatusCode()); + + } + + if (partitionKey.isEmpty() ) primaryKey=""; + else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; + else primaryKey=" (" + partitionKey + ")," + clusterKey; + + + if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); + + } else { // end of length > 0 + + if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) + && (partitionKey.equalsIgnoreCase(clusterKey) || + clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) { + logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey); + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( + "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ")") + .toMap()).build();*/ + throw new MusicQueryException( + "Create Table primary key error: clusterKey(" + clusterKey + + ") equals/contains/overlaps partitionKey(" + partitionKey + ")", + Status.BAD_REQUEST.getStatusCode()); + } + + if (partitionKey.isEmpty() ) primaryKey=""; + else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; + else primaryKey=" (" + partitionKey + ")," + clusterKey; + + if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); + } + fieldsString.append(")"); + + } // end of last field check + + } // end of for each + // information about the name-value style properties + Map propertiesMap = this.getProperties(); + StringBuilder propertiesString = new StringBuilder(); + if (propertiesMap != null) { + counter = 0; + for (Map.Entry entry : propertiesMap.entrySet()) { + Object ot = entry.getValue(); + String value = ot + ""; + if (ot instanceof String) { + value = "'" + value + "'"; + } else if (ot instanceof Map) { + @SuppressWarnings("unchecked") + Map otMap = (Map) ot; + try { + value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}"; + } catch (Exception e) { + throw new MusicQueryException(e.getMessage(), + Status.BAD_REQUEST.getStatusCode()); + } + } + + propertiesString.append(entry.getKey() + "=" + value + ""); + if (counter != propertiesMap.size() - 1) + propertiesString.append(" AND "); + + counter = counter + 1; + } + } + + String clusteringOrder = this.getClusteringOrder(); + + if (clusteringOrder != null && !(clusteringOrder.isEmpty())) { + String[] arrayClusterOrder = clusteringOrder.split("[,]+"); + + for (int i = 0; i < arrayClusterOrder.length; i++) { + String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+"); + if ( (clusterS.length ==2) && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) { + continue; + } else { + /*return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:"+ clusteringOrder+".") + .toMap()).build();*/ + + throw new MusicQueryException( + "createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:" + + clusteringOrder + ".", + Status.BAD_REQUEST.getStatusCode()); + } + // add validation for column names in cluster key + } + + if (!(clusterKey.isEmpty())) { + clusteringOrder = "CLUSTERING ORDER BY (" +clusteringOrder +")"; + //cjc check if propertiesString.length() >0 instead propertiesMap + if (propertiesMap != null) { + propertiesString.append(" AND "+ clusteringOrder); + } else { + propertiesString.append(clusteringOrder); + } + } else { + logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty "); + } + } //if non empty + + queryObject.appendQueryString( + "CREATE TABLE " + this.getKeyspaceName() + "." + this.getTableName() + " " + fieldsString); + + + if (propertiesString != null && propertiesString.length()>0 ) + queryObject.appendQueryString(" WITH " + propertiesString); + queryObject.appendQueryString(";"); + + return queryObject; + } + + /** + * + * @return + */ + public PreparedQueryObject genCreateShadowLockingTableQuery() { + if (logger.isDebugEnabled()) { + logger.debug("Coming inside genCreateShadowLockingTableQuery method " + this.getKeyspaceName()); + logger.debug("Coming inside genCreateShadowLockingTableQuery method " + this.getTableName()); + } + + String tableName = "unsyncedKeys_" + this.getTableName(); + String tabQuery = "CREATE TABLE IF NOT EXISTS " + this.getKeyspaceName() + "." + tableName + + " ( key text,PRIMARY KEY (key) );"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(tabQuery); + + return queryObject; + } + + /** + * genDropTableQuery + * + * @return PreparedQueryObject + */ + public PreparedQueryObject genDropTableQuery() { + if (logger.isDebugEnabled()) { + logger.debug("Coming inside genDropTableQuery method " + this.getKeyspaceName()); + logger.debug("Coming inside genDropTableQuery method " + this.getTableName()); + } + + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString("DROP TABLE " + this.getKeyspaceName() + "." + this.getTableName() + ";"); + logger.info("Delete Query ::::: " + query.getQuery()); + + return query; + } + + +} diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java new file mode 100644 index 00000000..12508de0 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java @@ -0,0 +1,416 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.datastore.jsonobjects; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ReturnType; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TableMetadata; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "JsonTable", description = "Json model for table update") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonUpdate implements Serializable { + private String keyspaceName; + private String tableName; + private transient Map values; + private String ttl; + private String timestamp; + private Map consistencyInfo; + private transient Map conditions; + private transient Map rowSpecification; + private StringBuilder rowIdString; + private String primarKeyValue; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonUpdate.class); + + @ApiModelProperty(value = "Conditions") + public Map getConditions() { + return conditions; + } + + public void setConditions(Map conditions) { + this.conditions = conditions; + } + + @ApiModelProperty(value = "Information for selecting sepcific rows") + public Map getRow_specification() { + return rowSpecification; + } + + public void setRow_specification(Map rowSpecification) { + this.rowSpecification = rowSpecification; + } + + + @ApiModelProperty(value = "Keyspace name") + public String getKeyspaceName() { + return keyspaceName; + } + + public void setKeyspaceName(String keyspaceName) { + this.keyspaceName = keyspaceName; + } + + @ApiModelProperty(value = "Table name") + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") + public Map getConsistencyInfo() { + return consistencyInfo; + } + + public void setConsistencyInfo(Map consistencyInfo) { + this.consistencyInfo = consistencyInfo; + } + + @ApiModelProperty(value = "Time to live value") + public String getTtl() { + return ttl; + } + + public void setTtl(String ttl) { + this.ttl = ttl; + } + + @ApiModelProperty(value = "Time stamp") + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + @ApiModelProperty(value = "Column values") + public Map getValues() { + return values; + } + + public void setValues(Map values) { + this.values = values; + } + + public StringBuilder getRowIdString() { + return rowIdString; + } + + public void setRowIdString(StringBuilder rowIdString) { + this.rowIdString = rowIdString; + } + + public String getPrimarKeyValue() { + return primarKeyValue; + } + + public void setPrimarKeyValue(String primarKeyValue) { + this.primarKeyValue = primarKeyValue; + } + + public byte[] serialize() { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutput out = null; + try { + out = new ObjectOutputStream(bos); + out.writeObject(this); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.DATAERROR); + } + return bos.toByteArray(); + } + + /** + * Generate TableInsertQuery + * @return + * @throws MusicQueryException + */ + public PreparedQueryObject genUpdatePreparedQueryObj(MultivaluedMap rowParams) throws MusicQueryException { + if (logger.isDebugEnabled()) { + logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getKeyspaceName()); + logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getTableName()); + } + + PreparedQueryObject queryObject = new PreparedQueryObject(); + + if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) || + (this.getTableName() == null || this.getTableName().isEmpty())){ + + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build();*/ + + throw new MusicQueryException("one or more path parameters are not set, please check and try again", + Status.BAD_REQUEST.getStatusCode()); + } + + EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) "); + long startTime = System.currentTimeMillis(); + String operationId = UUID.randomUUID().toString(); // just for infoging purposes. + String consistency = this.getConsistencyInfo().get("type"); + + logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency + + " update-" + operationId + "-------------------------"); + // obtain the field value pairs of the update + + Map valuesMap = this.getValues(); + + TableMetadata tableInfo; + + try { + tableInfo = MusicDataStoreHandle.returnColumnMetadata(this.getKeyspaceName(), this.getTableName()); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes + .GENERALSERVICEERROR, e); + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();*/ + throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); + }catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR, ErrorSeverity.CRITICAL, + ErrorTypes.GENERALSERVICEERROR); + throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); + } + + if (tableInfo == null) { + logger.error(EELFLoggerDelegate.errorLogger,"Table information not found. Please check input for table name= "+this.getTableName(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Table information not found. Please check input for table name= " + + this.getKeyspaceName() + "." + this.getTableName()).toMap()).build();*/ + + throw new MusicQueryException("Table information not found. Please check input for table name= " + + this.getKeyspaceName() + "." + this.getTableName(), Status.BAD_REQUEST.getStatusCode()); + } + + String vectorTs = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + StringBuilder fieldValueString = new StringBuilder("vector_ts=?,"); + queryObject.addValue(vectorTs); + int counter = 0; + for (Map.Entry entry : valuesMap.entrySet()) { + Object valueObj = entry.getValue(); + DataType colType = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + } catch(NullPointerException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex, "Invalid column name : "+entry.getKey(), ex); + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE). + * setError("Invalid column name : "+entry.getKey()).toMap()).build();*/ + + throw new MusicQueryException("Invalid column name : " + entry.getKey(),Status.BAD_REQUEST.getStatusCode()); + } + Object valueString = null; + try { + valueString = MusicUtil.convertToActualDataType(colType, valueObj); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e); + } + fieldValueString.append(entry.getKey() + "= ?"); + queryObject.addValue(valueString); + if (counter != valuesMap.size() - 1) { + fieldValueString.append(","); + } + counter = counter + 1; + } + String ttl = this.getTtl(); + String timestamp = this.getTimestamp(); + + queryObject.appendQueryString("UPDATE " + this.getKeyspaceName() + "." + this.getTableName() + " "); + if ((ttl != null) && (timestamp != null)) { + logger.info("both there"); + queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); + queryObject.addValue(Integer.parseInt(ttl)); + queryObject.addValue(Long.parseLong(timestamp)); + } + + if ((ttl != null) && (timestamp == null)) { + logger.info("ONLY TTL there"); + queryObject.appendQueryString(" USING TTL ?"); + queryObject.addValue(Integer.parseInt(ttl)); + } + + if ((ttl == null) && (timestamp != null)) { + logger.info("ONLY timestamp there"); + queryObject.appendQueryString(" USING TIMESTAMP ?"); + queryObject.addValue(Long.parseLong(timestamp)); + } + + // get the row specifier + RowIdentifier rowId = null; + try { + rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject); + this.setRowIdString(rowId.rowIdString); + this.setPrimarKeyValue(rowId.primarKeyValue); + if(rowId == null || rowId.primarKeyValue.isEmpty()) { + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap()).build();*/ + + throw new MusicQueryException("Mandatory WHERE clause is missing. Please check the input request.", + Status.BAD_REQUEST.getStatusCode()); + } + } catch (MusicQueryException ex) { + throw new MusicQueryException("Mandatory WHERE clause is missing. Please check the input request.", + Status.BAD_REQUEST.getStatusCode()); + + }catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes + .GENERALSERVICEERROR, ex); + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();*/ + + throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode()); + + } + + + + queryObject.appendQueryString( + " SET " + fieldValueString + " WHERE " + rowId.rowIdString + ";"); + + + + // get the conditional, if any + Condition conditionInfo; + if (this.getConditions() == null) { + conditionInfo = null; + } else { + // to avoid parsing repeatedly, just send the select query to obtain row + PreparedQueryObject selectQuery = new PreparedQueryObject(); + selectQuery.appendQueryString("SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " + + rowId.rowIdString + ";"); + selectQuery.addValue(rowId.primarKeyValue); + conditionInfo = new Condition(this.getConditions(), selectQuery); + } + + ReturnType operationResult = null; + long jsonParseCompletionTime = System.currentTimeMillis(); + + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency") != null) { + if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { + queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); + } else { + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR) + .setError("Invalid Consistency type").toMap()).build();*/ + + logger.error("Invalid Consistency type"); + throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode()); + } + } + + queryObject.setOperation("update"); + + return queryObject; + } + + private class RowIdentifier { + public String primarKeyValue; + public StringBuilder rowIdString; + @SuppressWarnings("unused") + public PreparedQueryObject queryObject; // the string with all the row + // identifiers separated by AND + + public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, + PreparedQueryObject queryObject) { + this.primarKeyValue = primaryKeyValue; + this.rowIdString = rowIdString; + this.queryObject = queryObject; + } + } + + /** + * + * @param keyspace + * @param tablename + * @param rowParams + * @param queryObject + * @return + * @throws MusicServiceException + */ + private RowIdentifier getRowIdentifier(String keyspace, String tablename, + MultivaluedMap rowParams, PreparedQueryObject queryObject) + throws MusicServiceException { + StringBuilder rowSpec = new StringBuilder(); + int counter = 0; + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + if (tableInfo == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + throw new MusicServiceException( + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + } + StringBuilder primaryKey = new StringBuilder(); + for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { + String keyName = entry.getKey(); + List valueList = entry.getValue(); + String indValue = valueList.get(0); + DataType colType = null; + Object formattedValue = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e); + } + if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { + primaryKey.append(indValue); + } + rowSpec.append(keyName + "= ?"); + queryObject.addValue(formattedValue); + if (counter != rowParams.size() - 1) { + rowSpec.append(" AND "); + } + counter = counter + 1; + } + return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); + } + +} diff --git a/music-core/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java b/music-core/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java new file mode 100644 index 00000000..fbfc0de6 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java @@ -0,0 +1,130 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.eelf.healthcheck; + +import java.util.UUID; + +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.MusicCore; + +import com.datastax.driver.core.ConsistencyLevel; + +/** + * @author inam + * + */ +public class MusicHealthCheck { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + + private String cassandrHost; + + public String getCassandraStatus(String consistency) { + logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra"); + + boolean result = false; + UUID randomUUID = UUID.randomUUID(); + try { + result = getAdminKeySpace(consistency, randomUUID); + } catch( Exception e) { + if(e.getMessage().toLowerCase().contains("unconfigured table healthcheck")) { + logger.error("Error", e); + logger.debug("Creating table...."); + try { + boolean ksresult = createKeyspace(); + if(ksresult) { + result = getAdminKeySpace(consistency, randomUUID); + } + } catch (MusicServiceException e1) { + logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN, e1); + } catch (MusicQueryException e1) { + logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN,e1); + } + } else { + logger.error("Error", e); + return "One or more nodes are down or not responding."; + } + } + try { + cleanHealthCheckId(randomUUID); + } catch (MusicServiceException | MusicQueryException e) { + logger.error("Error while cleaning healthcheck record id...", e); + } + if (result) { + return "ACTIVE"; + } else { + logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra Service is not responding"); + return "INACTIVE"; + } + } + + private Boolean getAdminKeySpace(String consistency, UUID randomUUID) throws MusicServiceException,MusicQueryException { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("insert into admin.healthcheck (id) values (?)"); + pQuery.addValue(randomUUID); + ResultType rs = null; + rs = MusicCore.nonKeyRelatedPut(pQuery, consistency); + logger.info(rs.toString()); + return null != rs; + + } + + private void cleanHealthCheckId(UUID randomUUID) throws MusicServiceException, MusicQueryException { + String cleanQuery = "delete from admin.healthcheck where id = ?"; + PreparedQueryObject deleteQueryObject = new PreparedQueryObject(); + deleteQueryObject.appendQueryString(cleanQuery); + deleteQueryObject.addValue(randomUUID); + MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "eventual"); + logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra healthcheck responded and cleaned up."); + } + + + + private boolean createKeyspace() throws MusicServiceException,MusicQueryException { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("CREATE TABLE admin.healthcheck (id uuid PRIMARY KEY)"); + ResultType rs = null ; + rs = MusicCore.nonKeyRelatedPut(pQuery, ConsistencyLevel.ONE.toString()); + return rs != null && rs.getResult().toLowerCase().contains("success"); + } + + public String getCassandrHost() { + return cassandrHost; + } + + public void setCassandrHost(String cassandrHost) { + this.cassandrHost = cassandrHost; + } + +} \ No newline at end of file diff --git a/music-core/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java b/music-core/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java new file mode 100644 index 00000000..a8012c82 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java @@ -0,0 +1,381 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.eelf.logging; + +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; +import java.net.InetAddress; +import java.text.MessageFormat; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import javax.servlet.http.HttpServletRequest; +import org.slf4j.MDC; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.configuration.SLF4jWrapper; + +public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { + + public static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + public static final EELFLogger applicationLogger = + EELFManager.getInstance().getApplicationLogger(); + public static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + public static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + public static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + public static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); + + private String className; + private static ConcurrentMap classMap = new ConcurrentHashMap<>(); + + public EELFLoggerDelegate(final String className) { + super(className); + this.className = className; + } + + /** + * Convenience method that gets a logger for the specified class. + * + * @see #getLogger(String) + * + * @param clazz + * @return Instance of EELFLoggerDelegate + */ + public static EELFLoggerDelegate getLogger(Class clazz) { + return getLogger(clazz.getName()); + } + + /** + * Gets a logger for the specified class name. If the logger does not already exist in the map, + * this creates a new logger. + * + * @param className If null or empty, uses EELFLoggerDelegate as the class name. + * @return Instance of EELFLoggerDelegate + */ + public static EELFLoggerDelegate getLogger(final String className) { + String classNameNeverNull = className == null || "".equals(className) + ? EELFLoggerDelegate.class.getName() + : className; + EELFLoggerDelegate delegate = classMap.get(classNameNeverNull); + if (delegate == null) { + delegate = new EELFLoggerDelegate(className); + classMap.put(className, delegate); + } + return delegate; + } + + /** + * Logs a message at the lowest level: trace. + * + * @param logger + * @param msg + */ + public void trace(EELFLogger logger, String msg) { + if (logger.isTraceEnabled()) { + logger.trace(msg); + } + } + + /** + * Logs a message with parameters at the lowest level: trace. + * + * @param logger + * @param msg + * @param arguments + */ + public void trace(EELFLogger logger, String msg, Object... arguments) { + if (logger.isTraceEnabled()) { + logger.trace(msg, arguments); + } + } + + /** + * Logs a message and throwable at the lowest level: trace. + * + * @param logger + * @param msg + * @param th + */ + public void trace(EELFLogger logger, String msg, Throwable th) { + if (logger.isTraceEnabled()) { + logger.trace(msg, th); + } + } + + /** + * Logs a message at the second-lowest level: debug. + * + * @param logger + * @param msg + */ + public void debug(EELFLogger logger, String msg) { + if (logger.isDebugEnabled()) { + logger.debug(msg); + } + } + + /** + * Logs a message with parameters at the second-lowest level: debug. + * + * @param logger + * @param msg + * @param arguments + */ + public void debug(EELFLogger logger, String msg, Object... arguments) { + if (logger.isDebugEnabled()) { + logger.debug(msg, arguments); + } + } + + /** + * Logs a message and throwable at the second-lowest level: debug. + * + * @param logger + * @param msg + * @param th + */ + public void debug(EELFLogger logger, String msg, Throwable th) { + if (logger.isDebugEnabled()) { + logger.debug(msg, th); + } + } + + /** + * Logs a message at info level. + * + * @param logger + * @param msg + */ + public void info(EELFLogger logger, String msg) { + logger.info(className + " - "+msg); + } + + /** + * Logs a message with parameters at info level. + * + * @param logger + * @param msg + * @param arguments + */ + public void info(EELFLogger logger, String msg, Object... arguments) { + logger.info(msg, arguments); + } + + /** + * Logs a message and throwable at info level. + * + * @param logger + * @param msg + * @param th + */ + public void info(EELFLogger logger, String msg, Throwable th) { + logger.info(msg, th); + } + + /** + * Logs a message at warn level. + * + * @param logger + * @param msg + */ + public void warn(EELFLogger logger, String msg) { + logger.warn(msg); + } + + /** + * Logs a message with parameters at warn level. + * + * @param logger + * @param msg + * @param arguments + */ + public void warn(EELFLogger logger, String msg, Object... arguments) { + logger.warn(msg, arguments); + } + + /** + * Logs a message and throwable at warn level. + * + * @param logger + * @param msg + * @param th + */ + public void warn(EELFLogger logger, String msg, Throwable th) { + logger.warn(msg, th); + } + + /** + * Logs a message at error level. + * + * @param logger + * @param msg + * + */ + public void error(EELFLogger logger, String msg) { + logger.error(className+ " - " + msg); + } + + /** + * Logs a message at error level. + * + * @param logger + * @param msg + */ + public void error(EELFLogger logger, Exception e) { + logger.error(className+ " - ", e); + } + + /** + * Logs a message with parameters at error level. + * + * @param logger + * @param msg + * @param arguments + * + */ + public void error(EELFLogger logger, String msg, Object... arguments) { + logger.error(msg, arguments); + } + + /** + * Logs a message with parameters at error level. + * + * @param logger + * @param msg + * @param arguments + */ + public void error(EELFLogger logger, Exception e, Object... arguments) { + logger.error("Exception", e, arguments); + } + + /** + * Logs a message and throwable at error level. + * + * @param logger + * @param msg + * @param th + */ + public void error(EELFLogger logger, String msg, Throwable th) { + logger.error(msg, th); + } + + /** + * Logs a message with the associated alarm severity at error level. + * + * @param logger + * @param msg + * @param severtiy + */ + public void error(EELFLogger logger, String msg, Object /* AlarmSeverityEnum */ severtiy) { + logger.error(msg); + } + + /** + * Initializes the logger context. + */ + public void init() { + setGlobalLoggingContext(); + final String msg = + "############################ Logging is started. ############################"; + // These loggers emit the current date-time without being told. + info(applicationLogger, msg); + error(errorLogger, msg); + debug(debugLogger, msg); + info(auditLogger, msg); + info(metricsLogger, msg); + info(securityLogger, msg); + + } + + /** + * Builds a message using a template string and the arguments. + * + * @param message + * @param args + * @return + */ + private String formatMessage(String message, Object... args) { + StringBuilder sbFormattedMessage = new StringBuilder(); + if (args != null && args.length > 0 && message != null && message != "") { + MessageFormat mf = new MessageFormat(message); + sbFormattedMessage.append(mf.format(args)); + } else { + sbFormattedMessage.append(message); + } + + return sbFormattedMessage.toString(); + } + + /** + * Loads all the default logging fields into the MDC context. + */ + private void setGlobalLoggingContext() { + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + errorLogger.error("setGlobalLoggingContext failed", e); + } + } + + public static void mdcPut(String key, String value) { + MDC.put(key, value); + } + + public static String mdcGet(String key) { + return MDC.get(key); + } + + public static void mdcRemove(String key) { + MDC.remove(key); + } + + /** + * Loads the RequestId/TransactionId into the MDC which it should be receiving with an each + * incoming REST API request. Also, configures few other request based logging fields into the + * MDC context. + * + * @param req + * @param appName + */ + public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req, + String appName) { + // Load the default fields + setGlobalLoggingContext(); + + // Load the request based fields + if (req != null) { + // Rest Path + MDC.put(MDC_SERVICE_NAME, req.getServletPath()); + + // Client IPAddress i.e. IPAddress of the remote host who is making + // this request. + String clientIPAddress = req.getHeader("X-FORWARDED-FOR"); + if (clientIPAddress == null) { + clientIPAddress = req.getRemoteAddr(); + } + } + } +} diff --git a/music-core/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java b/music-core/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java new file mode 100644 index 00000000..5af3661c --- /dev/null +++ b/music-core/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java @@ -0,0 +1,188 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; + +/** + * @author inam + * + */ +public enum AppMessages { + + + + /* + * 100-199 Security/Permission Related - Authentication problems + * [ERR100E] Missing Information + * [ERR101E] Authentication error occured + * + * 200-299 Availability/Timeout Related/IO - connectivity error - connection timeout + * [ERR200E] Connectivity + * [ERR201E] Host not available + * [ERR202E] Error while connecting to Cassandra cluster + * [ERR203E] IO Error has occured + * [ERR204E] Execution Interrupted + * [ERR205E] Session Expired + * [ERR206E] Cache not authenticated + * + * + * 300-399 Data Access/Integrity Related + * [ERR300E] Incorrect data + * + * 400-499 - Cassandra Query Related + * [ERR400E] Error while processing prepared query object + * [ERR401E] Executing Session Failure for Request + * [ERR402E] Ill formed queryObject for the request + * [ERR403E] Error processing Prepared Query Object + * + * 500-599 - Locking Related + * [ERR500E] Invalid lock + * [ERR501E] Locking Error has occured + * [ERR502E] Deprecated + * [ERR503E] Failed to aquire lock store handle + * [ERR504E] Failed to create Lock Reference + * [ERR505E] Lock does not exist + * [ERR506E] Failed to aquire lock + * [ERR507E] Lock not aquired + * [ERR508E] Lock state not set + * [ERR509E] Lock not destroyed + * [ERR510E] Lock not released + * [ERR511E] Lock not deleted + * [ERR512E] Deprecated + * + * + * 600 - 699 - Music Service Errors + * [ERR600E] Error initializing the cache + * + * 700-799 Schema Interface Type/Validation - received Pay-load checksum is + * invalid - received JSON is not valid + * + * 800-899 Business/Flow Processing Related - check out to service is not + * allowed - Roll-back is done - failed to generate heat file + * + * + * 900-999 Unknown Errors - Unexpected exception + * [ERR900E] Unexpected error occured + * [ERR901E] Number format exception + * + * + * 1000-1099 Reserved - do not use + * + */ + + + + + MISSINGINFO("[ERR100E]", "Missing Information ","Details: NA", "Please check application credentials and/or headers"), + AUTHENTICATIONERROR("[ERR101E]", "Authentication error occured ","Details: NA", "Please verify application credentials"), + CONNCECTIVITYERROR("[ERR200E]"," Connectivity error","Details: NA ","Please check connectivity to external resources"), + HOSTUNAVAILABLE("[ERR201E]","Host not available","Details: NA","Please verify the host details"), + CASSANDRACONNECTIVITY("[ERR202E]","Error while connecting to Cassandra cluster",""," Please check cassandra cluster details"), + IOERROR("[ERR203E]","IO Error has occured","","Please check IO"), + EXECUTIONINTERRUPTED("[ERR204E]"," Execution Interrupted","",""), + SESSIONEXPIRED("[ERR205E]"," Session Expired","","Session has expired."), + CACHEAUTHENTICATION("[ERR206E]","Cache not authenticated",""," Cache not authenticated"), + + INCORRECTDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"), + MULTIPLERECORDS("[ERR301E]"," Multiple records found",""," Please verify the request payload and try again"), + ALREADYEXIST("[ERR302E]"," Record already exist",""," Please verify the request payload and try again"), + MISSINGDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"), + + QUERYERROR("[ERR400E]","Error while processing prepared query object",""," Please verify the query"), + SESSIONFAILED("[ERR401E]","Executing Session Failure for Request","","Please verify the session and request"), + + INVALIDLOCK("[ERR500E]"," Invalid lock or acquire failed",""," Lock is not valid to aquire"), + LOCKINGERROR("[ERR501E]"," Locking Error has occured",""," Locking Error has occured"), + LOCKHANDLE("[ERR503E]","Failed to aquire lock store handle",""," Failed to aquire lock store handle"), + CREATELOCK("[ERR504E]","Failed to aquire lock store handle ","","Failed to aquire lock store handle "), + LOCKSTATE("[ERR508E]"," Lock state not set",""," Lock state not set"), + DESTROYLOCK("[ERR509E]"," Lock not destroyed",""," Lock not destroyed"), + RELEASELOCK("[ERR510E]"," Lock not released",""," Lock not released"), + DELTELOCK("[ERR511E]",""," Lock not deleted "," Lock not deleted "), + CACHEERROR("[ERR600E]"," Error initializing the cache",""," Error initializing the cache"), + + UNKNOWNERROR("[ERR900E]"," Unexpected error occured",""," Please check logs for details"); + + + + + private ErrorTypes eType; + private ErrorSeverity alarmSeverity; + private ErrorSeverity errorSeverity; + private String errorCode; + private String errorDescription; + private String details; + private String resolution; + + + AppMessages(String errorCode, String errorDescription, String details,String resolution) { + + this.errorCode = errorCode; + this.errorDescription = errorDescription; + this.details = details; + this.resolution = resolution; + } + + + public ErrorTypes getEType() { + return eType; + } + + public ErrorSeverity getAlarmSeverity() { + return alarmSeverity; + } + public ErrorSeverity getErrorSeverity() { + return errorSeverity; + } + + public void setDetails(String details){ this.details=details; } + + public String getDetails() { + return this.details; + } + + public void setResolution(String resolution){ this.resolution=resolution; } + + public String getResolution() { + return this.resolution; + } + + public void setErrorCode(String errorCode){ this.errorCode=errorCode; } + + public String getErrorCode() { + return this.errorCode; + } + + public void setErrorDescription(String errorDescription){ this.errorDescription=errorDescription; } + + public String getErrorDescription() { + return this.errorDescription; + } + + + + + + + +} diff --git a/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java b/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java new file mode 100644 index 00000000..91ee3473 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java @@ -0,0 +1,107 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; + + + +/** + * @author inam + * + */ +public enum ErrorCodes { + + + /* + * 100-199 Security/Permission Related - Authentication problems + * [ERR100E] Missing Information + * [ERR101E] Authentication error occured + * + * 200-299 Availability/Timeout Related/IO - connectivity error - connection timeout + * [ERR200E] Connectivity + * [ERR201E] Host not available + * [ERR202E] Error while connecting to Cassandra cluster + * [ERR203E] IO Error has occured + * [ERR204E] Execution Interrupted + * [ERR205E] Session Expired + * [ERR206E] Cache not authenticated + * + * + * 300-399 Data Access/Integrity Related + * + * 400-499 - Cassandra Query Related + * [ERR400E] Error while processing prepared query object + * [ERR401E] Executing Session Failure for Request + * [ERR402E] Ill formed queryObject for the request + * [ERR403E] Error processing Prepared Query Object + * + * 500-599 - Zookeepr/Locking Related + * [ERR500E] Invalid lock + * [ERR501E] Locking Error has occured + * [ERR502E] Zookeeper error has occured + * [ERR503E] Failed to aquire lock store handle + * [ERR504E] Failed to create Lock Reference + * [ERR505E] Lock does not exist + * [ERR506E] Failed to aquire lock + * [ERR507E] Lock not aquired + * [ERR508E] Lock state not set + * [ERR509E] Lock not destroyed + * [ERR510E] Lock not released + * [ERR511E] Lock not deleted + * [ERR512E] Failed to get Lock Handle + * + * + * 600 - 699 - Music Service Errors + * [ERR600E] Error initializing the cache + * + * 700-799 Schema Interface Type/Validation - received Pay-load checksum is + * invalid - received JSON is not valid + * + * 800-899 Business/Flow Processing Related - check out to service is not + * allowed - Roll-back is done - failed to generate heat file + * + * + * 900-999 Unknown Errors - Unexpected exception + * [ERR900E] Unexpected error occured + * [ERR901E] Number format exception + * + * + * 1000-1099 Reserved - do not use + * + */ + + /*SUCCESS("Success"), FAILURE("Failure"); + + private String result; + + ResultType(String result) { + this.result = result; + } + + public String getResult() { + return result; + } +*/ + + + +} diff --git a/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java b/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java new file mode 100644 index 00000000..4e798239 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java @@ -0,0 +1,38 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; + +/** + * @author inam + * + */ +public enum ErrorSeverity { + INFO, + WARN, + ERROR, + FATAL, + CRITICAL, + MAJOR, + MINOR, + NONE, +} diff --git a/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java b/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java new file mode 100644 index 00000000..9bdbf20f --- /dev/null +++ b/music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java @@ -0,0 +1,46 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; + +import com.att.eelf.i18n.EELFResolvableErrorEnum; + +/** + * @author inam + * + */ +public enum ErrorTypes implements EELFResolvableErrorEnum { + + + CONNECTIONERROR, + SESSIONEXPIRED, + AUTHENTICATIONERROR, + CACHEERROR, + SERVICEUNAVAILABLE, + QUERYERROR, + DATAERROR, + GENERALSERVICEERROR, + MUSICSERVICEERROR, + LOCKINGERROR, + UNKNOWN, + +} diff --git a/music-core/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java new file mode 100644 index 00000000..f5478e78 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +public class MusicDeadlockException extends MusicLockingException { + + public String owner = null; + public String keyspace = null; + public String table = null; + public String key = null; + + public MusicDeadlockException() { + super(); + } + + public MusicDeadlockException(String message) { + super(message); + } + + public MusicDeadlockException(Throwable cause) { + super(cause); + } + + public MusicDeadlockException(String message, Throwable cause) { + super(message, cause); + } + + public MusicDeadlockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public void setValues(String owner, String keyspace, String table, String key) { + this.owner = owner; + this.keyspace = keyspace; + this.table = table; + this.key = key; + } + + public String getOwner() { + return owner; + } + + public String getKeyspace() { + return keyspace; + } + + public String getTable() { + return table; + } + + public String getKey() { + return key; + } + + +} diff --git a/music-core/src/main/java/org/onap/music/exceptions/MusicLockingException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicLockingException.java new file mode 100644 index 00000000..ab70c54c --- /dev/null +++ b/music-core/src/main/java/org/onap/music/exceptions/MusicLockingException.java @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +/** + * @author inam + * + */ +public class MusicLockingException extends Exception { + + /** + * + */ + public MusicLockingException() { + + } + + /** + * @param message + */ + public MusicLockingException(String message) { + super(message); + + } + + /** + * @param cause + */ + public MusicLockingException(Throwable cause) { + super(cause); + + } + + /** + * @param message + * @param cause + */ + public MusicLockingException(String message, Throwable cause) { + super(message, cause); + + } + + /** + * @param message + * @param cause + * @param enableSuppression + * @param writableStackTrace + */ + public MusicLockingException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + + } + +} diff --git a/music-core/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java new file mode 100644 index 00000000..f489cd45 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.exceptions; + +/** + * @author inam + * + */ +public class MusicPolicyVoilationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * + */ + public MusicPolicyVoilationException() { + + } + + /** + * @param message + */ + public MusicPolicyVoilationException(String message) { + super(message); + + } + + /** + * @param cause + */ + public MusicPolicyVoilationException(Throwable cause) { + super(cause); + + } + + /** + * @param message + * @param cause + */ + public MusicPolicyVoilationException(String message, Throwable cause) { + super(message, cause); + + } + + /** + * @param message + * @param cause + * @param enableSuppression + * @param writableStackTrace + */ + public MusicPolicyVoilationException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + + } + +} diff --git a/music-core/src/main/java/org/onap/music/exceptions/MusicQueryException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicQueryException.java new file mode 100644 index 00000000..803f993f --- /dev/null +++ b/music-core/src/main/java/org/onap/music/exceptions/MusicQueryException.java @@ -0,0 +1,90 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + + + +/** + * @author inam + * + */ +public class MusicQueryException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + private int errorCode; + + + /** + * + */ + public MusicQueryException() { + super(); + } + + /** + * @param message + */ + public MusicQueryException(String message) { + super(message); + } + + + + /** + * @param message + */ + public MusicQueryException(String message, int errorCode) { + super(message); + this.errorCode = errorCode; + } + + /** + * @param cause + */ + public MusicQueryException(Throwable cause) { + super(cause); + } + + /** + * @param message + * @param cause + */ + public MusicQueryException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param message + * @param cause + * @param enableSuppression + * @param writableStackTrace + */ + public MusicQueryException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/music-core/src/main/java/org/onap/music/exceptions/MusicServiceException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicServiceException.java new file mode 100644 index 00000000..76e1f948 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/exceptions/MusicServiceException.java @@ -0,0 +1,88 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (C) 2018 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.exceptions; + +/** + * @author inam + * + */ +public class MusicServiceException extends Exception { + + + private int errorCode; + private String errorMessage; + + public MusicServiceException() { + super(); + } + + + public MusicServiceException(String message) { + super(message); + + } + + public MusicServiceException(String message, int errorCode) { + super(message); + this.errorCode=errorCode; + } + + public MusicServiceException(String message, int errorCode, String errorMessage) { + super(message); + this.errorCode=errorCode; + this.errorMessage=errorMessage; + } + + public MusicServiceException(Throwable cause) { + super(cause); + + } + + + public MusicServiceException(String message, Throwable cause) { + super(message, cause); + + } + + + public MusicServiceException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + + } + public void setErrorCode(int errorCode) { + this.errorCode=errorCode; + } + + public int getErrorCode() { + return errorCode; + } + public void setErrorMessage(String errorMessage) { + this.errorMessage=errorMessage; + } + public String getErrorMessage() { + return errorMessage; + } +} diff --git a/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java new file mode 100644 index 00000000..10898476 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java @@ -0,0 +1,604 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.lockingservice.cassandra; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.DeadlockDetectionUtil; +import org.onap.music.main.DeadlockDetectionUtil.OwnershipType; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.extras.codecs.enums.EnumNameCodec; + +/* + * This is the lock store that is built on top of Cassandra that is used by MUSIC to maintain lock state. + */ + +public class CassaLockStore { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CassaLockStore.class); + private static String table_prepend_name = "lockQ_"; + private MusicDataStore dsHandle; + + public CassaLockStore() { + dsHandle = new MusicDataStore(); + } + + public CassaLockStore(MusicDataStore dsHandle) { + this.dsHandle=dsHandle; + } + public class LockObject{ + private boolean isLockOwner; + private String lockRef; + private String createTime; + private String acquireTime; + private LockType locktype; + // Owner is the self-declared client which "owns" this row. It is used for deadlock detection. It is not (directly) related to isLockOwner. + private String owner; + public LockObject(boolean isLockOwner, String lockRef, String createTime, String acquireTime, LockType locktype, String owner) { + this.setIsLockOwner(isLockOwner); + this.setLockRef(lockRef); + this.setAcquireTime(acquireTime); + this.setCreateTime(createTime); + this.setLocktype(locktype); + this.setOwner(owner); + } + public boolean getIsLockOwner() { + return isLockOwner; + } + public void setIsLockOwner(boolean isLockOwner) { + this.isLockOwner = isLockOwner; + } + public String getAcquireTime() { + return acquireTime; + } + public void setAcquireTime(String acquireTime) { + this.acquireTime = acquireTime; + } + public String getCreateTime() { + return createTime; + } + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + public String getLockRef() { + return lockRef; + } + public void setLockRef(String lockRef) { + this.lockRef = lockRef; + } + public LockType getLocktype() { + return locktype; + } + public void setLocktype(LockType locktype) { + this.locktype = locktype; + } + public String getOwner() { + return owner; + } + public void setOwner(String owner) { + this.owner = owner; + } + } + + /** + * + * This method creates a shadow locking table for every main table in Cassandra. This table tracks all information regarding locks. + * @param keyspace of the application. + * @param table of the application. + * @return true if the operation was successful. + * @throws MusicServiceException + * @throws MusicQueryException + */ + public boolean createLockQueue(String keyspace, String table) throws MusicServiceException, MusicQueryException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Create lock queue/table for " + keyspace+"."+table); + table = table_prepend_name+table; + String tabQuery = "CREATE TABLE IF NOT EXISTS "+keyspace+"."+table + + " ( key text, lockReference bigint, createTime text, acquireTime text, guard bigint static, " + + "lockType text, owner text, PRIMARY KEY ((key), lockReference) ) " + + "WITH CLUSTERING ORDER BY (lockReference ASC);"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + + queryObject.appendQueryString(tabQuery); + boolean result; + result = dsHandle.executePut(queryObject, "eventual"); + return result; + } + + /** + * This method creates a lock reference for each invocation. The lock references are monotonically increasing timestamps. + * @param keyspace of the locks. + * @param table of the locks. + * @param lockName is the primary key of the lock table + * @param lockType is the type of lock (read/write) + * @param owner is the owner of the lock (optional, for deadlock detection) + * @return the UUID lock reference. + * @throws MusicServiceException + * @throws MusicQueryException + */ + public String genLockRefandEnQueue(String keyspace, String table, String lockName, LockType locktype, String owner) throws MusicServiceException, MusicQueryException, MusicLockingException { + return genLockRefandEnQueue(keyspace, table, lockName, locktype, owner, 0); + } + + private String genLockRefandEnQueue(String keyspace, String table, String lockName, LockType locktype, String owner, int count) throws MusicServiceException, MusicQueryException, MusicLockingException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Create " + locktype + " lock reference for " + keyspace + "." + table + "." + lockName); + String lockTable =""; + lockTable = table_prepend_name+table; + + PreparedQueryObject queryObject = new PreparedQueryObject(); + String selectQuery = "SELECT guard FROM " + keyspace + "." + lockTable + " WHERE key=?;"; + + queryObject.addValue(lockName); + queryObject.appendQueryString(selectQuery); + ResultSet gqResult = dsHandle.executeOneConsistencyGet(queryObject); + List latestGuardRow = gqResult.all(); + + long prevGuard = 0; + long lockRef = 1; + if (!latestGuardRow.isEmpty()) { + prevGuard = latestGuardRow.get(0).getLong(0); + lockRef = prevGuard + 1; + } + + long lockEpochMillis = System.currentTimeMillis(); + + logger.info(EELFLoggerDelegate.applicationLogger, + "Created lock reference for " + keyspace + "." + lockTable + "." + lockName + ":" + lockRef); + + queryObject = new PreparedQueryObject(); + + String insQuery = "BEGIN BATCH" + + " UPDATE " + keyspace + "." + lockTable + + " SET guard=? WHERE key=? IF guard = " + (prevGuard == 0 ? "NULL" : "?") +";" + + " INSERT INTO " + keyspace + "." + lockTable + + "(key, lockReference, createTime, acquireTime, lockType, owner) VALUES (?,?,?,?,?,?) IF NOT EXISTS; APPLY BATCH;"; + + queryObject.addValue(lockRef); + queryObject.addValue(lockName); + if (prevGuard != 0) + queryObject.addValue(prevGuard); + + queryObject.addValue(lockName); + queryObject.addValue(lockRef); + queryObject.addValue(String.valueOf(lockEpochMillis)); + queryObject.addValue("0"); + queryObject.addValue(locktype); + queryObject.addValue(owner); + queryObject.appendQueryString(insQuery); + boolean pResult = dsHandle.executePut(queryObject, "critical"); + if (!pResult) {// couldn't create lock ref, retry + count++; + if (count > MusicUtil.getRetryCount()) { + logger.warn(EELFLoggerDelegate.applicationLogger, "Unable to create lock reference"); + throw new MusicLockingException("Unable to create lock reference"); + } + return genLockRefandEnQueue(keyspace, table, lockName, locktype, owner, count); + } + return "$" + keyspace + "." + table + "." + lockName + "$" + String.valueOf(lockRef); + } + + /** + * Returns a result set containing the list of clients waiting for a particular lock + * + * @param keyspace + * @param table + * @param key + * @return list of lockrefs in the queue + * @throws MusicServiceException + * @throws MusicQueryException + */ + public List getLockQueue(String keyspace, String table, String key) + throws MusicServiceException, MusicQueryException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Getting the queue for " + keyspace + "." + table + "." + key); + table = table_prepend_name + table; + String selectQuery = "select * from " + keyspace + "." + table + " where key='" + key + "';"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(selectQuery); + ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); + ArrayList lockQueue = new ArrayList<>(); + for (Row row : rs) { + lockQueue.add(Long.toString(row.getLong("lockReference"))); + } + return lockQueue; + } + + + /** + * Returns a result set containing the list of clients waiting for a particular lock + * + * @param keyspace + * @param table + * @param key + * @return size of lockrefs queue + * @throws MusicServiceException + * @throws MusicQueryException + */ + public long getLockQueueSize(String keyspace, String table, String key) + throws MusicServiceException, MusicQueryException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Getting the queue size for " + keyspace + "." + table + "." + key); + table = table_prepend_name + table; + String selectQuery = "select count(*) from " + keyspace + "." + table + " where key='" + key + "';"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(selectQuery); + ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); + return rs.one().getLong("count"); + } + + + /** + * This method returns the top of lock table/queue for the key. + * + * @param keyspace of the application. + * @param table of the application. + * @param key is the primary key of the application table + * @return the UUID lock reference. Returns LockObject.isLockOwner=false if there is no owner or the + * lock doesn't exist + * @throws MusicServiceException + * @throws MusicQueryException + */ + public LockObject peekLockQueue(String keyspace, String table, String key) + throws MusicServiceException, MusicQueryException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Peek in lock table for " + keyspace + "." + table + "." + key); + table = table_prepend_name + table; + String selectQuery = "select * from " + keyspace + "." + table + " where key='" + key + "' LIMIT 1;"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(selectQuery); + ResultSet results = dsHandle.executeOneConsistencyGet(queryObject); + Row row = results.one(); + if (row == null || row.isNull("lockReference")) { + return new LockObject(false, null, null, null, null, null); + } + String lockReference = "" + row.getLong("lockReference"); + String createTime = row.getString("createTime"); + String acquireTime = row.getString("acquireTime"); + LockType locktype = row.get("lockType", LockType.class); + String owner = row.getString("owner"); + + return new LockObject(true, lockReference, createTime, acquireTime, locktype, owner); + } + + public List getCurrentLockHolders(String keyspace, String table, String key) + throws MusicServiceException, MusicQueryException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Getting lockholders in lock table for " + keyspace + "." + table + "." + key); + String origTable = table; + table = table_prepend_name + table; + String selectQuery = "select * from " + keyspace + "." + table + " where key=?;"; + List lockHolders = new ArrayList<>(); + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(selectQuery); + queryObject.addValue(key); + ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); + boolean topOfQueue = true; + StringBuilder lock = new StringBuilder(). + append("$").append(keyspace).append(".").append(origTable). + append(".").append(key).append("$"); + StringBuilder lockReference = new StringBuilder(); + for (Row row : rs) { + if ( row.isNull("lockReference") ) { + return lockHolders; + } + lockReference.append(lock).append(row.getLong("lockReference")); + if (row.get("lockType", LockType.class)!=LockType.WRITE) { + if (topOfQueue) { + lockHolders.add(lockReference.toString()); + break; + } else { + break; + } + } + // read lock + lockHolders.add(lockReference.toString()); + + topOfQueue = false; + lockReference.delete(0,lockReference.length()); + } + return lockHolders; + } + + /** + * Determine if the lock is a valid current lock holder. + * + * @param keyspace + * @param table + * @param key + * @param lockRef + * @return true if lockRef is a lock owner of key + * @throws MusicServiceException + * @throws MusicQueryException + */ + public boolean isLockOwner(String keyspace, String table, String key, String lockRef) + throws MusicServiceException, MusicQueryException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Checking in lock table for " + keyspace + "." + table + "." + key); + table = table_prepend_name + table; + String selectQuery = + "select * from " + keyspace + "." + table + " where key=?;"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(selectQuery); + queryObject.addValue(key); + ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); + + boolean topOfQueue = true; + for (Row row : rs) { + String lockReference = "" + row.getLong("lockReference"); + if (row.get("lockType", LockType.class)==LockType.WRITE) { + if (topOfQueue && lockRef.equals(lockReference)) { + return true; + } else { + return false; + } + } + if (lockRef.equals(lockReference)) { + return true; + } + topOfQueue = false; + } + logger.info(EELFLoggerDelegate.applicationLogger, "Could not find " + lockRef + + " in the lock queue. It has expired and no longer exists."); + return false; + } + + /** + * Determine if the lock is a valid current lock holder. + * + * @param keyspace + * @param table + * @param key + * @param lockRef + * @return true if lockRef is a lock owner of key + * @throws MusicServiceException + * @throws MusicQueryException + */ + public LockObject getLockInfo(String keyspace, String table, String key, String lockRef) + throws MusicServiceException, MusicQueryException { + logger.info(EELFLoggerDelegate.applicationLogger, + "Checking in lock table for " + keyspace + "." + table + "." + key); + String lockQ_table = table_prepend_name + table; + String selectQuery = + "select * from " + keyspace + "." + lockQ_table + " where key=? and lockReference=?;"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(selectQuery); + queryObject.addValue(key); + queryObject.addValue(Long.parseLong(lockRef)); + ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); + Row row = rs.one(); + if (row == null || row.isNull("lockReference")) { + return null; + } + + String lockReference = "" + row.getLong("lockReference"); + String createTime = row.getString("createTime"); + String acquireTime = row.getString("acquireTime"); + LockType locktype = row.get("lockType", LockType.class); + boolean isLockOwner = isLockOwner(keyspace, table, key, lockRef); + String owner = row.getString("owner"); + + return new LockObject(isLockOwner, lockReference, createTime, acquireTime, locktype, owner); + } + + + + /** + * This method removes the lock ref from the lock table/queue for the key. + * + * @param keyspace of the application. + * @param table of the application. + * @param key is the primary key of the application table + * @param lockReference the lock reference that needs to be dequeued. + * @throws MusicServiceException + * @throws MusicQueryException + * @throws MusicLockingException + */ + public void deQueueLockRef(String keyspace, String table, String key, String lockReference, int n) + throws MusicServiceException, MusicQueryException, MusicLockingException { + String prependTable = table_prepend_name + table; + PreparedQueryObject queryObject = new PreparedQueryObject(); + Long lockReferenceL = Long.parseLong(lockReference.substring(lockReference.lastIndexOf("$") + 1)); + String deleteQuery = "delete from " + keyspace + "." + prependTable + " where key='" + key + + "' AND lockReference =" + lockReferenceL + " IF EXISTS;"; + queryObject.appendQueryString(deleteQuery); + logger.info(EELFLoggerDelegate.applicationLogger, "Removing lock for key: "+key+ " and reference: "+lockReference); + try { + dsHandle.executePut(queryObject, "critical"); + logger.info(EELFLoggerDelegate.applicationLogger, + "Lock removed for key: " + key + " and reference: " + lockReference); + } catch (MusicServiceException ex) { + logger.error(logger, ex.getMessage(), ex); + logger.error(EELFLoggerDelegate.applicationLogger, + "Exception while deQueueLockRef for lockname: " + key + " reference:" + lockReference); + if (n > 1) { + logger.info(EELFLoggerDelegate.applicationLogger, "Trying again..."); + deQueueLockRef(keyspace, table, key, lockReference, n - 1); + } else { + logger.error(EELFLoggerDelegate.applicationLogger, + "deQueueLockRef failed for lockname: " + key + " reference:" + lockReference); + logger.error(logger, ex.getMessage(), ex); + throw new MusicLockingException("Error while deQueueLockRef: " + ex.getMessage()); + } + } + } + + + public void updateLockAcquireTime(String keyspace, String table, String key, String lockReference) { + table = table_prepend_name + table; + Long lockReferenceL = Long.parseLong(lockReference); + String updateQuery = "update " + keyspace + "." + table + " set acquireTime='" + System.currentTimeMillis() + + "' where key='" + key + "' AND lockReference = " + lockReferenceL + " IF EXISTS;"; + + //cannot use executePut because we need to ignore music timestamp adjustments for lock store + dsHandle.getSession().execute(updateQuery); + } + + public boolean checkForDeadlock(String keyspace, String table, String lockName, LockType locktype, String owner, boolean forAcquire) throws MusicServiceException, MusicQueryException { + if (locktype.equals(LockType.READ)) return false; + if (owner==null || owner.length()==0) return false; + + String lockTable = table_prepend_name + table; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("SELECT key, acquiretime, owner FROM " + keyspace + "." + lockTable); + queryObject.appendQueryString(" WHERE lockType = ? ALLOW FILTERING"); + queryObject.addValue(LockType.WRITE); + + DeadlockDetectionUtil ddu = new DeadlockDetectionUtil(); + + ResultSet rs = dsHandle.executeQuorumConsistencyGet(queryObject); + logger.debug("rs has " + rs.getAvailableWithoutFetching() + (rs.isFullyFetched()?"":" (or more!)") ); + Iterator it = rs.iterator(); + while (it.hasNext()) { + Row row = it.next(); + logger.debug("key = " + row.getString("key") + ", time = " + row.getString("acquiretime") + ", owner = " + row.getString("owner") ); + ddu.setExisting(row.getString("key"), row.getString("owner"), ("0".equals(row.getString("acquiretime")))?OwnershipType.CREATED:OwnershipType.ACQUIRED); + } + boolean deadlock = ddu.checkForDeadlock(lockName, owner, forAcquire?OwnershipType.ACQUIRED:OwnershipType.CREATED); + if (deadlock) logger.warn("Deadlock detected when " + owner + " tried to create lock on " + keyspace + "." + lockTable + "." + lockName); + return deadlock; + } + + public List getAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicServiceException, MusicQueryException { + List toRet = new ArrayList(); + String lockTable = table_prepend_name + table; + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("SELECT key, lockreference FROM " + keyspace + "." + lockTable); + queryObject.appendQueryString(" WHERE owner = '" + ownerId + "' ALLOW FILTERING"); + + ResultSet rs = dsHandle.executeQuorumConsistencyGet(queryObject); + Iterator it = rs.iterator(); + while (it.hasNext()) { + Row row = it.next(); + toRet.add(row.getString("key") + "$" + row.getLong("lockreference")); + } + return toRet; + } + + public ReturnType promoteLock(String keyspace, String table, String key, String lockRef) + throws MusicLockingException, MusicServiceException, MusicQueryException { + String lockqtable = table_prepend_name + table; + String selectQuery = "select * from " + keyspace + "." + lockqtable + " where key=?;"; + + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString(selectQuery); + queryObject.addValue(key); + ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); + + long refToPromote = Long.parseLong(lockRef); + + boolean topOfQueue = true; + boolean readBlock = false; + boolean seenLockToPromote = false; + boolean promotionOngoing = false; + long readBlockStart = 0; + long readBlockEnd = 0; + + + for (Row row : rs) { + long ref = row.getLong("lockreference"); + LockType lockType = row.get("lockType", LockType.class); + + if (refToPromote==ref) { + if (promotionOngoing) { + return new ReturnType(ResultType.FAILURE, "Can't promote, already promoting another lockref."); + } + seenLockToPromote = true; + if (!topOfQueue) { + readBlockStart = ref; + readBlockEnd = ref; + break; + } + } else if (!seenLockToPromote && refToPromote nodeList = null; + public enum OwnershipType {NONE, CREATED, ACQUIRED}; + + private class Node implements Comparable { + private String id; + private List links; + private boolean visited = false; + private boolean onStack = false; + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + for (Node link : links) sb.append(link.id); + return "Node [id=" + id + ", links=" + sb.toString() + ", visited=" + visited + ", onStack=" + onStack + "]"; + } + + public Node(String id) { + super(); + this.id = id; + this.links = new ArrayList(); + } + + public List getLinks() { + return links; + } + + public void addLink(Node link) { + this.links.add(link); + } + + public void removeLink(Node link) { + this.links.remove(link); + } + + public boolean isVisited() { + return visited; + } + + public boolean isOnStack() { + return onStack; + } + + public void setVisited(boolean visited) { + this.visited = visited; + } + + public void setOnStack(boolean onStack) { + this.onStack = onStack; + } + + @Override + public int compareTo(Node arg0) { + return id.compareTo(arg0.id); + } + } + + public DeadlockDetectionUtil() { + this.nodeList = new HashMap(); + } + + public void listAllNodes() { + System.out.println("In DeadlockDetectionUtil: "); + for (String key : nodeList.keySet()) { + System.out.println(" " + key + " : " + nodeList.get(key)); + } + } + + public boolean checkForDeadlock(String resource, String owner, OwnershipType operation) { + setExisting(resource, owner, operation); + + Node currentNode = null; + if (operation.equals(OwnershipType.ACQUIRED)) { + currentNode = nodeList.get("r" + resource); + } else if (operation.equals(OwnershipType.CREATED)) { + currentNode = nodeList.get("o" + owner); + } + + boolean cycle = findCycle(currentNode); + return cycle; + } + + private boolean findCycle(Node currentNode) { + if (currentNode==null) return false; + if (currentNode.isOnStack()) return true; + if (currentNode.isVisited()) return false; + currentNode.setOnStack(true); + currentNode.setVisited(true); + for (Node childNode : currentNode.getLinks()) { + if (findCycle(childNode)) return true; + } + currentNode.setOnStack(false); + return false; + } + + public void setExisting(String resource, String owner, OwnershipType operation) { + String resourceKey = "r" + resource; + Node resourceNode = nodeList.get(resourceKey); + if (resourceNode==null) { + resourceNode = new Node(resourceKey); + nodeList.put(resourceKey, resourceNode); + } + + String ownerKey = "o" + owner; + Node ownerNode = nodeList.get(ownerKey); + if (ownerNode==null) { + ownerNode = new Node(ownerKey); + nodeList.put(ownerKey, ownerNode); + } + + if (operation.equals(OwnershipType.ACQUIRED)) { + resourceNode.addLink(ownerNode); + ownerNode.removeLink(resourceNode); + } else if (operation.equals(OwnershipType.CREATED)) { + ownerNode.addLink(resourceNode); + resourceNode.removeLink(ownerNode); + } + } + +} diff --git a/music-core/src/main/java/org/onap/music/main/MusicCore.java b/music-core/src/main/java/org/onap/music/main/MusicCore.java new file mode 100644 index 00000000..658f2124 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/main/MusicCore.java @@ -0,0 +1,260 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.main; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonIndex; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.service.MusicCoreService; + +import com.datastax.driver.core.ResultSet; + +public class MusicCore { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class); + private static MusicCoreService musicCore = MusicUtil.getMusicCoreService(); + private static CassaLockStore mLockHandle; + + public static CassaLockStore getmLockHandle() { + return mLockHandle; + } + + public static void setmLockHandle(CassaLockStore mLockHandleIn) { + mLockHandle = mLockHandleIn; + } + + /** + * Acquire lock + * + * @param fullyQualifiedKey DO NOT RELY ON THIS KEY WORKING. INCLUDE THE KEY IN THE LOCKID. + * @param lockId - the full lock id (key + lockRef) + * @return + * @throws MusicLockingException + * @throws MusicQueryException + * @throws MusicServiceException + */ + public static ReturnType acquireLock(String fullyQualifiedKey, String lockId) + throws MusicLockingException, MusicQueryException, MusicServiceException { + return musicCore.acquireLock(fullyQualifiedKey, lockId); + } + + public static ReturnType acquireLockWithLease(String key, String lockId, long leasePeriod) + throws MusicLockingException, MusicQueryException, MusicServiceException { + return musicCore.acquireLockWithLease(key, lockId, leasePeriod); + } + + public static String createLockReference(String fullyQualifiedKey) throws MusicLockingException { + return musicCore.createLockReference(fullyQualifiedKey); + } + + public static String createLockReference(String fullyQualifiedKey, LockType locktype) throws MusicLockingException { + return musicCore.createLockReference(fullyQualifiedKey, locktype); + } + + public static String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException { + return musicCore.createLockReference(fullyQualifiedKey, locktype, owner); + } + + public static ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, + String consistency) throws MusicServiceException { + return musicCore.createTable(keyspace, table, tableQueryObject, consistency); + } + + public static ResultSet quorumGet(PreparedQueryObject query) { + return musicCore.quorumGet(query); + } + + /** + * Gets the top of queue for fullyQualifiedKey + * + * @param fullyQualifiedKey + * @return + */ + public static String whoseTurnIsIt(String fullyQualifiedKey) { + return musicCore.whoseTurnIsIt(fullyQualifiedKey); + } + + /** + * Gets the current lockholder(s) for fullyQualifiedKey + * + * @param fullyQualifiedKey + * @return + */ + public static List getCurrentLockHolders(String fullyQualifiedKey) { + return musicCore.getCurrentLockHolders(fullyQualifiedKey); + } + + public static ReturnType promoteLock(String lockIdToPromote) throws MusicLockingException { + return musicCore.promoteLock(lockIdToPromote); + } + + public static void destroyLockRef(String lockId) throws MusicLockingException { + musicCore.destroyLockRef(lockId); + } + + public static ReturnType eventualPut(PreparedQueryObject queryObject) { + return musicCore.eventualPut(queryObject); + } + + public static ReturnType eventualPut_nb(PreparedQueryObject queryObject, String keyspace, String tablename, + String primaryKey) { + return musicCore.eventualPut_nb(queryObject, keyspace, tablename, primaryKey); + } + + public static ReturnType criticalPut(String keyspace, String table, String primaryKeyValue, + PreparedQueryObject queryObject, String lockReference, Condition conditionInfo) { + return musicCore.criticalPut(keyspace, table, primaryKeyValue, queryObject, lockReference, conditionInfo); + } + + public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) + throws MusicServiceException,MusicQueryException { + return musicCore.nonKeyRelatedPut(queryObject, consistency); + } + + public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { + return musicCore.get(queryObject); + } + + public static ResultSet criticalGet(String keyspace, String table, String primaryKeyValue, + PreparedQueryObject queryObject, String lockReference) throws MusicServiceException { + return musicCore.criticalGet(keyspace, table, primaryKeyValue, queryObject, lockReference); + } + + public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) + throws MusicLockingException, MusicQueryException, MusicServiceException { + return musicCore.atomicPut(keyspaceName, tableName, primaryKey, queryObject, conditionInfo); + } + + public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException { + return musicCore.atomicGet(keyspaceName, tableName, primaryKey, queryObject); + } + + public static List getLockQueue(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException { + return musicCore.getLockQueue(fullyQualifiedKey); + } + + public static long getLockQueueSize(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException { + return musicCore.getLockQueueSize(fullyQualifiedKey); + } + + public static void deleteLock(String lockName) throws MusicLockingException { + musicCore.deleteLock(lockName); + } + + public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { + return musicCore.atomicPutWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject, conditionInfo); + } + + public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException { + return musicCore.atomicGetWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject); + } + + public static Map validateLock(String lockName) { + return musicCore.validateLock(lockName); + } + + public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException { + return musicCore.releaseLock(lockId, voluntaryRelease); + } + + public static List releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException { + return musicCore.releaseAllLocksForOwner(ownerId, keyspace, table); + } + + //Added changes for orm implementation. + + public static ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo) + throws MusicServiceException, MusicQueryException { + return musicCore.createKeyspace(jsonKeySpaceObject,consistencyInfo); + } + + public static ResultType dropKeyspace(JsonKeySpace josnKeyspaceObject, String consistencyInfo) + throws MusicServiceException,MusicQueryException { + return musicCore.dropKeyspace(josnKeyspaceObject, consistencyInfo); + } + + public static ResultType createTable(JsonTable jsonTableObject,String consistencyInfo) + throws MusicServiceException,MusicQueryException { + return musicCore.createTable(jsonTableObject, consistencyInfo); + } + + public static ResultType dropTable(JsonTable jsonTableObject, String consistencyInfo) + throws MusicServiceException, MusicQueryException { + return musicCore.dropTable(jsonTableObject, consistencyInfo); + } + + public static ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo) + throws MusicServiceException,MusicQueryException { + return musicCore.createIndex(jsonIndexObject, consistencyInfo); + } + + public static ResultSet select(JsonSelect jsonSelect, MultivaluedMap rowParams) + throws MusicServiceException, MusicQueryException{ + return musicCore.select(jsonSelect, rowParams); + } + + public static ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException{ + return musicCore.selectCritical(jsonInsertObj, rowParams); + } + + + public static ReturnType insertIntoTable(JsonInsert jsonInsert) throws MusicLockingException, MusicQueryException, MusicServiceException{ + return musicCore.insertIntoTable(jsonInsert); + } + + public static ReturnType updateTable(JsonUpdate jsonUpdateObj,MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException{ + return musicCore.updateTable(jsonUpdateObj, rowParams); + } + + public static ReturnType deleteFromTable(JsonDelete jsonDeleteObj,MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException{ + return musicCore.deleteFromTable(jsonDeleteObj,rowParams); + } + +} diff --git a/music-core/src/main/java/org/onap/music/main/MusicUtil.java b/music-core/src/main/java/org/onap/music/main/MusicUtil.java new file mode 100644 index 00000000..d46e770e --- /dev/null +++ b/music-core/src/main/java/org/onap/music/main/MusicUtil.java @@ -0,0 +1,820 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 IBM. + * Modifications Copyright (c) 2019 Samsung. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.main; + +import com.datastax.driver.core.ColumnDefinitions; +import com.datastax.driver.core.ColumnDefinitions.Definition; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import java.io.File; +import java.io.FileNotFoundException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import java.util.UUID; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; + +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.DataType; + +/** + * @author nelson24 + * + * Properties This will take Properties and load them into MusicUtil. + * This is a hack for now. Eventually it would bebest to do this in + * another way. + * + */ +public class MusicUtil { + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + + // Consistancy Constants + public static final String ATOMIC = "atomic"; + public static final String EVENTUAL = "eventual"; + public static final String CRITICAL = "critical"; + public static final String EVENTUAL_NB = "eventual_nb"; + public static final String ALL = "all"; + public static final String QUORUM = "quorum"; + public static final String ONE = "one"; + public static final String ATOMICDELETELOCK = "atomic_delete_lock"; + + // Header Constants + private static final String XLATESTVERSION = "X-latestVersion"; + private static final String XMINORVERSION = "X-minorVersion"; + private static final String XPATCHVERSION = "X-patchVersion"; + public static final String AUTHORIZATION = "Authorization"; + + // CQL Constants + public static final String SELECT = "select"; + public static final String INSERT = "insert"; + public static final String UPDATE = "update"; + public static final String UPSERT = "upsert"; + public static final String USERID = "userId"; + public static final String PASSWORD = ""; + public static final String CASSANDRA = "cassandra"; + + private static final String LOCALHOST = "localhost"; + private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties"; + public static final String DEFAULTKEYSPACENAME = "TBD"; + + private static long defaultLockLeasePeriod = 6000; + // Amount of times to retry to delete a lock in atomic. + private static int retryCount = 3; + private static String lockUsing = MusicUtil.CASSANDRA; + // Cadi OnOff + private static boolean isCadi = false; + // Keyspace Creation on/off + private static boolean isKeyspaceActive = false; + private static boolean debug = true; + private static String version = "0.0.0"; + private static String build = ""; + + private static String musicPropertiesFilePath = PROPERTIES_FILE; + // private static final String[] propKeys = new String[] { MusicUtil.class.getDeclaredMethod(arg0, )"build","cassandra.host", "debug", + // "version", "music.properties", "lock.lease.period", "cassandra.user", + // "cassandra.password", "aaf.endpoint.url","admin.username","admin.password", + // "music.namespace","admin.aaf.role","cassandra.port","lock.using","retry.count", + // "transId.header.required","conversation.header.required","clientId.header.required", + // "messageId.header.required","transId.header.prefix","conversation.header.prefix", + // "clientId.header.prefix","messageId.header.prefix"}; + // Consistency Constants and variables. + private static final String[] cosistencyLevel = new String[] { + "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO", + "THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"}; + private static final Map consistencyName = new HashMap<>(); + static { + consistencyName.put("ONE",ConsistencyLevel.ONE); + consistencyName.put("TWO",ConsistencyLevel.TWO); + consistencyName.put("THREE",ConsistencyLevel.THREE); + consistencyName.put("SERIAL",ConsistencyLevel.SERIAL); + consistencyName.put("ALL",ConsistencyLevel.ALL); + consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM); + consistencyName.put("QUORUM",ConsistencyLevel.QUORUM); + consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM); + consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE); + consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL); + } + + // Cassandra Values + private static String cassName = "cassandra"; + private static String cassPwd; + private static String myCassaHost = LOCALHOST; + private static int cassandraPort = 9042; + + // AAF + private static String musicAafNs = "org.onap.music.cadi"; + + // Locking + public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM + public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050) + public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day + + // Response/Request tracking headers + private static String transIdPrefix = "false"; + private static String conversationIdPrefix = "false"; + private static String clientIdPrefix = "false"; + private static String messageIdPrefix = "false"; + private static Boolean transIdRequired = false; + private static Boolean conversationIdRequired = false; + private static Boolean clientIdRequired = false; + private static Boolean messageIdRequired = false; + private static String cipherEncKey = ""; + + public MusicUtil() { + throw new IllegalStateException("Utility Class"); + } + + public static String getLockUsing() { + return lockUsing; + } + + public static void setLockUsing(String lockUsing) { + MusicUtil.lockUsing = lockUsing; + } + + /** + * + * @return cassandra port + */ + public static int getCassandraPort() { + return cassandraPort; + } + + /** + * set cassandra port + * @param cassandraPort + */ + public static void setCassandraPort(int cassandraPort) { + MusicUtil.cassandraPort = cassandraPort; + } + /** + * @return the cassName + */ + public static String getCassName() { + return cassName; + } + + /** + * @return the cassPwd + */ + public static String getCassPwd() { + return cassPwd; + } + + /** + * Returns An array of property names that should be in the Properties + * files. + * +// * @return +// */ +// public static String[] getPropkeys() { +// return propKeys.clone(); +// } + + /** + * Get MusicPropertiesFilePath - Default = /opt/music/music.properties + * property file value - music.properties + * + * @return + */ + public static String getMusicPropertiesFilePath() { + return musicPropertiesFilePath; + } + + /** + * Set MusicPropertiesFilePath + * + * @param musicPropertiesFilePath + */ + public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) { + MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath; + } + + /** + * Get DefaultLockLeasePeriod - Default = 6000 property file value - + * lock.lease.period + * + * @return + */ + public static long getDefaultLockLeasePeriod() { + return defaultLockLeasePeriod; + } + + /** + * Set DefaultLockLeasePeriod + * + * @param defaultLockLeasePeriod + */ + public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) { + MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod; + } + + /** + * Set Debug + * + * @param debug + */ + public static void setDebug(boolean debug) { + MusicUtil.debug = debug; + } + + /** + * Is Debug - Default = true property file value - debug + * + * @return + */ + public static boolean isDebug() { + return debug; + } + + /** + * Set Version + * + * @param version + */ + public static void setVersion(String version) { + MusicUtil.version = version; + } + + /** + * Return the version property file value - version. + * + * @return + */ + public static String getVersion() { + return version; + } + + /** + * Set the build of project which is a combination of the + * version and the date. + * + * @param build - version-date. + */ + public static void setBuild(String build) { + MusicUtil.build = build; + } + + /** + * Return the build version-date. + */ + public static String getBuild() { + return build; + } + + /** + * Get MyCassHost - Cassandra Hostname - Default = localhost property file + * value - cassandra.host + * + * @return + */ + public static String getMyCassaHost() { + return myCassaHost; + } + + /** + * Set MyCassHost - Cassandra Hostname + * + * @param myCassaHost . + */ + public static void setMyCassaHost(String myCassaHost) { + MusicUtil.myCassaHost = myCassaHost; + } + + /** + * Gey default retry count + * @return + */ + public static int getRetryCount() { + return retryCount; + } + + /** + * Set retry count + * @param retryCount . + */ + public static void setRetryCount(int retryCount) { + MusicUtil.retryCount = retryCount; + } + + + /** + * This is used to turn keyspace creation api on/off. + * + */ + public static void setKeyspaceActive(Boolean keyspaceActive) { + MusicUtil.isKeyspaceActive = keyspaceActive; + } + + /** + * This is used to turn keyspace creation api on/off. + * @return boolean isKeyspaceActive + */ + public static boolean isKeyspaceActive() { + return isKeyspaceActive; + } + + /** + * This method depricated as its not used or needed. + * + * @return String + */ + @Deprecated + public static String getTestType() { + String testType = ""; + try { + Scanner fileScanner = new Scanner(new File("")); + testType = fileScanner.next();// ignore the my id line + @SuppressWarnings("unused") + String batchSize = fileScanner.next();// ignore the my public ip line + fileScanner.close(); + } catch (FileNotFoundException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); + } + return testType; + + } + + /** + * Method to do a Thread Sleep. + * Used for adding a delay. + * + * @param time + */ + public static void sleep(long time) { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); + Thread.currentThread().interrupt(); + } + } + + /** + * Utility function to check if the query object is valid. + * + * @param withparams + * @param queryObject + * @return + */ + public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) { + if (withparams) { + int noOfValues = queryObject.getValues().size(); + int noOfParams = 0; + char[] temp = queryObject.getQuery().toCharArray(); + for (int i = 0; i < temp.length; i++) { + if (temp[i] == '?') + noOfParams++; + } + return (noOfValues == noOfParams); + } else { + return !queryObject.getQuery().isEmpty(); + } + + } + + public static void setCassName(String cassName) { + MusicUtil.cassName = cassName; + } + + public static void setCassPwd(String cassPwd) { + MusicUtil.cassPwd = cassPwd; + } + + @SuppressWarnings("unchecked") + public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception { + + String value = ""; + switch (type.getName()) { + case UUID: + value = valueObj + ""; + break; + case TEXT: + case VARCHAR: + String valueString = valueObj + ""; + valueString = valueString.replace("'", "''"); + value = "'" + valueString + "'"; + break; + case MAP: { + Map otMap = (Map) valueObj; + value = "{" + jsonMaptoSqlString(otMap, ",") + "}"; + break; + } + default: + value = valueObj + ""; + break; + } + return value; + } + + /** + * + * @param colType + * @param valueObj + * @return + * @throws MusicTypeConversionException + * @throws Exception + */ + @SuppressWarnings("unchecked") + public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception { + String valueObjString = valueObj + ""; + switch (colType.getName()) { + case UUID: + return UUID.fromString(valueObjString); + case VARINT: + return BigInteger.valueOf(Long.parseLong(valueObjString)); + case BIGINT: + return Long.parseLong(valueObjString); + case INT: + return Integer.parseInt(valueObjString); + case FLOAT: + return Float.parseFloat(valueObjString); + case DOUBLE: + return Double.parseDouble(valueObjString); + case BOOLEAN: + return Boolean.parseBoolean(valueObjString); + case MAP: + return (Map) valueObj; + case LIST: + return (List)valueObj; + case BLOB: + + default: + return valueObjString; + } + } + + public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) { + ByteBuffer buffer = ByteBuffer.wrap(valueObj); + return buffer; + } + + /** + * + * Utility function to parse json map into sql like string + * + * @param jMap + * @param lineDelimiter + * @return + */ + + public static String jsonMaptoSqlString(Map jMap, String lineDelimiter) throws Exception{ + StringBuilder sqlString = new StringBuilder(); + int counter = 0; + for (Map.Entry entry : jMap.entrySet()) { + Object ot = entry.getValue(); + String value = ot + ""; + if (ot instanceof String) { + value = "'" + value.replace("'", "''") + "'"; + } + sqlString.append("'" + entry.getKey() + "':" + value); + if (counter != jMap.size() - 1) + sqlString.append(lineDelimiter); + counter = counter + 1; + } + return sqlString.toString(); + } + + @SuppressWarnings("unused") + public static String buildVersion(String major, String minor, String patch) { + if (minor != null) { + major += "." + minor; + if (patch != null) { + major += "." + patch; + } + } + return major; + } + + /** + * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion + * X-latestVerstion will be equal to the latest full version. + * X-minorVersion - will be equal to the latest minor version. + * X-pathVersion - will be equal to the latest patch version. + * Future plans will change this. + * @param response + * @param major + * @param minor + * @param patch + * @return + */ + public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) { + ResponseBuilder response = Response.noContent(); + String versionIn = buildVersion(major,minor,patch); + String version = MusicUtil.getVersion(); + String[] verArray = version.split("\\.",3); + if ( minor != null ) { + response.header(XMINORVERSION,minor); + } else { + response.header(XMINORVERSION,verArray[1]); + } + if ( patch != null ) { + response.header(XPATCHVERSION,patch); + } else { + response.header(XPATCHVERSION,verArray[2]); + } + response.header(XLATESTVERSION,version); + logger.info(EELFLoggerDelegate.auditLogger,"Version In:" + versionIn); + return response; + } + + public static boolean isValidConsistency(String consistency) { + for (String string : cosistencyLevel) { + if (string.equalsIgnoreCase(consistency)) + return true; + } + return false; + + } + + public static ConsistencyLevel getConsistencyLevel(String consistency) { + return consistencyName.get(consistency.toUpperCase()); + } + + /** + * Given the time of write for an update in a critical section, this method provides a transformed timestamp + * that ensures that a previous lock holder who is still alive can never corrupt a later critical section. + * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections. + * @param the UUID lock reference associated with the write. + * @param the long timeOfWrite which is the actual time at which the write took place + * @throws MusicServiceException + * @throws MusicQueryException + */ + public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException { + // TODO: use acquire time instead of music eternity epoch + long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis); + + return ts; + } + + public static MusicCoreService getMusicCoreService() { + if(getLockUsing().equals(MusicUtil.CASSANDRA)) + return MusicCassaCore.getInstance(); + else + return MusicCassaCore.getInstance(); + } + + /** + * @param lockName + * @return + */ + public static Map validateLock(String lockName) { + Map resultMap = new HashMap<>(); + String[] locks = lockName.split("\\."); + if(locks.length < 3) { + resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey"); + return resultMap; + } + String keyspace= locks[0]; + if(keyspace.startsWith("$")) + keyspace = keyspace.substring(1); + resultMap.put("keyspace",keyspace); + return resultMap; + } + + + public static void setIsCadi(boolean isCadi) { + MusicUtil.isCadi = isCadi; + } + + public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName, + PreparedQueryObject updateQuery, String keyspace, String table, + Object cqlFormattedPrimaryKeyValue) + throws Exception { + try { + ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery); + // write it back to a quorum + Row row = results.one(); + ColumnDefinitions colInfo = row.getColumnDefinitions(); + int totalColumns = colInfo.size(); + int counter = 1; + StringBuilder fieldValueString = new StringBuilder(""); + for (Definition definition : colInfo) { + String colName = definition.getName(); + if (colName.equals(primaryKeyName)) + continue; + DataType colType = definition.getType(); + Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType); + Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); + fieldValueString.append(colName + " = ?"); + updateQuery.addValue(valueString); + if (counter != (totalColumns - 1)) + fieldValueString.append(","); + counter = counter + 1; + } + updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET " + + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";"); + updateQuery.addValue(cqlFormattedPrimaryKeyValue); + + MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical"); + } catch (MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery , + ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR, e); + } + } + + public static boolean getIsCadi() { + return MusicUtil.isCadi; + } + + + /** + * @return a random uuid + */ + public static String generateUUID() { + String uuid = UUID.randomUUID().toString(); + logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid); + return uuid; + } + + private static String checkPrefix(String prefix){ + if (prefix == null || "".equals(prefix) || prefix.endsWith("-")) { + return prefix; + } else { + return prefix + "-"; + } + } + + /** + * @return the transIdPrefix + */ + public static String getTransIdPrefix() { + return transIdPrefix; + } + + /** + * @param transIdPrefix the transIdPrefix to set + */ + public static void setTransIdPrefix(String transIdPrefix) { + MusicUtil.transIdPrefix = checkPrefix(transIdPrefix); + } + + /** + * @return the conversationIdPrefix + */ + public static String getConversationIdPrefix() { + return conversationIdPrefix; + } + + /** + * @param conversationIdPrefix the conversationIdPrefix to set + */ + public static void setConversationIdPrefix(String conversationIdPrefix) { + MusicUtil.conversationIdPrefix = checkPrefix(conversationIdPrefix); + } + + /** + * @return the clientIdPrefix + */ + public static String getClientIdPrefix() { + return clientIdPrefix; + } + + /** + * @param clientIdPrefix the clientIdPrefix to set + */ + public static void setClientIdPrefix(String clientIdPrefix) { + MusicUtil.clientIdPrefix = checkPrefix(clientIdPrefix); + } + + /** + * @return the messageIdPrefix + */ + public static String getMessageIdPrefix() { + return messageIdPrefix; + } + + /** + * @param messageIdPrefix the messageIdPrefix to set + */ + public static void setMessageIdPrefix(String messageIdPrefix) { + MusicUtil.messageIdPrefix = checkPrefix(messageIdPrefix); + } + + /** + * @return the transIdRequired + */ + public static Boolean getTransIdRequired() { + return transIdRequired; + } + + + /** + * @param transIdRequired the transIdRequired to set + */ + public static void setTransIdRequired(Boolean transIdRequired) { + MusicUtil.transIdRequired = transIdRequired; + } + + + /** + * @return the conversationIdRequired + */ + public static Boolean getConversationIdRequired() { + return conversationIdRequired; + } + + + /** + * @param conversationIdRequired the conversationIdRequired to set + */ + public static void setConversationIdRequired(Boolean conversationIdRequired) { + MusicUtil.conversationIdRequired = conversationIdRequired; + } + + + /** + * @return the clientIdRequired + */ + public static Boolean getClientIdRequired() { + return clientIdRequired; + } + + + /** + * @param clientIdRequired the clientIdRequired to set + */ + public static void setClientIdRequired(Boolean clientIdRequired) { + MusicUtil.clientIdRequired = clientIdRequired; + } + + + /** + * @return the messageIdRequired + */ + public static Boolean getMessageIdRequired() { + return messageIdRequired; + } + + /** + * @param messageIdRequired the messageIdRequired to set + */ + public static void setMessageIdRequired(Boolean messageIdRequired) { + MusicUtil.messageIdRequired = messageIdRequired; + } + + + public static String getCipherEncKey() { + return MusicUtil.cipherEncKey; + } + + + public static void setCipherEncKey(String cipherEncKey) { + MusicUtil.cipherEncKey = cipherEncKey; + if ( null == cipherEncKey || cipherEncKey.equals("") || + cipherEncKey.equals("nothing to see here")) { + logger.error(EELFLoggerDelegate.errorLogger, "Missing Cipher Encryption Key."); + } + } + + public static String getMusicAafNs() { + return MusicUtil.musicAafNs; + } + + + public static void setMusicAafNs(String musicAafNs) { + MusicUtil.musicAafNs = musicAafNs; + } + + + +} + diff --git a/music-core/src/main/java/org/onap/music/main/ResultType.java b/music-core/src/main/java/org/onap/music/main/ResultType.java new file mode 100644 index 00000000..f5ef2070 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/main/ResultType.java @@ -0,0 +1,42 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.main; + +public enum ResultType { + SUCCESS("Success"), FAILURE("Failure"), + SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"), + BODYMISSING("Incomplete Request body. Please correct your input request and retry."); + + private String result; + + ResultType(String result) { + this.result = result; + } + + public String getResult() { + return result; + } + +} + + diff --git a/music-core/src/main/java/org/onap/music/main/ReturnType.java b/music-core/src/main/java/org/onap/music/main/ReturnType.java new file mode 100644 index 00000000..f02dabbf --- /dev/null +++ b/music-core/src/main/java/org/onap/music/main/ReturnType.java @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.main; + +import java.util.HashMap; +import java.util.Map; + +public class ReturnType { + private ResultType result; + private String message; + + private String timingInfo; + + public ReturnType(ResultType result, String message) { + super(); + this.result = result; + this.message = message; + } + + public String getTimingInfo() { + return timingInfo; + } + + public void setTimingInfo(String timingInfo) { + this.timingInfo = timingInfo; + } + + public ResultType getResult() { + return result; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String toJson() { + return "{ \"result\":\"" + result.getResult() + "\", \"message\":\"" + message + "\"}"; + } + + public String toString() { + return result + " | " + message; + } + + public Map toMap() { + Map newMap = new HashMap<>(); + newMap.put("result", result.getResult()); + newMap.put("message", message); + return newMap; + } + +} diff --git a/music-core/src/main/java/org/onap/music/service/MusicCoreService.java b/music-core/src/main/java/org/onap/music/service/MusicCoreService.java new file mode 100644 index 00000000..b3226906 --- /dev/null +++ b/music-core/src/main/java/org/onap/music/service/MusicCoreService.java @@ -0,0 +1,181 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.service; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonIndex; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; + +import com.datastax.driver.core.ResultSet; + +public interface MusicCoreService { + + + // Core Music Database Methods + + + public ReturnType eventualPut(PreparedQueryObject queryObject); + + public ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey); + + public ReturnType criticalPut(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, String lockId, Condition conditionInfo); + + public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) + throws MusicServiceException,MusicQueryException; + + public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException; + + public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException; + + public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException; + + public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException; + + public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) + throws MusicLockingException, MusicQueryException, MusicServiceException; + + public ResultSet criticalGet(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, String lockId) throws MusicServiceException; + + // Core Music Locking Service Methods + + /** + * Create a lock ref in the music lock store. + * Default is write as this is the safest semantically + * + * @param fullyQualifiedKey the key to create a lock on + * @see {@link #creatLockReference(String, LockType)} + */ + public String createLockReference(String fullyQualifiedKey) throws MusicLockingException; // lock name + + /** + * Create a lock ref in the music lock store + * @param fullyQualifiedKey the key to create a lock on + * @param locktype the type of lock create, see {@link LockType} + */ + public String createLockReference(String fullyQualifiedKey, LockType locktype) throws MusicLockingException; + + /** + * Create a lock ref in the music lock store + * @param fullyQualifiedKey the key to create a lock on + * @param locktype the type of lock create, see {@link LockType} + * @param owner the owner of the lock, for deadlock prevention + */ + public String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException; + + public ReturnType acquireLockWithLease(String key, String lockReference, long leasePeriod) + throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id,time + + public ReturnType acquireLock(String key, String lockReference) + throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id + + public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, + String consistency) throws MusicServiceException; + + public ResultSet quorumGet(PreparedQueryObject query); + + /** + * Gets top of queue for fullyQualifiedKey + * @param fullyQualifiedKey + * @return + */ + public String whoseTurnIsIt(String fullyQualifiedKey);// lock name + + /** + * Gets the current lockholder(s) for lockName + * @param lockName + * @return + */ + public List getCurrentLockHolders(String fullyQualifiedKey); + + public void destroyLockRef(String lockId) throws MusicLockingException; + + public void deleteLock(String lockName) throws MusicLockingException; + + public ReturnType promoteLock(String lockIdToPromote) throws MusicLockingException; + + public List getLockQueue(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException; + + public long getLockQueueSize(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException; + + public Map validateLock(String lockName); + + public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException; + + public List releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException; + + + //Methods added for orm + + + public ResultType createTable(JsonTable jsonTableObject, String consistencyInfo) throws MusicServiceException,MusicQueryException; + + public ResultType dropTable(JsonTable jsonTableObject, String consistencyInfo) + throws MusicServiceException,MusicQueryException; + + public ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject,String consistencyInfo) throws MusicServiceException,MusicQueryException; + + public ResultType dropKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo) + throws MusicServiceException,MusicQueryException; + + public ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo) throws MusicServiceException,MusicQueryException; + + public ResultSet select(JsonSelect jsonSelect, MultivaluedMap rowParams) throws MusicServiceException, MusicQueryException; + + public ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException; + + public ReturnType insertIntoTable(JsonInsert jsonInsert) throws MusicLockingException, MusicQueryException, MusicServiceException; + + public ReturnType updateTable(JsonUpdate jsonUpdateObj,MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException; + + public ReturnType deleteFromTable(JsonDelete jsonDeleteObj,MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException; + +} diff --git a/music-core/src/main/java/org/onap/music/service/impl/MusicCassaCore.java b/music-core/src/main/java/org/onap/music/service/impl/MusicCassaCore.java new file mode 100644 index 00000000..0d2e3f0a --- /dev/null +++ b/music-core/src/main/java/org/onap/music/service/impl/MusicCassaCore.java @@ -0,0 +1,1149 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (c) 2018 IBM. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.service.impl; + +import java.io.StringWriter; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import javax.ws.rs.core.MultivaluedMap; + +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonIndex; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicDeadlockException; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.service.MusicCoreService; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.TableMetadata; + +public class MusicCassaCore implements MusicCoreService { + + private static CassaLockStore mLockHandle = null; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCassaCore.class); + private static MusicCassaCore musicCassaCoreInstance = null; + + private MusicCassaCore() { + // not going to happen + } + + public static CassaLockStore getmLockHandle() { + return mLockHandle; + } + + public static void setmLockHandle(CassaLockStore mLockHandle) { + MusicCassaCore.mLockHandle = mLockHandle; + } + + public static MusicCassaCore getInstance() { + + if(musicCassaCoreInstance == null) { + musicCassaCoreInstance = new MusicCassaCore(); + } + return musicCassaCoreInstance; + } + + + + + public static CassaLockStore getLockingServiceHandle() throws MusicLockingException { + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle"); + long start = System.currentTimeMillis(); + + if (mLockHandle == null) { + try { + mLockHandle = new CassaLockStore(MusicDataStoreHandle.getDSHandle()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); + throw new MusicLockingException("Failed to aquire Locl store handle " + e); + } + } + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms"); + return mLockHandle; + } + + public String createLockReference(String fullyQualifiedKey) throws MusicLockingException { + return createLockReference(fullyQualifiedKey, LockType.WRITE); + } + + public String createLockReference(String fullyQualifiedKey, LockType locktype) throws MusicLockingException { + return createLockReference(fullyQualifiedKey, locktype, null); + } + + public String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException { + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String lockName = splitString[2]; + + logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName); + long start = System.currentTimeMillis(); + String lockReference = null; + + try { + boolean deadlock = getLockingServiceHandle().checkForDeadlock(keyspace, table, lockName, locktype, owner, false); + if (deadlock) { + MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + owner + " tried to create lock on " + keyspace + "." + table + "." + lockName); + e.setValues(owner, keyspace, table, lockName); + throw e; + } + } catch (MusicDeadlockException e) { + //just threw this, no need to wrap it + throw e; + } catch (MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.applicationLogger, e); + throw new MusicLockingException("Unable to check for deadlock. " + e.getMessage(), e); + } + + try { + lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName, locktype, owner); + } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.applicationLogger, e); + throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger, e); + throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e); + } + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms"); + return lockReference; + } + + public ReturnType promoteLock(String lockId) throws MusicLockingException { + String[] splitString = lockId.split("\\."); + String keyspace = splitString[0].substring(1);//remove '$' + String table = splitString[1]; + String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$")); + String localFullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); + String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end + + logger.info(EELFLoggerDelegate.applicationLogger,"Attempting to promote lock " + lockId); + + try { + return getLockingServiceHandle().promoteLock(keyspace, table, primaryKeyValue, lockRef); + } catch (MusicServiceException e) { + throw new MusicLockingException("Unable to promote lock. ", e); + } catch (MusicQueryException e) { + throw new MusicLockingException("Unable to promote lock. ", e); + } + + } + + + public ReturnType acquireLockWithLease(String fullyQualifiedKey, String lockReference, long leasePeriod) + throws MusicLockingException, MusicQueryException, MusicServiceException { + evictExpiredLockHolder(fullyQualifiedKey,leasePeriod); + return acquireLock(fullyQualifiedKey, lockReference); + } + + private void evictExpiredLockHolder(String fullyQualifiedKey, long leasePeriod) + throws MusicLockingException, MusicQueryException, MusicServiceException { + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String primaryKeyValue = splitString[2]; + + LockObject currentLockHolderObject = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue); + + if (!currentLockHolderObject.getIsLockOwner()) { // no lock holder + return; + } + /* + * Release the lock of the previous holder if it has expired. if the update to the acquire time has + * not reached due to network delays, simply use the create time as the reference + */ + long referenceTime = Math.max(Long.parseLong(currentLockHolderObject.getAcquireTime()), + Long.parseLong(currentLockHolderObject.getCreateTime())); + if ((System.currentTimeMillis() - referenceTime) > leasePeriod) { + forciblyReleaseLock(fullyQualifiedKey, currentLockHolderObject.getLockRef() + ""); + logger.info(EELFLoggerDelegate.applicationLogger, currentLockHolderObject.getLockRef() + " forcibly released"); + } + } + + public ReturnType acquireLock(String fullyQualifiedKey, String lockId) + throws MusicLockingException, MusicQueryException, MusicServiceException { + String[] splitString = lockId.split("\\."); + String keyspace = splitString[0].substring(1);//remove '$' + String table = splitString[1]; + String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$")); + String localFullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); + String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end + + LockObject lockInfo = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, lockRef); + + if (!lockInfo.getIsLockOwner()) { + return new ReturnType(ResultType.FAILURE, lockId + " is not a lock holder");//not top of the lock store q + } + + if (getLockingServiceHandle().checkForDeadlock(keyspace, table, primaryKeyValue, lockInfo.getLocktype(), lockInfo.getOwner(), true)) { + MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + lockInfo.getOwner() + " tried to create lock on " + keyspace + "." + table + "." + primaryKeyValue); + e.setValues(lockInfo.getOwner(), keyspace, table, primaryKeyValue); + throw e; + } + + //check to see if the value of the key has to be synced in case there was a forceful release + String syncTable = keyspace+".unsyncedKeys_"+table; + String query = "select * from "+syncTable+" where key='"+localFullyQualifiedKey+"';"; + PreparedQueryObject readQueryObject = new PreparedQueryObject(); + readQueryObject.appendQueryString(query); + ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(readQueryObject); + if (!results.all().isEmpty()) { + logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!"); + try { + syncQuorum(keyspace, table, primaryKeyValue); + } catch (Exception e) { + StringWriter sw = new StringWriter(); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ", + ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e); + String exceptionAsString = sw.toString(); + return new ReturnType(ResultType.FAILURE, "Exception thrown while syncing key:\n" + exceptionAsString); + } + String cleanQuery = "delete from " + syncTable + " where key='"+localFullyQualifiedKey+"';"; + PreparedQueryObject deleteQueryObject = new PreparedQueryObject(); + deleteQueryObject.appendQueryString(cleanQuery); + MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "critical"); + } + + getLockingServiceHandle().updateLockAcquireTime(keyspace, table, primaryKeyValue, lockRef); + + return new ReturnType(ResultType.SUCCESS, lockRef+" is the lock holder for the key"); + } + + + + /** + * + * @param tableQueryObject + * @param consistency + * @return Boolean Indicates success or failure + * @throws MusicServiceException + * + * + */ + public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, + String consistency) throws MusicServiceException { + boolean result = false; + + try { + // create shadow locking table + result = getLockingServiceHandle().createLockQueue(keyspace, table); + if (result == false) + return ResultType.FAILURE; + + result = false; + + // create table to track unsynced_keys + table = "unsyncedKeys_" + table; + + String tabQuery = + "CREATE TABLE IF NOT EXISTS " + keyspace + "." + table + " ( key text,PRIMARY KEY (key) );"; + PreparedQueryObject queryObject = new PreparedQueryObject(); + + queryObject.appendQueryString(tabQuery); + result = false; + result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual"); + + // create actual table + result = MusicDataStoreHandle.getDSHandle().executePut(tableQueryObject, consistency); + } catch (MusicQueryException | MusicServiceException | MusicLockingException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, + ErrorTypes.MUSICSERVICEERROR); + throw new MusicServiceException(ex.getMessage()); + } + return result ? ResultType.SUCCESS : ResultType.FAILURE; + } + + private static void syncQuorum(String keyspace, String table, String primaryKeyValue) throws Exception { + logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---"); + PreparedQueryObject selectQuery = new PreparedQueryObject(); + PreparedQueryObject updateQuery = new PreparedQueryObject(); + + // get the primary key d + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, table); + String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); // we only support single + // primary key + DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType(); + Object cqlFormattedPrimaryKeyValue = + MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue); + + // get the row of data from a quorum + selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + table + " WHERE " + + primaryKeyName + "= ?" + ";"); + selectQuery.addValue(cqlFormattedPrimaryKeyValue); + MusicUtil.writeBackToQuorum(selectQuery, primaryKeyName, updateQuery, keyspace, table, + cqlFormattedPrimaryKeyValue); + } + + /** + * + * @param query + * @return ResultSet + */ + public ResultSet quorumGet(PreparedQueryObject query) { + ResultSet results = null; + try { + results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(query); + } catch (MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR, + ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR, e); + + } + return results; + } + + public String whoseTurnIsIt(String fullyQualifiedKey) { + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String primaryKeyValue = splitString[2]; + try { + LockObject lockOwner = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue); + if (!lockOwner.getIsLockOwner()) { + return null; + } + return "$" + fullyQualifiedKey + "$" + lockOwner.getLockRef(); + } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.LOCKINGERROR + fullyQualifiedKey, + ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); + } + return null; + } + + public List getCurrentLockHolders(String fullyQualifiedKey) { + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String primaryKeyValue = splitString[2]; + try { + return getLockingServiceHandle().getCurrentLockHolders(keyspace, table, primaryKeyValue); + } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+fullyQualifiedKey ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); + } + return null; + } + + /** + * + * @param lockReference + * @return + */ + public static String getLockNameFromId(String lockReference) { + StringTokenizer st = new StringTokenizer(lockReference); + return st.nextToken("$"); + } + + @Override + public void destroyLockRef(String lockId) throws MusicLockingException { + long start = System.currentTimeMillis(); + String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); + String lockRef = lockId.substring(lockId.lastIndexOf('$')+1); + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String primaryKeyValue = splitString[2]; + try { + getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockRef,MusicUtil.getRetryCount()); + } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockRef, + ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e); + throw new MusicLockingException(e.getMessage()); + } + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms"); + } + + public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference) throws MusicLockingException { + long start = System.currentTimeMillis(); + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String primaryKeyValue = splitString[2]; + try { + getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockReference,MusicUtil.getRetryCount()); + } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK + lockReference, + ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR,e); + throw new MusicLockingException(e.getMessage()); + } + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms"); + return new MusicLockState(LockStatus.UNLOCKED, ""); + } + + @Override + public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException { + String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); + String lockRef = lockId.substring(lockId.lastIndexOf('$')+1); + if (voluntaryRelease) { + return voluntaryReleaseLock(fullyQualifiedKey, lockRef); + } else { + return forciblyReleaseLock(fullyQualifiedKey, lockRef); + } + } + + public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference) + throws MusicLockingException { + MusicLockState result = null; + try { + result = destroyLockRef(fullyQualifiedKey, lockReference); + } catch (Exception ex) { + logger.info(EELFLoggerDelegate.applicationLogger, + "Exception in voluntaryReleaseLock() for " + fullyQualifiedKey + "ref: " + lockReference); + throw new MusicLockingException(ex.getMessage()); + } + return result; + } + + public MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException { + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + + //leave a signal that this key could potentially be unsynchronized + String syncTable = keyspace+".unsyncedKeys_"+table; + PreparedQueryObject queryObject = new PreparedQueryObject(); + String values = "(?)"; + queryObject.addValue(fullyQualifiedKey); + String insQuery = "insert into "+syncTable+" (key) values "+values+";"; + queryObject.appendQueryString(insQuery); + try { + MusicDataStoreHandle.getDSHandle().executePut(queryObject, "critical"); + } catch (Exception e) { + logger.error("Cannot forcibly release lock: " + fullyQualifiedKey + " " + lockReference + ". " + + e.getMessage(), e); + } + + //now release the lock + return destroyLockRef(fullyQualifiedKey, lockReference); + } + + @Override + public List releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException { +// System.out.println("IN RELEASEALLLOCKSFOROWNER, "); + + List lockIds = getLockingServiceHandle().getAllLocksForOwner(ownerId, keyspace, table); + for (String lockId : lockIds) { +// System.out.println(" LOCKID = " + lockId); + //return "$" + keyspace + "." + table + "." + lockName + "$" + String.valueOf(lockRef); + releaseLock("$" + keyspace + "." + table + "." + lockId, true); + } + return lockIds; + } + + /** + * + * @param lockName + * @throws MusicLockingException + */ + @Deprecated + public void deleteLock(String lockName) throws MusicLockingException { + throw new MusicLockingException("Depreciated Method Delete Lock"); + } + + // Prepared Query Additions. + + /** + * + * @param queryObject + * @return ReturnType + * @throws MusicServiceException + */ + public ReturnType eventualPut(PreparedQueryObject queryObject) { + boolean result = false; + try { + result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); + } catch (MusicServiceException | MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex); + return new ReturnType(ResultType.FAILURE, ex.getMessage()); + } + if (result) { + return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed"); + } else { + return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform"); + } + } + + /** + * + * @param queryObject + * @return ReturnType + * @throws MusicServiceException + */ + public ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey) { + boolean result = false; + long guard = 0; + PreparedQueryObject getGaurd = new PreparedQueryObject(); + getGaurd.appendQueryString("SELECT guard FROM "+keyspace+".lockq_"+tablename+ " WHERE key = ? ;"); + getGaurd.addValue(primaryKey); + try { + ResultSet getGaurdResult = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(getGaurd); + Row row = getGaurdResult.one(); + if (row != null) { + guard = row.getLong("guard"); + long timeOfWrite = System.currentTimeMillis(); + long ts = MusicUtil.v2sTimeStampInMicroseconds(guard, timeOfWrite); + String query = queryObject.getQuery(); + if (!queryObject.getQuery().contains("USING TIMESTAMP")) { + if (queryObject.getOperation().equalsIgnoreCase("delete")) + query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE "); + else + query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET"); + } + queryObject.replaceQueryString(query); + } + + } catch (MusicServiceException | MusicQueryException e) { + logger.error(EELFLoggerDelegate.applicationLogger,e.getMessage(), e); + } + try { + result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); + } catch (MusicServiceException | MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(),"[ERR512E] Failed to get Lock Handle ", + ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " ", ex); + return new ReturnType(ResultType.FAILURE, ex.getMessage()); + } + if (result) { + return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed"); + } else { + return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform"); + } + } + + /** + * + * @param keyspace + * @param table + * @param primaryKeyValue + * @param queryObject + * @param lockId + * @return + */ + public ReturnType criticalPut(String keyspace, String table, String primaryKeyValue, + PreparedQueryObject queryObject, String lockId, Condition conditionInfo) { + long start = System.currentTimeMillis(); + try { + String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$")); + if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) { + return new ReturnType(ResultType.FAILURE,"Lock value '" + keyLock + "' and key value '" + + primaryKeyValue + "' not match. Please check your values: " + + lockId + " ."); + } + LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, + lockId.substring(lockId.lastIndexOf("$") + 1)); + + if ( lockObject == null ) { + return new ReturnType(ResultType.FAILURE, lockId + " does not exist."); + } else if (!lockObject.getIsLockOwner()) { + return new ReturnType(ResultType.FAILURE, lockId + " is not the lock holder"); + } else if (lockObject.getLocktype() != LockType.WRITE) { + return new ReturnType(ResultType.FAILURE, + "Attempting to do write operation, but " + lockId + " is a read lock"); + } + + if (conditionInfo != null) { + try { + if (conditionInfo.testCondition() == false) + return new ReturnType(ResultType.FAILURE, "Lock acquired but the condition is not true"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e); + return new ReturnType(ResultType.FAILURE, + "Exception thrown while checking the condition, check its sanctity:\n" + e.getMessage()); + } + } + String query = queryObject.getQuery(); + long timeOfWrite = System.currentTimeMillis(); + long lockOrdinal = Long.parseLong(lockId.substring(lockId.lastIndexOf("$") + 1)); + long ts = MusicUtil.v2sTimeStampInMicroseconds(lockOrdinal, timeOfWrite); + // TODO: use Statement instead of modifying query + if (!queryObject.getQuery().contains("USING TIMESTAMP")) { + if (queryObject.getOperation().equalsIgnoreCase("delete")) + query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE "); + else if (queryObject.getOperation().equalsIgnoreCase("insert")) + query = query.replaceFirst(";", " USING TIMESTAMP " + ts + " ; "); + else + query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET"); + } + queryObject.replaceQueryString(query); + MusicDataStore dsHandle = MusicDataStoreHandle.getDSHandle(); + dsHandle.executePut(queryObject, MusicUtil.CRITICAL); + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms"); + } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e); + return new ReturnType(ResultType.FAILURE, + "Exception thrown while doing the critical put: " + + e.getMessage()); + } + return new ReturnType(ResultType.SUCCESS, "Update performed"); + } + + + /** + * + * @param queryObject + * @param consistency + * @return Boolean Indicates success or failure + * @throws MusicServiceException + * + * + */ + public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException,MusicQueryException { + // this is mainly for some functions like keyspace creation etc which does not + // really need the bells and whistles of Music locking. + boolean result = false; +// try { + result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, consistency); +// } catch (MusicQueryException | MusicServiceException ex) { + // logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, + // ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR, ex); +// throw new MusicServiceException(ex.getMessage(),ex); +// } + return result ? ResultType.SUCCESS : ResultType.FAILURE; + } + + /** + * This method performs DDL operation on cassandra. + * + * @param queryObject query object containing prepared query and values + * @return ResultSet + * @throws MusicServiceException + */ + public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { + ResultSet results = null; + try { + results = MusicDataStoreHandle.getDSHandle().executeOneConsistencyGet(queryObject); + } catch (MusicQueryException | MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); + throw new MusicServiceException(e.getMessage()); + } + return results; + } + + /** + * This method performs DDL operations on cassandra, if the the resource is available. Lock ID + * is used to check if the resource is free. + * + * @param keyspace name of the keyspace + * @param table name of the table + * @param primaryKeyValue primary key value + * @param queryObject query object containing prepared query and values + * @param lockId lock ID to check if the resource is free to perform the operation. + * @return ResultSet + */ + public ResultSet criticalGet(String keyspace, String table, String primaryKeyValue, + PreparedQueryObject queryObject, String lockId) throws MusicServiceException { + ResultSet results = null; + String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$")); + try { + if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) { + throw new MusicLockingException("Lock value '" + keyLock + "' and key value '" + + primaryKeyValue + "' do not match. Please check your values: " + + lockId + " ."); + } + LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, + lockId.substring(lockId.lastIndexOf("$") + 1)); + if (null == lockObject) { + throw new MusicLockingException("No Lock Object. Please check if lock name or key is correct." + + lockId + " ."); + } + if ( !lockObject.getIsLockOwner()) { + return null;// not top of the lock store q + } + results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryObject); + } catch ( MusicLockingException e ) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR); + throw new MusicServiceException( + "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage()); + } catch (MusicQueryException | MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, e); + throw new MusicServiceException( + "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage()); + } + return results; + } + + /** + * This method performs DML operation on cassandra, when the lock of the dd is acquired. + * + * @param keyspaceName name of the keyspace + * @param tableName name of the table + * @param primaryKey primary key value + * @param queryObject query object containing prepared query and values + * @return ReturnType + * @throws MusicLockingException + * @throws MusicServiceException + * @throws MusicQueryException + */ + public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) + throws MusicLockingException, MusicQueryException, MusicServiceException { + long start = System.currentTimeMillis(); + String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey; + String lockId = createLockReference(fullyQualifiedKey, LockType.WRITE); + long lockCreationTime = System.currentTimeMillis(); + ReturnType lockAcqResult = null; + logger.info(EELFLoggerDelegate.applicationLogger, + "***Acquiring lock for atomicPut() query : " + queryObject.getQuery() + " : " + primaryKey); + logger.info(EELFLoggerDelegate.applicationLogger, + "***Acquiring lock for atomicPut() values: " + queryObject.getValues().toString()); + if (conditionInfo != null) { + logger.info(EELFLoggerDelegate.applicationLogger, + "***Acquiring lock for atomicPut() conditions: " + conditionInfo.toString()); + } + try { + lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod()); + } catch (MusicLockingException ex) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception while acquireLockWithLease() in atomic put for key: " + primaryKey); + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); + throw new MusicServiceException( + "Cannot perform atomic put for key: " + primaryKey + " : " + ex.getMessage()); + } + long lockAcqTime = System.currentTimeMillis(); + + /* + * if (!lockAcqResult.getResult().equals(ResultType.SUCCESS)) { logger.info(EELFLoggerDelegate. + * applicationLogger,"unable to acquire lock, id " + lockId); + * voluntaryReleaseLock(fullyQualifiedKey,lockId); return lockAcqResult; } + */ + + logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId); + String lockRef = lockId.substring(lockId.lastIndexOf("$")); + ReturnType criticalPutResult = null; + if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { + criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockRef, conditionInfo); + long criticalPutTime = System.currentTimeMillis(); + long lockDeleteTime = System.currentTimeMillis(); + String timingInfo = "|lock creation time:" + (lockCreationTime - start) + "|lock accquire time:" + + (lockAcqTime - lockCreationTime) + "|critical put time:" + (criticalPutTime - lockAcqTime) + + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|"; + criticalPutResult.setTimingInfo(timingInfo); + } else { + logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId); + criticalPutResult = lockAcqResult; + } + try { + voluntaryReleaseLock(fullyQualifiedKey, lockId); + } catch (MusicLockingException ex) { + logger.info(EELFLoggerDelegate.applicationLogger, + "Exception occured while deleting lock after atomic put for key: " + primaryKey); + criticalPutResult.setMessage(criticalPutResult.getMessage() + "Lock release failed"); + } + return criticalPutResult; + } + + + + /** + * This method performs DDL operation on cassasndra, when the lock for the resource is acquired. + * + * @param keyspaceName name of the keyspace + * @param tableName name of the table + * @param primaryKey primary key value + * @param queryObject query object containing prepared query and values + * @return ResultSet + * @throws MusicServiceException + * @throws MusicLockingException + * @throws MusicQueryException + */ + public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException { + String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey; + String lockId = createLockReference(fullyQualifiedKey, LockType.READ); + long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); + ReturnType lockAcqResult = null; + ResultSet result = null; + logger.info(EELFLoggerDelegate.applicationLogger, "Acquiring lock for atomicGet() : " + queryObject.getQuery()); + try { + lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod()); + } catch (MusicLockingException ex) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception while acquireLockWithLease() in atomic get for key: " + primaryKey); + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); + throw new MusicServiceException( + "Cannot perform atomic get for key: " + primaryKey + " : " + ex.getMessage()); + } + if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { + logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId); + String lockRef = lockId.substring(lockId.lastIndexOf("$")); + result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockRef); + } else { + logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId); + } + try { + voluntaryReleaseLock(fullyQualifiedKey, lockId); + } catch (MusicLockingException ex) { + logger.info(EELFLoggerDelegate.applicationLogger, + "Exception occured while deleting lock after atomic put for key: " + primaryKey); + throw new MusicLockingException(ex.getMessage()); + } + + return result; + } + + + + /** + * @param lockName + * @return + */ + public Map validateLock(String lockName) { + return MusicUtil.validateLock(lockName); + } + + @Override + @Deprecated + public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { + return null; + } + + @Override + public List getLockQueue(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException { + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String primaryKeyValue = splitString[2]; + + return getLockingServiceHandle().getLockQueue(keyspace, table, primaryKeyValue); + } + @Override + public long getLockQueueSize(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException { + String[] splitString = fullyQualifiedKey.split("\\."); + String keyspace = splitString[0]; + String table = splitString[1]; + String primaryKeyValue = splitString[2]; + + return getLockingServiceHandle().getLockQueueSize(keyspace, table, primaryKeyValue); + } + + @Override + @Deprecated + public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException { + //deprecated + return null; + } + + //Methods added for ORM changes + + public ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject,String consistencyInfo) + throws MusicServiceException,MusicQueryException { + ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genCreateKeyspaceQuery(), consistencyInfo); + logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace Creation Process completed successfully"); + + return result; + } + + public ResultType dropKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo) + throws MusicServiceException,MusicQueryException { + ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genDropKeyspaceQuery(), + consistencyInfo); + logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace deletion Process completed successfully"); + return result; + } + + public ResultType createTable(JsonTable jsonTableObject, String consistencyInfo) + throws MusicServiceException, MusicQueryException { + ResultType result = null; + try { + result = createTable(jsonTableObject.getKeyspaceName(), + jsonTableObject.getTableName(), jsonTableObject.genCreateTableQuery(), consistencyInfo); + + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, + ErrorTypes.MUSICSERVICEERROR); + throw new MusicServiceException(ex.getMessage()); + } + logger.info(EELFLoggerDelegate.applicationLogger, " Table Creation Process completed successfully "); + return result; + } + + public ResultType dropTable(JsonTable jsonTableObject,String consistencyInfo) + throws MusicServiceException,MusicQueryException { + ResultType result = nonKeyRelatedPut(jsonTableObject.genDropTableQuery(), + consistencyInfo); + logger.info(EELFLoggerDelegate.applicationLogger, " Table deletion Process completed successfully "); + + return result; + } + + @Override + public ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo) + throws MusicServiceException, MusicQueryException{ + ResultType result = nonKeyRelatedPut(jsonIndexObject.genCreateIndexQuery(), + consistencyInfo); + + logger.info(EELFLoggerDelegate.applicationLogger, " Index creation Process completed successfully "); + return result; + } + + /** + * This method performs DDL operation on cassandra. + * + * @param queryObject query object containing prepared query and values + * @return ResultSet + * @throws MusicServiceException + */ + public ResultSet select(JsonSelect jsonSelect, MultivaluedMap rowParams) + throws MusicServiceException, MusicQueryException { + ResultSet results = null; + try { + results = get(jsonSelect.genSelectQuery(rowParams)); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + throw new MusicServiceException(e.getMessage()); + } + return results; + } + + /** + * Select Critical + */ + public ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException { + + ResultSet results = null; + String consistency = ""; + if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) { + consistency = jsonInsertObj.getConsistencyInfo().get("type"); + } + + String lockId = jsonInsertObj.getConsistencyInfo().get("lockId"); + + PreparedQueryObject queryObject = jsonInsertObj.genSelectCriticalPreparedQueryObj(rowParams); + + if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + results = criticalGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), + jsonInsertObj.getPrimaryKeyVal(), queryObject,lockId); + } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { + results = atomicGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), + jsonInsertObj.getPrimaryKeyVal(), queryObject); + } + + return results; + } + + /** + * this is insert row into Table + */ + public ReturnType insertIntoTable(JsonInsert jsonInsertObj) + throws MusicLockingException, MusicQueryException, MusicServiceException { + + String consistency = ""; + if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) { + consistency = jsonInsertObj.getConsistencyInfo().get("type"); + } + + ReturnType result = null; + + try { + PreparedQueryObject queryObj = null; + queryObj = jsonInsertObj.genInsertPreparedQueryObj(); + + if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { + result = eventualPut(jsonInsertObj.genInsertPreparedQueryObj()); + } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + String lockId = jsonInsertObj.getConsistencyInfo().get("lockId"); + if(lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock " + + "and acquire lock or use ATOMIC instead of CRITICAL"); + } + result = criticalPut(jsonInsertObj.getKeyspaceName(), + jsonInsertObj.getTableName(), jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), lockId,null); + } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { + result = atomicPut(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), + jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), null); + } + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return new ReturnType(ResultType.FAILURE, ex.getMessage()); + } + + return result; + } + + /** + * This is insert row into Table + */ + public ReturnType updateTable(JsonUpdate jsonUpdateObj, MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException { + + ReturnType result = null; + String consistency = ""; + if(null != jsonUpdateObj && null != jsonUpdateObj.getConsistencyInfo()) { + consistency = jsonUpdateObj.getConsistencyInfo().get("type"); + } + PreparedQueryObject queryObject = jsonUpdateObj.genUpdatePreparedQueryObj(rowParams); + + Condition conditionInfo; + if (jsonUpdateObj.getConditions() == null) { + conditionInfo = null; + } else { + // to avoid parsing repeatedly, just send the select query to obtain row + PreparedQueryObject selectQuery = new PreparedQueryObject(); + selectQuery.appendQueryString("SELECT * FROM " + jsonUpdateObj.getKeyspaceName() + "." + jsonUpdateObj.getTableName() + " WHERE " + + jsonUpdateObj.getRowIdString() + ";"); + selectQuery.addValue(jsonUpdateObj.getPrimarKeyValue()); + conditionInfo = new Condition(jsonUpdateObj.getConditions(), selectQuery); + } + + + if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { + result = eventualPut(queryObject); + } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + String lockId = jsonUpdateObj.getConsistencyInfo().get("lockId"); + if(lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + + return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock " + + "and acquire lock or use ATOMIC instead of CRITICAL"); + } + result = criticalPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(), + queryObject, lockId, conditionInfo); + } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) { + // this function is mainly for the benchmarks + try { + result = atomicPutWithDeleteLock(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), + jsonUpdateObj.getPrimarKeyValue(), queryObject, conditionInfo); + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, + ErrorTypes.GENERALSERVICEERROR, e); + throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString()); + + } + } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { + try { + result = atomicPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(), + queryObject, conditionInfo); + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e); + throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString()); + } + } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { + try { + result = eventualPut_nb(queryObject, jsonUpdateObj.getKeyspaceName(), + jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue()); + }catch (Exception e) { + return new ReturnType(ResultType.FAILURE, e.getMessage()); + } + + } + + return result; + } + + /** + * This method is for Delete From Table + */ + public ReturnType deleteFromTable(JsonDelete jsonDeleteObj, MultivaluedMap rowParams) + throws MusicLockingException, MusicQueryException, MusicServiceException { + + ReturnType result = null; + String consistency = ""; + if(null != jsonDeleteObj && null != jsonDeleteObj.getConsistencyInfo()) { + consistency = jsonDeleteObj.getConsistencyInfo().get("type"); + } + PreparedQueryObject queryObject = jsonDeleteObj.genDeletePreparedQueryObj(rowParams); + + // get the conditional, if any + Condition conditionInfo; + if (jsonDeleteObj.getConditions() == null) { + conditionInfo = null; + } else { + // to avoid parsing repeatedly, just send the select query to obtain row + PreparedQueryObject selectQuery = new PreparedQueryObject(); + selectQuery.appendQueryString("SELECT * FROM " + jsonDeleteObj.getKeyspaceName() + "." + jsonDeleteObj.getTableName() + " WHERE " + + jsonDeleteObj.getRowIdString() + ";"); + selectQuery.addValue(jsonDeleteObj.getPrimarKeyValue()); + conditionInfo = new Condition(jsonDeleteObj.getConditions(), selectQuery); + } + + if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) + result = eventualPut(queryObject); + else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + String lockId = jsonDeleteObj.getConsistencyInfo().get("lockId"); + if(lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + + return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock " + + "and acquire lock or use ATOMIC instead of CRITICAL"); + } + result = criticalPut(jsonDeleteObj.getKeyspaceName(), + jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(), + queryObject, lockId, conditionInfo); + } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { + result = atomicPut(jsonDeleteObj.getKeyspaceName(), + jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(), + queryObject, conditionInfo); + } else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { + result = eventualPut_nb(queryObject, jsonDeleteObj.getKeyspaceName(), + jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue()); + } + + return result; + } + + +} diff --git a/music-core/src/main/resources/LICENSE.txt b/music-core/src/main/resources/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/music-core/src/main/resources/LICENSE.txt @@ -0,0 +1,24 @@ + +The following license applies to all files in this and sub-directories. Licenses +are included in individual source files where appropriate, and if it differs +from this text, it supersedes this. Any file that does not have license text +defaults to being covered by this text; not all files support the addition of +licenses. +# +# ------------------------------------------------------------------------- +# Copyright (c) 2017 AT&T Intellectual Property +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +# \ No newline at end of file diff --git a/music-core/src/main/resources/Resources.properties b/music-core/src/main/resources/Resources.properties new file mode 100644 index 00000000..72269cb8 --- /dev/null +++ b/music-core/src/main/resources/Resources.properties @@ -0,0 +1,50 @@ +#============LICENSE_START========================================== +#org.onap.music +#=================================================================== +# Copyright (c) 2017 AT&T Intellectual Property +#=================================================================== +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#============LICENSE_END============================================= +#==================================================================== +#Resource key=Error Code|Message text|Resolution text |Description text +LOADING_DEFAULT_LOG_CONFIGURATION=\ + EELF0001I|\ + Loading default logging configuration from system resource file "{0}"|\ + No external logging configurations were defined or found, So verify the default logging configuration from system resource file (../logback.xml). |\ + Loading default logging configuration from system resource file +LOADING_LOG_CONFIGURATION=EELF0002I|\ + Loading logging configuration from file "{0}"|\ + Verify the correct logging configuration file is loaded. |\ + Loading logging configuration for specific file +LOGGING_ALREADY_INITIALIZED=\ + EELF0003W|\ + Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration.|\ + Verify the container logging definitions to ensure they represent your desired logging configuration. |\ + Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration. +NO_LOG_CONFIGURATION=\ + EELF0004E|\ + No log configuration could be found or defaulted!|\ + No external and default logging configuration file. |\ + No log configuration could be found or defaulted! +SEARCHING_LOG_CONFIGURATION=\ + EELF0005I|\ + Searching path "{0}" for log configuration file "{1}"|\ + Verify the correct Path({user.home};etc;../etc) and filename (eelf.logging.file).|\ + Searching path for specific log configuration file. +UNSUPPORTED_LOGGING_FRAMEWORK=\ + EELF0006E|\ + An unsupported logging framework is bound to SLF4J. |\ + Verify your logging frameworks.|\ + An unsupported logging framework is bound to SLF4J. + diff --git a/music-core/src/main/resources/application.properties b/music-core/src/main/resources/application.properties new file mode 100755 index 00000000..6fbe6326 --- /dev/null +++ b/music-core/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8080 +server.servlet.context-path=/MUSIC/rest +security.require-ssl=true +server.ssl.key-store=/opt/app/aafcertman/keystore.jks +server.ssl.key-store-password=changeit +server.ssl.key-store-provider=SUN +server.ssl.key-store-type=JKS +httpPort=8081 +spring.jackson.mapper.ACCEPT_CASE_INSENSITIVE_ENUMS=true diff --git a/music-core/src/main/resources/logback.xml b/music-core/src/main/resources/logback.xml new file mode 100644 index 00000000..69d59ca3 --- /dev/null +++ b/music-core/src/main/resources/logback.xml @@ -0,0 +1,273 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + ${logDirectory}/${generalLogName}.log + + + ${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip + 1GB + 5 + 5GB + + + ${applicationLoggerPattern} + + + + + 256 + true + + + + + + ${logDirectory}/${securityLogName}.log + + ${logDirectory}/${securityLogName}.%i.log.zip + 1 + 9 + + + 5MB + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + 256 + 0 + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + 1 + 9 + + + 5MB + + + ${auditLoggerPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + + ${metricsLoggerPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + 1 + 9 + + + 5MB + + + ${errorLoggerPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + 1 + 9 + + + 5MB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/music-core/src/main/resources/project.properties b/music-core/src/main/resources/project.properties new file mode 100644 index 00000000..69b99adc --- /dev/null +++ b/music-core/src/main/resources/project.properties @@ -0,0 +1,5 @@ +version=${project.version} +artifactId=${project.artifactId} +build=${project.version}-${timestamp} +music.properties=/opt/app/music/etc/music.properties + diff --git a/music-core/src/main/webapp/WEB-INF/.gitignore b/music-core/src/main/webapp/WEB-INF/.gitignore new file mode 100644 index 00000000..840e7d31 --- /dev/null +++ b/music-core/src/main/webapp/WEB-INF/.gitignore @@ -0,0 +1 @@ +/classes/ diff --git a/music-core/src/test/java/LICENSE.txt b/music-core/src/test/java/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/music-core/src/test/java/LICENSE.txt @@ -0,0 +1,24 @@ + +The following license applies to all files in this and sub-directories. Licenses +are included in individual source files where appropriate, and if it differs +from this text, it supersedes this. Any file that does not have license text +defaults to being covered by this text; not all files support the addition of +licenses. +# +# ------------------------------------------------------------------------- +# Copyright (c) 2017 AT&T Intellectual Property +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +# \ No newline at end of file diff --git a/music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java b/music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java new file mode 100644 index 00000000..7ab7d148 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java @@ -0,0 +1,101 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * e + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.datastore; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class PreparedQueryObjectTest { + + private PreparedQueryObject preparedQueryObject; + + @Before + public void setUp() + { + preparedQueryObject = new PreparedQueryObject(); + } + + @Test + public void testKeyspaceName() + { + preparedQueryObject.setKeyspaceName("keyspaceName"); + assertEquals("keyspaceName", preparedQueryObject.getKeyspaceName()); + } + + @Test + public void testConsistency() + { + preparedQueryObject.setConsistency("consistency"); + assertEquals("consistency", preparedQueryObject.getConsistency()); + } + + @Test + public void testTableName() + { + preparedQueryObject.setTableName("tableName"); + assertEquals("tableName", preparedQueryObject.getTableName()); + } + + @Test + public void testoperation() + { + preparedQueryObject.setOperation("operation"); + assertEquals("operation", preparedQueryObject.getOperation()); + } + + @Test + public void testprimaryKeyValue() + { + preparedQueryObject.setPrimaryKeyValue("primaryKeyValue"); + assertEquals("primaryKeyValue", preparedQueryObject.getPrimaryKeyValue()); + } + + @Test + public void testAddValue() { + preparedQueryObject.addValue("one"); + assertEquals("one", preparedQueryObject.getValues().get(0)); + } + + @Test + public void testAddValues() { + preparedQueryObject.addValues("one", "two", "three"); + assertEquals(3, preparedQueryObject.getValues().size()); + assertEquals("two", preparedQueryObject.getValues().get(1)); + } + + @Test + public void testConstructorQuery() { + preparedQueryObject = new PreparedQueryObject("some query string"); + assertEquals("some query string", preparedQueryObject.getQuery()); + } + + @Test + public void testConstructorQueryValues() { + preparedQueryObject = new PreparedQueryObject("another query string", "a", "b", "c"); + assertEquals("another query string", preparedQueryObject.getQuery()); + assertEquals(3, preparedQueryObject.getValues().size()); + assertEquals("b", preparedQueryObject.getValues().get(1)); + } +} diff --git a/music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java b/music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java new file mode 100644 index 00000000..cba9c7c2 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class AppMessagesTest { + + private AppMessages messages; + + @Before + public void setUp() { + messages= AppMessages.ALREADYEXIST; + } + + @Test + public void testDetails() + { + messages.setDetails("details"); + assertEquals("details", messages.getDetails()); + } + + @Test + public void testResolution() + { + messages.setResolution("Resolution"); + assertEquals("Resolution", messages.getResolution()); + } + + @Test + public void testErrorCode() + { + messages.setErrorCode("ErrorCode"); + assertEquals("ErrorCode", messages.getErrorCode()); + } + + @Test + public void testErrorDescription() + { + messages.setErrorDescription("ErrorDescription"); + assertEquals("ErrorDescription", messages.getErrorDescription()); + } +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java new file mode 100644 index 00000000..583a9fd4 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java @@ -0,0 +1,104 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicLockingExceptionTest { + + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException("MusicLockingException Exception occured.."); + } + } catch (MusicLockingException mle) { + assertEquals(mle.getMessage(), "MusicLockingException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(new Throwable()); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + + @Test + public void TestException4() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(message, new Throwable()); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + + @Test + public void TestException5() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(message, new Throwable(), enableSuppression, writableStackTrace); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java new file mode 100644 index 00000000..22e2d728 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java @@ -0,0 +1,106 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicPolicyVoilationExceptionTest { + + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException("MusicPolicyVoilationException Exception occured.."); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals(mve.getMessage(), "MusicPolicyVoilationException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(new Throwable()); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + + @Test + public void TestException4() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(message, new Throwable()); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + + @Test + public void TestException5() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(message, new Throwable(), enableSuppression, + writableStackTrace); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java new file mode 100644 index 00000000..9096506a --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java @@ -0,0 +1,118 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicQueryExceptionTest { + + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException("MusicQueryException Exception occured.."); + } + } catch (MusicQueryException mqe) { + assertEquals(mqe.getMessage(), "MusicQueryException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException("MusicQueryException Exception occured..", 001); + } + } catch (MusicQueryException mqe) { + assertEquals(mqe.getMessage(), "MusicQueryException Exception occured.."); + } + + } + + @Test + public void TestException4() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(new Throwable()); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + + @Test + public void TestException5() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(message, new Throwable()); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + + @Test + public void TestException6() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(message, new Throwable(), enableSuppression, writableStackTrace); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java new file mode 100644 index 00000000..bf056b61 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java @@ -0,0 +1,145 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicServiceExceptionTest { + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException("MusicServiceException Exception occured.."); + } + } catch (MusicServiceException mse) { + assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException("MusicServiceException Exception occured..", 001); + } + } catch (MusicServiceException mse) { + assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); + } + + } + + @Test + public void TestException4() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException("MusicServiceException Exception occured..", 001, "errorMsg"); + } + } catch (MusicServiceException mse) { + assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); + } + + } + + @Test + public void TestException5() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(new Throwable()); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void TestException6() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(message, new Throwable()); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void TestException7() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(message, new Throwable(), enableSuppression, writableStackTrace); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void testErrorCode() { + MusicServiceException musicServiceException = new MusicServiceException(); + musicServiceException.setErrorCode(0001); + assertEquals(0001, musicServiceException.getErrorCode()); + } + + @Test + public void testSetErrorMsg() { + MusicServiceException musicServiceException = new MusicServiceException(); + musicServiceException.setErrorMessage("errorMsg"); + assertEquals("errorMsg", musicServiceException.getErrorMessage()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/CassandraCQL.java b/music-core/src/test/java/org/onap/music/unittests/CassandraCQL.java new file mode 100644 index 00000000..7b116bc8 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/CassandraCQL.java @@ -0,0 +1,247 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +/** + * @author srupane + * + */ + +import java.math.BigInteger; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +//import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.lockingservice.cassandra.LockType; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.extras.codecs.enums.EnumNameCodec; + +public class CassandraCQL { + public static final String createAdminKeyspace = "CREATE KEYSPACE admin WITH REPLICATION = " + + "{'class' : 'SimpleStrategy' , 'replication_factor': 1} AND DURABLE_WRITES = true"; + + public static final String createAdminTable = "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text," + + " application_name text, is_api boolean," + + " password text, username text," + + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");"; + + public static final String createKeySpace = + "CREATE KEYSPACE IF NOT EXISTS testcassa WITH replication = " + +"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;"; + + public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testcassa"; + + public static final String createTableEmployees = + "CREATE TABLE IF NOT EXISTS testcassa.employees " + + "(vector_ts text,empid uuid,empname text,empsalary varint,address Map,PRIMARY KEY (empname)) " + + "WITH comment='Financial Info of employees' " + + "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} " + + "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};"; + + public static final String insertIntoTablePrepared1 = + "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary) VALUES (?,?,?,?); "; + + public static final String insertIntoTablePrepared2 = + "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary,address) VALUES (?,?,?,?,?);"; + + public static final String selectALL = "SELECT * FROM testcassa.employees;"; + + public static final String selectSpecific = + "SELECT * FROM testcassa.employees WHERE empname= ?;"; + + public static final String updatePreparedQuery = + "UPDATE testcassa.employees SET vector_ts=?,address= ? WHERE empname= ?;"; + + public static final String deleteFromTable = " "; + + public static final String deleteFromTablePrepared = " "; + + // Set Values for Prepared Query + + public static List setPreparedInsertValues1() { + + List preppreparedInsertValues1 = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6"); + BigInteger empSalary = BigInteger.valueOf(23443); + String empName = "Mr Test one"; + preppreparedInsertValues1.add(vectorTs); + preppreparedInsertValues1.add(empId); + preppreparedInsertValues1.add(empName); + preppreparedInsertValues1.add(empSalary); + return preppreparedInsertValues1; + } + + public static List setPreparedInsertValues2() { + + List preparedInsertValues2 = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6"); + BigInteger empSalary = BigInteger.valueOf(45655); + String empName = "Mr Test two"; + Map address = new HashMap<>(); + preparedInsertValues2.add(vectorTs); + preparedInsertValues2.add(empId); + preparedInsertValues2.add(empName); + preparedInsertValues2.add(empSalary); + address.put("Street", "1 some way"); + address.put("City", "Some town"); + preparedInsertValues2.add(address); + return preparedInsertValues2; + } + + public static List setPreparedUpdateValues() { + + List preparedUpdateValues = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + Map address = new HashMap<>(); + preparedUpdateValues.add(vectorTs); + String empName = "Mr Test one"; + address.put("Street", "101 Some Way"); + address.put("City", "New York"); + preparedUpdateValues.add(address); + preparedUpdateValues.add(empName); + return preparedUpdateValues; + } + + // Generate Different Prepared Query Objects + /** + * Query Object for Get. + * + * @return + */ + public static PreparedQueryObject setPreparedGetQuery() { + + PreparedQueryObject queryObject = new PreparedQueryObject(); + String empName1 = "Mr Test one"; + queryObject.appendQueryString(selectSpecific); + queryObject.addValue(empName1); + return queryObject; + } + + /** + * Query Object 1 for Insert. + * + * @return {@link PreparedQueryObject} + */ + public static PreparedQueryObject setPreparedInsertQueryObject1() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(insertIntoTablePrepared1); + List values = setPreparedInsertValues1(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + /** + * Query Object 2 for Insert. + * + * @return {@link PreparedQueryObject} + */ + public static PreparedQueryObject setPreparedInsertQueryObject2() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(insertIntoTablePrepared2); + List values = setPreparedInsertValues2(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + /** + * Query Object for Update. + * + * @return {@link PreparedQueryObject} + */ + public static PreparedQueryObject setPreparedUpdateQueryObject() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(updatePreparedQuery); + List values = setPreparedUpdateValues(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + private static ArrayList getAllPossibleLocalIps() { + ArrayList allPossibleIps = new ArrayList(); + try { + Enumeration en = NetworkInterface.getNetworkInterfaces(); + while (en.hasMoreElements()) { + NetworkInterface ni = (NetworkInterface) en.nextElement(); + Enumeration ee = ni.getInetAddresses(); + while (ee.hasMoreElements()) { + InetAddress ia = (InetAddress) ee.nextElement(); + allPossibleIps.add(ia.getHostAddress()); + } + } + } catch (SocketException e) { + System.out.println(e.getMessage()); + } + return allPossibleIps; + } + + public static MusicDataStore connectToEmbeddedCassandra() throws Exception { + System.setProperty("log4j.configuration", "log4j.properties"); + + String address = "localhost"; + + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + Cluster cluster = new Cluster.Builder().withoutJMXReporting().withoutMetrics().addContactPoint(address).withPort(9142).build(); + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(5000); + EnumNameCodec lockTypeCodec = new EnumNameCodec(LockType.class); + cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec); + + Session session = cluster.connect(); + + return new MusicDataStore(cluster, session); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/MusicUtilTest.java b/music-core/src/test/java/org/onap/music/unittests/MusicUtilTest.java new file mode 100644 index 00000000..39432d07 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/MusicUtilTest.java @@ -0,0 +1,332 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests; + +import static org.junit.Assert.*; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.junit.Test; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.main.MusicUtil; +//import org.onap.music.main.CorePropertiesLoader; +import org.onap.music.service.MusicCoreService; + +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.DataType; + +public class MusicUtilTest { + + private static final String XLATESTVERSION = "X-latestVersion"; + private static final String XMINORVERSION = "X-minorVersion"; + private static final String XPATCHVERSION = "X-patchVersion"; + + @Test + public void testGetCassName() { + MusicUtil.setCassName("Cassandra"); + assertTrue(MusicUtil.getCassName().equals("Cassandra")); + } + + @Test + public void testGetCassPwd() { + MusicUtil.setCassPwd("Cassandra"); + assertTrue(MusicUtil.getCassPwd().equals("Cassandra")); + } + + @Test + public void testMusicAafNs() { + MusicUtil.setMusicAafNs("ns"); + assertTrue("ns".equals(MusicUtil.getMusicAafNs())); + } + + @Test + public void testMusicCoreService() { + MusicUtil.setLockUsing(MusicUtil.CASSANDRA); + MusicCoreService mc = null; + mc = MusicUtil.getMusicCoreService(); + assertTrue(mc != null); + MusicUtil.setLockUsing("nothing"); + mc = null; + mc = MusicUtil.getMusicCoreService(); + assertTrue(mc != null); + + } + + @Test + public void testCipherEncKey() { + MusicUtil.setCipherEncKey("cipherEncKey"); + assertTrue("cipherEncKey".equals(MusicUtil.getCipherEncKey())); + } + + @Test + public void testGetMusicPropertiesFilePath() { + MusicUtil.setMusicPropertiesFilePath("filepath"); + assertEquals(MusicUtil.getMusicPropertiesFilePath(),"filepath"); + } + + @Test + public void testGetDefaultLockLeasePeriod() { + MusicUtil.setDefaultLockLeasePeriod(5000); + assertEquals(MusicUtil.getDefaultLockLeasePeriod(),5000); + } + + @Test + public void testIsDebug() { + MusicUtil.setDebug(true); + assertTrue(MusicUtil.isDebug()); + } + + @Test + public void testGetVersion() { + MusicUtil.setVersion("1.0.0"); + assertEquals(MusicUtil.getVersion(),"1.0.0"); + } + + @Test + public void testBuildVersionA() { + assertEquals(MusicUtil.buildVersion("1","2","3"),"1.2.3"); + } + + @Test + public void testBuildVersionB() { + assertEquals(MusicUtil.buildVersion("1",null,"3"),"1"); + } + + @Test + public void testBuildVersionC() { + assertEquals(MusicUtil.buildVersion("1","2",null),"1.2"); + } + +/* + @Test + public void testBuileVersionResponse() { + assertTrue(MusicUtil.buildVersionResponse("1","2","3").getClass().getSimpleName().equals("Builder")); + assertTrue(MusicUtil.buildVersionResponse("1",null,"3").getClass().getSimpleName().equals("Builder")); + assertTrue(MusicUtil.buildVersionResponse("1","2",null).getClass().getSimpleName().equals("Builder")); + assertTrue(MusicUtil.buildVersionResponse(null,null,null).getClass().getSimpleName().equals("Builder")); + } +*/ + @Test + public void testGetConsistency() { + assertTrue(ConsistencyLevel.ONE.equals(MusicUtil.getConsistencyLevel("one"))); + } + + @Test + public void testRetryCount() { + MusicUtil.setRetryCount(1); + assertEquals(MusicUtil.getRetryCount(),1); + } + + @Test + public void testIsCadi() { + MusicUtil.setIsCadi(true); + assertEquals(MusicUtil.getIsCadi(),true); + } + + + @Test + public void testGetMyCassaHost() { + MusicUtil.setMyCassaHost("10.0.0.2"); + assertEquals(MusicUtil.getMyCassaHost(),"10.0.0.2"); + } + + @Test + public void testIsValidQueryObject() { + PreparedQueryObject myQueryObject = new PreparedQueryObject(); + myQueryObject.appendQueryString("select * from apple where type = ?"); + myQueryObject.addValue("macintosh"); + assertTrue(MusicUtil.isValidQueryObject(true,myQueryObject)); + + myQueryObject.appendQueryString("select * from apple"); + assertTrue(MusicUtil.isValidQueryObject(false,myQueryObject)); + + myQueryObject.appendQueryString("select * from apple where type = ?"); + assertFalse(MusicUtil.isValidQueryObject(true,myQueryObject)); + + myQueryObject = new PreparedQueryObject(); + myQueryObject.appendQueryString(""); + System.out.println("#######" + myQueryObject.getQuery().isEmpty()); + assertFalse(MusicUtil.isValidQueryObject(false,myQueryObject)); + + + } + + + + + @Test(expected = IllegalStateException.class) + public void testMusicUtil() { + System.out.println("MusicUtil Constructor Test"); + MusicUtil mu = new MusicUtil(); + System.out.println(mu.toString()); + } + + @Test + public void testConvertToCQLDataType() throws Exception { + Map myMap = new HashMap(); + myMap.put("name","tom"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.varchar(),"Happy People"),"'Happy People'"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.uuid(),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")),"29dc2afa-c2c0-47ae-afae-e72a645308ab"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.blob(),"Hi"),"Hi"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),"{'name':'tom'}"); + } + + @Test + public void testConvertToActualDataType() throws Exception { + assertEquals(MusicUtil.convertToActualDataType(DataType.varchar(),"Happy People"),"Happy People"); + assertEquals(MusicUtil.convertToActualDataType(DataType.uuid(),"29dc2afa-c2c0-47ae-afae-e72a645308ab"),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")); + assertEquals(MusicUtil.convertToActualDataType(DataType.varint(),"1234"),BigInteger.valueOf(Long.parseLong("1234"))); + assertEquals(MusicUtil.convertToActualDataType(DataType.bigint(),"123"),Long.parseLong("123")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cint(),"123"),Integer.parseInt("123")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cfloat(),"123.01"),Float.parseFloat("123.01")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cdouble(),"123.02"),Double.parseDouble("123.02")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cboolean(),"true"),Boolean.parseBoolean("true")); + List myList = new ArrayList(); + List newList = myList; + myList.add("TOM"); + assertEquals(MusicUtil.convertToActualDataType(DataType.list(DataType.varchar()),myList),newList); + Map myMap = new HashMap(); + myMap.put("name","tom"); + Map newMap = myMap; + assertEquals(MusicUtil.convertToActualDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),newMap); + } + + @Test + public void testConvertToActualDataTypeByte() throws Exception { + byte[] testByte = "TOM".getBytes(); + assertEquals(MusicUtil.convertToActualDataType(DataType.blob(),testByte),ByteBuffer.wrap(testByte)); + + } + + @Test + public void testJsonMaptoSqlString() throws Exception { + Map myMap = new HashMap<>(); + myMap.put("name","tom"); + myMap.put("value",5); + String result = MusicUtil.jsonMaptoSqlString(myMap,","); + assertTrue(result.contains("name")); + assertTrue(result.contains("value")); + } + + @Test + public void test_generateUUID() { + //this function shouldn't be in cachingUtil + System.out.println("Testing getUUID"); + String uuid1 = MusicUtil.generateUUID(); + String uuid2 = MusicUtil.generateUUID(); + assertFalse(uuid1==uuid2); + } + + + @Test + public void testIsValidConsistency(){ + assertTrue(MusicUtil.isValidConsistency("ALL")); + assertFalse(MusicUtil.isValidConsistency("TEST")); + } + + @Test + public void testLockUsing() { + MusicUtil.setLockUsing("testlock"); + assertEquals("testlock", MusicUtil.getLockUsing()); + } + + @Test + public void testCassaPort() { + MusicUtil.setCassandraPort(1234); + assertEquals(1234, MusicUtil.getCassandraPort()); + } + + @Test + public void testBuild() { + MusicUtil.setBuild("testbuild"); + assertEquals("testbuild", MusicUtil.getBuild()); + } + + @Test + public void testTransId() { + MusicUtil.setTransIdPrefix("prefix"); + assertEquals("prefix-", MusicUtil.getTransIdPrefix()); + } + + + @Test + public void testConversationIdPrefix() { + MusicUtil.setConversationIdPrefix("prefix-"); + assertEquals("prefix-", MusicUtil.getConversationIdPrefix()); + } + + @Test + public void testClientIdPrefix() { + MusicUtil.setClientIdPrefix("clientIdPrefix"); + assertEquals("clientIdPrefix-", MusicUtil.getClientIdPrefix()); + } + + @Test + public void testMessageIdPrefix() { + MusicUtil.setMessageIdPrefix("clientIdPrefix"); + assertEquals("clientIdPrefix-", MusicUtil.getMessageIdPrefix()); + } + + @Test + public void testTransIdPrefix() { + MusicUtil.setTransIdPrefix("transIdPrefix"); + assertEquals("transIdPrefix-", MusicUtil.getTransIdPrefix()); + } + + @Test + public void testConvIdReq() { + MusicUtil.setConversationIdRequired(true); + assertEquals(true, MusicUtil.getConversationIdRequired()); + } + + @Test + public void testClientIdRequired() { + MusicUtil.setClientIdRequired(true); + assertEquals(true, MusicUtil.getClientIdRequired()); + } + + @Test + public void testMessageIdRequired() { + MusicUtil.setMessageIdRequired(true); + assertEquals(true, MusicUtil.getMessageIdRequired()); + } + + @Test + public void testTransIdRequired() { + MusicUtil.setTransIdRequired(true); + assertEquals(true,MusicUtil.getTransIdRequired()); + } +/* + @Test + public void testLoadProperties() { + PropertiesLoader pl = new PropertiesLoader(); + pl.loadProperties(); + } +*/ +} diff --git a/music-core/src/test/java/org/onap/music/unittests/ResultTypeTest.java b/music-core/src/test/java/org/onap/music/unittests/ResultTypeTest.java new file mode 100644 index 00000000..012629e0 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/ResultTypeTest.java @@ -0,0 +1,43 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +import static org.junit.Assert.*; +import org.junit.Test; +import org.onap.music.main.ResultType; + +public class ResultTypeTest { + + @Test + public void testResultType() { + assertEquals("SUCCESS",ResultType.SUCCESS.name()); + assertEquals("FAILURE",ResultType.FAILURE.name()); + } + + @Test + public void testGetResult() { + assertEquals("Success",ResultType.SUCCESS.getResult()); + assertEquals("Failure",ResultType.FAILURE.getResult()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/ReturnTypeTest.java b/music-core/src/test/java/org/onap/music/unittests/ReturnTypeTest.java new file mode 100644 index 00000000..490020ac --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/ReturnTypeTest.java @@ -0,0 +1,84 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Map; + +import org.junit.Test; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; + +public class ReturnTypeTest { + + @Test + public void testReturnType() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + assertEquals(result.getMessage(),"message"); + assertEquals(result.getResult(),ResultType.SUCCESS); + } + + @Test + public void testTimingInfo() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + result.setTimingInfo("123"); + assertEquals(result.getTimingInfo(),"123"); + } + + @Test + public void testGetResult() { + ReturnType result = new ReturnType(ResultType.FAILURE,"message"); + assertEquals(result.getResult(),ResultType.FAILURE); + } + + @Test + public void testGetMessage() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + result.setMessage("NewMessage"); + assertEquals(result.getMessage(),"NewMessage"); + } + + @Test + public void testToJson() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + String myJson = result.toJson(); + assertTrue(myJson.contains("message")); + } + + @Test + public void testToString() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + String test = result.toString(); + assertTrue(test.contains("message")); + } + + @Test + public void testToMap() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + Map myMap = result.toMap(); + assertTrue(myMap.containsKey("message")); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java new file mode 100644 index 00000000..7f6af4c5 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests.jsonobjects; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import org.onap.music.datastore.jsonobjects.JSONObject; + +public class JSONObjectTest { + private JSONObject jsonObject; + + @Before + public void setUp() { + jsonObject = new JSONObject(); + } + + @Test + public void testGetSetData() { + jsonObject.setData("data"); + Assert.assertEquals("data", jsonObject.getData()); + } +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java new file mode 100644 index 00000000..a069b81d --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonDelete; + +public class JsonDeleteTest { + + JsonDelete jd = null; + + @Before + public void init() { + jd = new JsonDelete(); + } + + @Test + public void testGetConditions() { + Map mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + jd.setConditions(mapSo); + assertEquals("one",jd.getConditions().get("key1")); + } + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs.put("key3","three"); + mapSs.put("key4","four"); + jd.setConsistencyInfo(mapSs); + assertEquals("three",jd.getConsistencyInfo().get("key3")); + } + + @Test + public void testGetColumns() { + List ary = new ArrayList<>(); + ary.add("e1"); + ary.add("e2"); + ary.add("e3"); + jd.setColumns(ary); + assertEquals("e1",jd.getColumns().get(0)); + } + + @Test + public void testGetTtl() { + jd.setTtl("2000"); + assertEquals("2000",jd.getTtl()); + } + + @Test + public void testGetTimestamp() { + jd.setTimestamp("20:00"); + assertEquals("20:00",jd.getTimestamp()); + + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java new file mode 100644 index 00000000..4992af7b --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java @@ -0,0 +1,111 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests.jsonobjects; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.SerializationUtils; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonInsert; + +public class JsonInsertTest { + + JsonInsert ji = new JsonInsert(); + + @Test + public void testGetKeyspaceName() { + ji.setKeyspaceName("keyspace"); + assertEquals("keyspace",ji.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + ji.setTableName("table"); + assertEquals("table",ji.getTableName()); + } + + @Test + public void testGetConsistencyInfo() { + Map cons = new HashMap<>(); + cons.put("test","true"); + ji.setConsistencyInfo(cons); + assertEquals("true",ji.getConsistencyInfo().get("test")); + } + + @Test + public void testGetTtl() { + ji.setTtl("ttl"); + assertEquals("ttl",ji.getTtl()); + } + + @Test + public void testGetTimestamp() { + ji.setTimestamp("10:30"); + assertEquals("10:30",ji.getTimestamp()); + } + + @Test + public void testGetValues() { + Map cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setValues(cons); + assertEquals("one",ji.getValues().get("val1")); + } + + @Test + public void testGetRowSpecification() { + Map cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setRowSpecification(cons); + assertEquals("two",ji.getRowSpecification().get("val2")); + } + + @Test + public void testSerialize() { + Map cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setTimestamp("10:30"); + ji.setRowSpecification(cons); + byte[] test1 = ji.serialize(); + byte[] ji1 = SerializationUtils.serialize(ji); + assertArrayEquals(ji1,test1); + } + + @Test + public void testObjectMap() + { + Map map = new HashMap<>(); + ji.setObjectMap(map); + assertEquals(map, ji.getObjectMap()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java new file mode 100644 index 00000000..0f4abd7c --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java @@ -0,0 +1,73 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; + +public class JsonKeySpaceTest { + + JsonKeySpace jk = null; + + + @Before + public void init() { + jk = new JsonKeySpace(); + } + + + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jk.setConsistencyInfo(mapSs); + assertEquals("one",jk.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetReplicationInfo() { + Map mapSo = new HashMap<>(); + mapSo.put("k1", "one"); + jk.setReplicationInfo(mapSo); + assertEquals("one",jk.getReplicationInfo().get("k1")); + + } + + @Test + public void testGetDurabilityOfWrites() { + jk.setDurabilityOfWrites("1"); + assertEquals("1",jk.getDurabilityOfWrites()); + } + + @Test + public void testGetKeyspaceName() { + jk.setKeyspaceName("Keyspace"); + assertEquals("Keyspace",jk.getKeyspaceName()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java new file mode 100644 index 00000000..b7dfa075 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java @@ -0,0 +1,47 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests.jsonobjects; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonLeasedLock; + +public class JsonLeasedLockTest { + + JsonLeasedLock jl = null; + + @Before + public void init() { + jl = new JsonLeasedLock(); + } + + + @Test + public void testGetLeasePeriod() { + long lease = 20000; + jl.setLeasePeriod(lease); + assertEquals(lease,jl.getLeasePeriod()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java new file mode 100644 index 00000000..37d1787a --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java @@ -0,0 +1,56 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018-2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests.jsonobjects; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonSelect; + +public class JsonSelectTest { + + @Test + public void testGetConsistencyInfo() { + JsonSelect js = new JsonSelect(); + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + js.setConsistencyInfo(mapSs); + assertEquals("one", js.getConsistencyInfo().get("k1")); + } + + @Test + public void testSerialize() throws IOException { + JsonSelect js = new JsonSelect(); + Map mapSs = new HashMap<>(); + mapSs.put("Key", "Value"); + js.setConsistencyInfo(mapSs); + js.serialize(); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java new file mode 100644 index 00000000..4e3b4629 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java @@ -0,0 +1,100 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonTable; + +public class JsonTableTest { + + JsonTable jt = null; + + @Before + public void init() { + jt = new JsonTable(); + } + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jt.setConsistencyInfo(mapSs); + assertEquals("one",jt.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetProperties() { + Map properties = new HashMap<>(); + properties.put("k1", "one"); + jt.setProperties(properties); + } + + @Test + public void testGetFields() { + Map fields = new HashMap<>(); + fields.put("k1", "one"); + jt.setFields(fields); + assertEquals("one",jt.getFields().get("k1")); + } + + @Test + public void testGetKeyspaceName() { + String keyspace = "keyspace"; + jt.setKeyspaceName(keyspace); + assertEquals(keyspace,jt.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + String table = "table"; + jt.setTableName(table); + assertEquals(table,jt.getTableName()); + } + + @Test + public void testGetClusteringOrder() { + String clusteringOrder = "clusteringOrder"; + jt.setClusteringOrder(clusteringOrder); + assertEquals(clusteringOrder,jt.getClusteringOrder()); + } + + @Test + public void testGetPrimaryKey() { + String primaryKey = "primaryKey"; + jt.setPrimaryKey(primaryKey); + assertEquals(primaryKey,jt.getPrimaryKey()); + } + + @Test + public void testFilteringKey() { + jt.setFilteringKey("FilteringKey"); + assertEquals("FilteringKey",jt.getFilteringKey()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java new file mode 100644 index 00000000..e00cb463 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2018 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + *******************************************************************************/ + +package org.onap.music.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonUpdate; + +public class JsonUpdateTest { + + JsonUpdate ju = null; + + @Before + public void init() { + ju = new JsonUpdate(); + } + + + @Test + public void testGetConditions() { + Map mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + ju.setConditions(mapSo); + assertEquals("one",ju.getConditions().get("key1")); + } + + @Test + public void testGetRow_specification() { + Map mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + ju.setRow_specification(mapSo); + assertEquals("one",ju.getRow_specification().get("key1")); + } + + @Test + public void testGetKeyspaceName() { + String keyspace = "keyspace"; + ju.setKeyspaceName(keyspace); + assertEquals(keyspace,ju.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + String table = "table"; + ju.setTableName(table); + assertEquals(table,ju.getTableName()); + } + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + ju.setConsistencyInfo(mapSs); + assertEquals("one",ju.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetTtl() { + ju.setTtl("2000"); + assertEquals("2000",ju.getTtl()); + } + + @Test + public void testGetTimestamp() { + ju.setTimestamp("20:00"); + assertEquals("20:00",ju.getTimestamp()); + + } + + @Test + public void testGetValues() { + Map cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ju.setValues(cons); + assertEquals("one",ju.getValues().get("val1")); + } + + @Test + public void testSerialize() { + assertTrue(ju.serialize() instanceof byte[]); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java new file mode 100644 index 00000000..ceda3f3a --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests.jsonobjects; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.onap.music.eelf.healthcheck.MusicHealthCheck; + +public class MusicHealthCheckTest { + + private MusicHealthCheck musicHealthCheck; + + @Before + public void setUp() + { + musicHealthCheck= new MusicHealthCheck(); + } + + @Test + public void testCassandraHost() + { + musicHealthCheck.setCassandrHost("9042"); + assertEquals("9042", musicHealthCheck.getCassandrHost()); + } + +} diff --git a/music-core/src/test/resources/LICENSE.txt b/music-core/src/test/resources/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/music-core/src/test/resources/LICENSE.txt @@ -0,0 +1,24 @@ + +The following license applies to all files in this and sub-directories. Licenses +are included in individual source files where appropriate, and if it differs +from this text, it supersedes this. Any file that does not have license text +defaults to being covered by this text; not all files support the addition of +licenses. +# +# ------------------------------------------------------------------------- +# Copyright (c) 2017 AT&T Intellectual Property +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +# \ No newline at end of file diff --git a/music-core/src/test/resources/Resources.properties b/music-core/src/test/resources/Resources.properties new file mode 100644 index 00000000..72269cb8 --- /dev/null +++ b/music-core/src/test/resources/Resources.properties @@ -0,0 +1,50 @@ +#============LICENSE_START========================================== +#org.onap.music +#=================================================================== +# Copyright (c) 2017 AT&T Intellectual Property +#=================================================================== +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#============LICENSE_END============================================= +#==================================================================== +#Resource key=Error Code|Message text|Resolution text |Description text +LOADING_DEFAULT_LOG_CONFIGURATION=\ + EELF0001I|\ + Loading default logging configuration from system resource file "{0}"|\ + No external logging configurations were defined or found, So verify the default logging configuration from system resource file (../logback.xml). |\ + Loading default logging configuration from system resource file +LOADING_LOG_CONFIGURATION=EELF0002I|\ + Loading logging configuration from file "{0}"|\ + Verify the correct logging configuration file is loaded. |\ + Loading logging configuration for specific file +LOGGING_ALREADY_INITIALIZED=\ + EELF0003W|\ + Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration.|\ + Verify the container logging definitions to ensure they represent your desired logging configuration. |\ + Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration. +NO_LOG_CONFIGURATION=\ + EELF0004E|\ + No log configuration could be found or defaulted!|\ + No external and default logging configuration file. |\ + No log configuration could be found or defaulted! +SEARCHING_LOG_CONFIGURATION=\ + EELF0005I|\ + Searching path "{0}" for log configuration file "{1}"|\ + Verify the correct Path({user.home};etc;../etc) and filename (eelf.logging.file).|\ + Searching path for specific log configuration file. +UNSUPPORTED_LOGGING_FRAMEWORK=\ + EELF0006E|\ + An unsupported logging framework is bound to SLF4J. |\ + Verify your logging frameworks.|\ + An unsupported logging framework is bound to SLF4J. + diff --git a/music-core/src/test/resources/application.properties b/music-core/src/test/resources/application.properties new file mode 100644 index 00000000..02e9c1a9 --- /dev/null +++ b/music-core/src/test/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8080 +server.servlet.context-path=/MUSIC/rest \ No newline at end of file diff --git a/music-core/src/test/resources/cache.ccf b/music-core/src/test/resources/cache.ccf new file mode 100644 index 00000000..e152ee8b --- /dev/null +++ b/music-core/src/test/resources/cache.ccf @@ -0,0 +1,62 @@ +# DEFAULT CACHE REGION +jcs.default=DC +jcs.default.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes +jcs.default.cacheattributes.MaxObjects=1000 +jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache +jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes +jcs.default.elementattributes.IsEternal=true +jcs.default.elementattributes.IsSpool=true + +# PRE-DEFINED CACHE REGIONS +jcs.region.musicCache= +jcs.region.musicCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes +jcs.region.musicCache.cacheattributes.MaxObjects=1000 +jcs.region.musicCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache +jcs.region.musicCache.cacheattributes.UseMemoryShrinker=false +jcs.region.musicCache.cacheattributes.MaxMemoryIdleTime=3600 +jcs.region.musicCache.cacheattributes.ShrinkerInterval=60 +jcs.region.musicCache.cacheattributes.MaxSpoolPerRun=500 +jcs.region.musicCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes +jcs.region.musicCache.elementattributes.IsEternal=false + + +# PRE-DEFINED CACHE REGIONS +jcs.region.aafCache= +jcs.region.aafCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes +jcs.region.aafCache.cacheattributes.MaxObjects=1000 +jcs.region.aafCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache +jcs.region.aafCache.cacheattributes.UseMemoryShrinker=false +jcs.region.aafCache.cacheattributes.MaxMemoryIdleTime=3600 +jcs.region.aafCache.cacheattributes.ShrinkerInterval=60 +jcs.region.aafCache.cacheattributes.MaxSpoolPerRun=500 +jcs.region.aafCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes +jcs.region.aafCache.elementattributes.IsEternal=false + +# PRE-DEFINED CACHE REGIONS +jcs.region.appNameCache= +jcs.region.appNameCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes +jcs.region.appNameCache.cacheattributes.MaxObjects=1000 +jcs.region.appNameCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache +jcs.region.appNameCache.cacheattributes.UseMemoryShrinker=false +jcs.region.appNameCache.cacheattributes.MaxMemoryIdleTime=3600 +jcs.region.appNameCache.cacheattributes.ShrinkerInterval=60 +jcs.region.appNameCache.cacheattributes.MaxSpoolPerRun=500 +jcs.region.appNameCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes +jcs.region.appNameCache.elementattributes.IsEternal=false + +jcs.default=DC +jcs.default.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes +jcs.default.cacheattributes.MaxObjects=1000 +jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache +jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes +jcs.default.elementattributes.IsEternal=true +jcs.default.elementattributes.IsSpool=true + +jcs.region.eternalCache=DC +jcs.region.eternalCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes +jcs.region.eternalCache.cacheattributes.MaxObjects=1000 +jcs.region.eternalCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache +jcs.region.eternalCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes +jcs.region.eternalCache.elementattributes.IsEternal=true +jcs.region.eternalCache.elementattributes.IsSpool=true + diff --git a/music-core/src/test/resources/logback.xml b/music-core/src/test/resources/logback.xml new file mode 100644 index 00000000..6bc5fd5e --- /dev/null +++ b/music-core/src/test/resources/logback.xml @@ -0,0 +1,302 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + ${logDirectory}/${generalLogName}.log + + + ${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip + 1GB + 5 + 5GB + + + ${applicationLoggerPattern} + + + + + 256 + true + + + + + + ${logDirectory}/${securityLogName}.log + + ${logDirectory}/${securityLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + 256 + 0 + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${auditLoggerPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + + ${metricsLoggerPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${errorLoggerPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/music-core/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/music-core/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 00000000..1f0955d4 --- /dev/null +++ b/music-core/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline diff --git a/music-core/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider b/music-core/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider new file mode 100644 index 00000000..bc2f0992 --- /dev/null +++ b/music-core/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider @@ -0,0 +1 @@ +org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider diff --git a/music-core/src/test/resources/project.properties b/music-core/src/test/resources/project.properties new file mode 100644 index 00000000..199afa33 --- /dev/null +++ b/music-core/src/test/resources/project.properties @@ -0,0 +1,4 @@ +version=${project.version} +artifactId=${project.artifactId} +music.properties=/opt/app/music/etc/music.properties + diff --git a/music-rest/pom.xml b/music-rest/pom.xml new file mode 100755 index 00000000..6c611e88 --- /dev/null +++ b/music-rest/pom.xml @@ -0,0 +1,274 @@ + + + + 4.0.0 + org.onap.music + MUSIC-rest + jar + 3.2.37-SNAPSHOT + + This is the MUSIC Spring-based REST service. + + music-rest + + + org.onap.music + MUSIC + 3.2.37-SNAPSHOT + + + + org.onap.music.MusicApplication + UTF-8 + UTF-8 + UTF-8 + 1.8 + 1.19 + 2.25.1 + 2.0.1 + + UTF-8 + UTF-8 + + https://nexus.onap.org + https://nexus.onap.org + /content/repositories/snapshots/ + /content/repositories/releases/ + /content/repositories/staging/ + /content/sites/site/org/onap/music/${project.version} + + ${maven.build.timestamp} + yyyy.MM.dd.HH.mm + + false + + ${project.version}-${timestamp} + ${project.version}-latest + 1.8 + 1.8 + + + + + + org.springframework.boot + spring-boot-dependencies + 2.1.1.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.data + spring-data-cassandra + + + org.springframework.boot + spring-boot-starter-jersey + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework + spring-aop + compile + + + org.springframework.boot + spring-boot-autoconfigure + + + org.aspectj + aspectjweaver + compile + + + + org.onap.music + MUSIC-core + 3.2.37-SNAPSHOT + + + + com.sun.jersey + jersey-client + ${jersey1.version} + + + com.sun.jersey + jersey-server + ${jersey1.version} + + + com.sun.jersey + jersey-json + ${jersey1.version} + + + com.sun.jersey + jersey-servlet + ${jersey1.version} + + + + + junit + junit + 4.12 + test + + + org.cassandraunit + cassandra-unit-spring + 3.5.0.1 + test + + + org.slf4j + slf4j-log4j12 + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + + + org.cassandraunit + cassandra-unit + + + io.dropwizard.metrics + metrics-core + + + com.addthis.metrics + reporter-config-base + + + + + org.cassandraunit + cassandra-unit-shaded + 3.5.0.1 + test + + + org.mockito + mockito-core + 2.23.4 + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.1.1.RELEASE + + org.onap.music.MusicApplication + ../distribution/music/ + true + MUSIC-SB + + + + install + + repackage + + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + + + diff --git a/music-rest/src/main/java/LICENSE.txt b/music-rest/src/main/java/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/music-rest/src/main/java/LICENSE.txt @@ -0,0 +1,24 @@ + +The following license applies to all files in this and sub-directories. Licenses +are included in individual source files where appropriate, and if it differs +from this text, it supersedes this. Any file that does not have license text +defaults to being covered by this text; not all files support the addition of +licenses. +# +# ------------------------------------------------------------------------- +# Copyright (c) 2017 AT&T Intellectual Property +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +# \ No newline at end of file diff --git a/music-rest/src/main/java/org/onap/music/JerseyConfig.java b/music-rest/src/main/java/org/onap/music/JerseyConfig.java new file mode 100755 index 00000000..b64e7044 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/JerseyConfig.java @@ -0,0 +1,87 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music; + +import io.swagger.jaxrs.config.BeanConfig; +import io.swagger.jaxrs.listing.ApiListingResource; +import io.swagger.jaxrs.listing.SwaggerSerializers; + +import javax.annotation.PostConstruct; + +import org.glassfish.jersey.server.ResourceConfig; +import org.onap.music.conductor.conditionals.RestMusicConditionalAPI; +import org.onap.music.exceptions.MusicExceptionMapper; +import org.onap.music.rest.RestMusicDataAPI; +import org.onap.music.rest.RestMusicHealthCheckAPI; +import org.onap.music.rest.RestMusicLocksAPI; +import org.onap.music.rest.RestMusicQAPI; +import org.onap.music.rest.RestMusicTestAPI; +import org.onap.music.rest.RestMusicVersionAPI; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class JerseyConfig extends ResourceConfig { + + @Value("${spring.jersey.application-path:/}") + private String apiPath; + + public JerseyConfig() { + this.registerEndpoints(); + register(MusicExceptionMapper.class); + } + + @PostConstruct + public void init() { + this.configureSwagger(); + } + + private void registerEndpoints() { + register(RestMusicDataAPI.class); + register(RestMusicLocksAPI.class); + register(RestMusicConditionalAPI.class); + register(RestMusicQAPI.class); + register(RestMusicTestAPI.class); + register(RestMusicVersionAPI.class); + register(RestMusicHealthCheckAPI.class); + + } + + private void configureSwagger() { + // Available at localhost:port/swagger.json + this.register(ApiListingResource.class); + this.register(SwaggerSerializers.class); + + BeanConfig config = new BeanConfig(); + config.setConfigId("MUSIC"); + config.setTitle("MUSIC"); + config.setVersion("v2"); + config.setContact("Thomas Nelson"); + config.setSchemes(new String[] {"http", "https"}); + config.setBasePath("/MUSIC/rest"); + config.setResourcePackage("org.onap.music"); + config.setPrettyPrint(true); + config.setScan(true); + } + +} diff --git a/music-rest/src/main/java/org/onap/music/MusicApplication.java b/music-rest/src/main/java/org/onap/music/MusicApplication.java new file mode 100755 index 00000000..22c9e7bf --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/MusicApplication.java @@ -0,0 +1,203 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import org.onap.aaf.cadi.PropAccess; +import org.onap.music.authentication.CadiAuthFilter; +import org.onap.music.authentication.MusicAuthorizationFilter; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.MusicLoggingServletFilter; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.PropertiesLoader; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.DependsOn; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.context.request.RequestContextListener; + +@SpringBootApplication(scanBasePackages = { "org.onap.music.rest"}) +@EnableAutoConfiguration(exclude = { CassandraDataAutoConfiguration.class }) +@ComponentScan(value = { "org.onap.music" }) +@EnableScheduling +public class MusicApplication extends SpringBootServletInitializer { + + private static final String KEYSPACE_PATTERN = "/v2/keyspaces/*"; + private static final String LOCKS_PATTERN = "/v2/locks/*"; + private static final String Q_PATTERN = "/v2/priorityq/*"; + + @Autowired + private PropertiesLoader propertyLoader; + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicApplication.class); + + + public static void main(String[] args) { + new MusicApplication().configure(new SpringApplicationBuilder(MusicApplication.class)).run(args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + + return application.sources(MusicApplication.class); + } + + @Bean("loadProperties") + public void loadProperties() { + propertyLoader.loadProperties(); + } + + + @Bean + @DependsOn("loadProperties") + public PropAccess propAccess() { + if (MusicUtil.getIsCadi()) { + return new PropAccess(new String[] { + "cadi_prop_files=/opt/app/music/etc/cadi.properties" }); + } else { + return null; + } + } + + @Bean(name = "cadiFilter") + @DependsOn("loadProperties") + public Filter cadiFilter() throws ServletException { + propertyLoader.loadProperties(); + if (MusicUtil.getIsCadi()) { + PropAccess propAccess = propAccess(); + return new CadiAuthFilter(propAccess); + } else { + return (ServletRequest request, ServletResponse response, FilterChain chain) -> { + // do nothing for now. + }; + } + } + + /** + * Added for capturing custom header values from client. + * + * order is set to 1 for this filter + * + * sp931a + * + * @return + * @throws ServletException + */ + @Bean(name="logFilter") + @DependsOn("loadProperties") + public FilterRegistrationBean loggingFilterRegistration() throws ServletException { + logger.info("loggingFilterRegistration called for log filter.."); + propertyLoader.loadProperties(); + FilterRegistrationBean frb = new FilterRegistrationBean<>(); + frb.setFilter(new MusicLoggingServletFilter()); + frb.addUrlPatterns( + KEYSPACE_PATTERN, + LOCKS_PATTERN, + Q_PATTERN + ); + frb.setName("logFilter"); + frb.setOrder(1); + return frb; + } + + @Bean + @DependsOn("loadProperties") + public FilterRegistrationBean cadiFilterRegistration() throws ServletException { + logger.info("cadiFilterRegistration called for cadi filter.."); + FilterRegistrationBean frb = new FilterRegistrationBean<>(); + frb.setFilter(cadiFilter()); + if (MusicUtil.getIsCadi()) { + frb.addUrlPatterns( + KEYSPACE_PATTERN, + LOCKS_PATTERN, + Q_PATTERN + ); + } else { + frb.addUrlPatterns("/v0/test"); + } + frb.setName("cadiFilter"); + frb.setOrder(2); + return frb; + } + + + /** + * Added for Authorization using CADI + * + * sp931a + * + * @return + * @throws ServletException + */ + @Bean + @DependsOn("loadProperties") + public FilterRegistrationBean cadiFilterRegistrationForAuth() throws ServletException { + logger.info("cadiFilterRegistrationForAuth called for cadi auth filter.."); + FilterRegistrationBean frb = new FilterRegistrationBean<>(); + frb.setFilter(cadiMusicAuthFilter()); + + if (MusicUtil.getIsCadi()) { + frb.addUrlPatterns( + KEYSPACE_PATTERN, + LOCKS_PATTERN, + Q_PATTERN + ); + } else { + frb.addUrlPatterns("/v0/test"); + } + frb.setName("cadiMusicAuthFilter"); + frb.setOrder(3); + return frb; + } + + @Bean(name = "cadiMusicAuthFilter") + @DependsOn("loadProperties") + public Filter cadiMusicAuthFilter() throws ServletException { + propertyLoader.loadProperties(); + if (MusicUtil.getIsCadi()) { + return new MusicAuthorizationFilter(); + } else { + return (ServletRequest request, ServletResponse response, FilterChain chain) -> { + // do nothing for now. + }; + } + } + + @Bean + @ConditionalOnMissingBean(RequestContextListener.class) + public RequestContextListener requestContextListener() { + return new RequestContextListener(); + } +} diff --git a/music-rest/src/main/java/org/onap/music/authentication/AuthUtil.java b/music-rest/src/main/java/org/onap/music/authentication/AuthUtil.java new file mode 100644 index 00000000..ee3b77a4 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/authentication/AuthUtil.java @@ -0,0 +1,276 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.authentication; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Pattern; + +import javax.servlet.ServletRequest; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; +import org.onap.aaf.cadi.CadiWrap; +import org.onap.aaf.cadi.Permission; +import org.onap.aaf.cadi.aaf.AAFPermission; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicAuthenticationException; + +public class AuthUtil { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AuthUtil.class); + + private AuthUtil() { + throw new IllegalStateException("Utility class"); + } + + /** + * Get the list of permissions from the Request object. + * + * + * @param request servlet request object + * @return returns list of AAFPermission of the requested MechId for all the + * namespaces + */ + public static List getAAFPermissions(ServletRequest request) { + CadiWrap wrapReq = (CadiWrap) request; + + List perms = wrapReq.getPermissions(wrapReq.getUserPrincipal()); + List aafPermsList = new ArrayList<>(); + for (Permission perm : perms) { + AAFPermission aafPerm = (AAFPermission) perm; + aafPermsList.add(aafPerm); + } + return aafPermsList; + } + + /** + * Here is a sample of a permission object in AAI. The key attribute will have + * Type|Instance|Action. + * AAFPermission: + * NS: null + * Type: org.onap.music.cadi.keyspace ( Permission Type ) + * Instance: tomtest ( Cassandra Keyspace ) + * Action: *|GET|ALL ( Access Level [*|ALL] for full access and [GET] for Read only) + * Key: org.onap.music.cadi.keyspace|tomtest|* + * + * This method will filter all permissions whose key starts with the requested namespace. + * The nsamespace here is the music namespace which is defined in music.property file. + * i;e is the type contains in key is org.onap.music.cadi.keyspace and the namespace + * value is org.onap.music.cadi.keyspace, it will add to list + * otherwise reject. + * + * @param nameSpace + * @param allPermissionsList + * @return + */ + private static List filterNameSpacesAAFPermissions(String nameSpace, + List allPermissionsList) { + List list = new ArrayList<>(); + for (Iterator iterator = allPermissionsList.iterator(); iterator.hasNext();) { + AAFPermission aafPermission = iterator.next(); + if(aafPermission.getType().indexOf(nameSpace) == 0) { + list.add(aafPermission); + } + } + return list; + } + + /** + * Decode certian characters from url encoded to normal. + * + * @param str - String being decoded. + * @return returns the decoded string. + * @throws Exception throws excpetion + */ + public static String decodeFunctionCode(String str) throws MusicAuthenticationException { + final String DECODEVALUE_FORWARDSLASH = "2f"; + final String DECODEVALUE_HYPHEN = "2d"; + final String DECODEVALUE_ASTERISK = "2a"; + String decodedString = str; + List decodingList = new ArrayList<>(); + decodingList.add(Pattern.compile(DECODEVALUE_FORWARDSLASH)); + decodingList.add(Pattern.compile(DECODEVALUE_HYPHEN)); + decodingList.add(Pattern.compile(DECODEVALUE_ASTERISK)); + for (Pattern xssInputPattern : decodingList) { + try { + decodedString = decodedString.replaceAll("%" + xssInputPattern, + new String(Hex.decodeHex(xssInputPattern.toString().toCharArray()))); + } catch (DecoderException e) { + logger.error(EELFLoggerDelegate.securityLogger, + "AuthUtil Decode Failed! for instance: " + str); + throw new MusicAuthenticationException("Decode failed", e); + } + } + + return decodedString; + } + + /** + * + * + * @param request servlet request object + * @param nameSpace application namespace + * @return boolean value if the access is allowed + * @throws Exception throws exception + */ + public static boolean isAccessAllowed(ServletRequest request, String nameSpace) throws MusicAuthenticationException { + + if (request==null) { + throw new MusicAuthenticationException("Request cannot be null"); + } + + if (nameSpace==null || nameSpace.isEmpty()) { + throw new MusicAuthenticationException("NameSpace not Declared!"); + } + + boolean isauthorized = false; + List aafPermsList = getAAFPermissions(request); + logger.info(EELFLoggerDelegate.securityLogger, + "AAFPermission of the requested MechId for all the namespaces: " + aafPermsList); + logger.debug(EELFLoggerDelegate.securityLogger, "Requested nameSpace: " + nameSpace); + + List aafPermsFinalList = filterNameSpacesAAFPermissions(nameSpace, aafPermsList); + + logger.debug(EELFLoggerDelegate.securityLogger, + "AuthUtil list of AAFPermission for the specific namespace :::" + + aafPermsFinalList); + + HttpServletRequest httpRequest = (HttpServletRequest) request; + String requestUri = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length() + 1); + + logger.debug(EELFLoggerDelegate.securityLogger, + "AuthUtil requestUri :::" + requestUri); + + for (Iterator iterator = aafPermsFinalList.iterator(); iterator.hasNext();) { + AAFPermission aafPermission = iterator.next(); + if(!isauthorized) { + isauthorized = isMatchPattern(aafPermission, requestUri, httpRequest.getMethod()); + } + } + + logger.debug(EELFLoggerDelegate.securityLogger, + "isAccessAllowed for the request uri: " + requestUri + "is :" + isauthorized); + return isauthorized; + } + + /** + * + * This method will check, if the requested URI matches any of the instance + * found with the AAF permission list. + * i;e if the request URI is; /v2/keyspaces/tomtest/tables/emp15 and in the + * AAF permission table, we have an instance + * defined as "tomtest" mapped the logged in user, it will allow else error. + * + * User trying to create or aquire a lock + * Here is the requested URI /v2/locks/create/tomtest.MyTable.Field1 + * Here the keyspace name i;e tomtest will be test throught out the URL if it + * matches, it will allow the user to create a lock. + * "tomtest" here is the key, which is mapped as an instance in permission object. + * Instance can be delimited with ":" i;e ":music-cassandra-1908-dev:admin". In this case, + * each delimited + * token will be matched with that of request URI. + * + * Example Permission: + * org.onap.music.api.user.access|tomtest|* or ALL + * org.onap.music.api.user.access|tomtest|GET + * In case of the action field is ALL and *, user will be allowed else it will + * be matched with the requested http method type. + * + * + * + * @param aafPermission - AAfpermission obtained by cadi. + * @param requestUri - Rest URL client is calling. + * @param method - REST Method being used (GET,POST,PUT,DELETE) + * @return returns a boolean + * @throws Exception - throws an exception + */ + private static boolean isMatchPattern( + AAFPermission aafPermission, + String requestUri, + String method) throws MusicAuthenticationException { + if (null == aafPermission || null == requestUri || null == method) { + return false; + } + + String permKey = aafPermission.getKey(); + + logger.debug(EELFLoggerDelegate.securityLogger, "isMatchPattern permKey: " + + permKey + ", requestUri " + requestUri + " ," + method); + + String[] keyArray = permKey.split("\\|"); + String[] subPath = null; + String instance = keyArray[1]; + String action = keyArray[2]; + + //if the instance & action both are * , then allow + if ("*".equalsIgnoreCase(instance) && "*".equalsIgnoreCase(action)) { + return true; + } + //Decode string like %2f, %2d and %2a + if (!"*".equals(instance)) { + instance = decodeFunctionCode(instance); + } + if (!"*".equals(action)) { + action = decodeFunctionCode(action); + } + //Instance: :music-cassandra-1908-dev:admin + List instanceList = Arrays.asList(instance.split(":")); + + String[] path = requestUri.split("/"); + + for (int i = 0; i < path.length; i++) { + // Sometimes the value will begin with "$", so we need to remove it + if (path[i].startsWith("$")) { + path[i] = path[i].replace("$",""); + } + // Each path element can again delemited by ".";i;e + // tomtest.tables.emp. We have scenarios like lock aquire URL + subPath = path[i].split("\\."); + for (int j = 0; j < subPath.length; j++) { + if (instanceList.contains(subPath[j])) { + return checkAction(method,action); + } else { + continue; + } + } + } + return false; + } + + private static boolean checkAction(String method, String action) { + if ("*".equals(action) || "ALL".equalsIgnoreCase(action)) { + return true; + } else { + return (method.equalsIgnoreCase(action)); + } + } + + + +} \ No newline at end of file diff --git a/music-rest/src/main/java/org/onap/music/authentication/AuthorizationError.java b/music-rest/src/main/java/org/onap/music/authentication/AuthorizationError.java new file mode 100644 index 00000000..7015b550 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/authentication/AuthorizationError.java @@ -0,0 +1,55 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.authentication; + + +/** + * Authorization error class used while setting error code and description back to client. + * + * + * @author sp931a + * + */ +public class AuthorizationError { + + private int responseCode; + + private String responseMessage; + + public int getResponseCode() { + return responseCode; + } + + public void setResponseCode(int responseCode) { + this.responseCode = responseCode; + } + + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + +} \ No newline at end of file diff --git a/music-rest/src/main/java/org/onap/music/authentication/CadiAuthFilter.java b/music-rest/src/main/java/org/onap/music/authentication/CadiAuthFilter.java new file mode 100644 index 00000000..d043e6d6 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/authentication/CadiAuthFilter.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.authentication; + + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; + +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.onap.music.eelf.logging.EELFLoggerDelegate; + +@WebFilter(urlPatterns = { "/*" }) +public class CadiAuthFilter extends CadiFilter { + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CadiAuthFilter.class); + + public CadiAuthFilter(PropAccess access) throws ServletException { + super(true, access); + } + + public CadiAuthFilter() throws ServletException { + super(); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + super.init(filterConfig); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + logger.info(EELFLoggerDelegate.securityLogger, "Request is entering cadifilter"); + long startTime = System.currentTimeMillis(); + request.setAttribute("startTime", startTime); + super.doFilter(request, response, chain); + } +} \ No newline at end of file diff --git a/music-rest/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java b/music-rest/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java new file mode 100644 index 00000000..bde3e205 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java @@ -0,0 +1,122 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.authentication; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicAuthenticationException; +import org.onap.music.main.MusicUtil; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * This filter class does authorization from AAF + * + * @author sp931a + * + */ +//@PropertySource(value = {"file:/opt/app/music/etc/music.properties"}) +public class MusicAuthorizationFilter implements Filter { + + private String musicNS = MusicUtil.getMusicAafNs(); + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthorizationFilter.class); + + public MusicAuthorizationFilter() throws ServletException { + super(); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // Do Nothing + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + HttpServletResponse httpResponse = null; + + boolean isAuthAllowed = false; + + if (null != servletRequest && null != servletResponse) { + httpResponse = (HttpServletResponse) servletResponse; + long startTime = 0; + if( null != servletRequest.getAttribute("startTime")) { + startTime = ((Long)servletRequest.getAttribute("startTime")).longValue(); + } else { + startTime = System.currentTimeMillis(); // this will set only incase the request attribute not found + } + + try { + isAuthAllowed = AuthUtil.isAccessAllowed(servletRequest, musicNS); + } catch (MusicAuthenticationException e) { + logger.error(EELFLoggerDelegate.securityLogger, + "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage(),e); + } catch ( Exception e) { + logger.error(EELFLoggerDelegate.securityLogger, + "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage(),e); + } + + long endTime = System.currentTimeMillis(); + + //startTime set in CadiAuthFilter doFilter + logger.debug(EELFLoggerDelegate.securityLogger, + "Time took for authentication & authorization : " + + (endTime - startTime) + " milliseconds"); + + if (!isAuthAllowed) { + logger.info(EELFLoggerDelegate.securityLogger, + "Unauthorized Access"); + AuthorizationError authError = new AuthorizationError(); + authError.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); + authError.setResponseMessage("Unauthorized Access - Please make sure you are " + + "onboarded and have proper access to MUSIC. "); + + byte[] responseToSend = restResponseBytes(authError); + httpResponse.setHeader("Content-Type", "application/json"); + + httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + servletResponse.getOutputStream().write(responseToSend); + return; + } else { + filterChain.doFilter(servletRequest, servletResponse); + } + } + } + + private byte[] restResponseBytes(AuthorizationError eErrorResponse) throws IOException { + String serialized = new ObjectMapper().writeValueAsString(eErrorResponse); + return serialized.getBytes(); + } +} + diff --git a/music-rest/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java b/music-rest/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java new file mode 100644 index 00000000..4efcabea --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java @@ -0,0 +1,90 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.conductor.conditionals; + +import java.io.Serializable; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import io.swagger.annotations.ApiModel; + +@ApiModel(value = "JsonConditional", description = "Json model for insert or update into table based on some conditions") +@JsonIgnoreProperties(ignoreUnknown = true) +public class JsonConditional implements Serializable { + + private String primaryKey; + private String primaryKeyValue; + private String casscadeColumnName; + private Map tableValues; + private Map casscadeColumnData; + private Map> conditions; + + public Map getTableValues() { + return tableValues; + } + public void setTableValues(Map tableValues) { + this.tableValues = tableValues; + } + + public String getPrimaryKey() { + return primaryKey; + } + public String getPrimaryKeyValue() { + return primaryKeyValue; + } + public String getCasscadeColumnName() { + return casscadeColumnName; + } + + public Map getCasscadeColumnData() { + return casscadeColumnData; + } + + + + public void setPrimaryKey(String primaryKey) { + this.primaryKey = primaryKey; + } + public void setPrimaryKeyValue(String primaryKeyValue) { + this.primaryKeyValue = primaryKeyValue; + } + public Map> getConditions() { + return conditions; + } + public void setConditions(Map> conditions) { + this.conditions = conditions; + } + public void setCasscadeColumnName(String casscadeColumnName) { + this.casscadeColumnName = casscadeColumnName; + } + + public void setCasscadeColumnData(Map casscadeColumnData) { + this.casscadeColumnData = casscadeColumnData; + } + + + + + +} \ No newline at end of file diff --git a/music-rest/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java b/music-rest/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java new file mode 100644 index 00000000..18fa8a18 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java @@ -0,0 +1,379 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (C) 2019 IBM. + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.conductor.conditionals; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; + +import org.codehaus.jettison.json.JSONObject; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.rest.RestMusicDataAPI; + +import com.datastax.driver.core.ColumnDefinitions; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.TableMetadata; + +public class MusicConditional { + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); + + public static ReturnType conditionalInsert(String keyspace, String tablename, String casscadeColumnName, + Map casscadeColumnData, String primaryKey, Map valuesMap, + Map status) throws Exception { + + Map queryBank = new HashMap<>(); + TableMetadata tableInfo = null; + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); + String primaryId = tableInfo.getPrimaryKey().get(0).getName(); + DataType casscadeColumnType = tableInfo.getColumn(casscadeColumnName).getType(); + String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + + PreparedQueryObject select = new PreparedQueryObject(); + select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?"); + select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey)); + queryBank.put(MusicUtil.SELECT, select); + + PreparedQueryObject update = new PreparedQueryObject(); + //casscade column values + Map updateColumnvalues = getValues(true, casscadeColumnData, status); + Object formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, updateColumnvalues); + update.appendQueryString("UPDATE " + keyspace + "." + tablename + " SET " + casscadeColumnName + " =" + + casscadeColumnName + " + ? , vector_ts = ?" + " WHERE " + primaryId + " = ? "); + update.addValue(formatedValues); + update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector)); + update.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey)); + queryBank.put(MusicUtil.UPDATE, update); + + + //casscade column values + Map insertColumnvalues = getValues(false, casscadeColumnData, status); + formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, insertColumnvalues); + PreparedQueryObject insert = extractQuery(valuesMap, tableInfo, tablename, keyspace, primaryId, primaryKey,casscadeColumnName,formatedValues); + queryBank.put(MusicUtil.INSERT, insert); + + + String key = keyspace + "." + tablename + "." + primaryKey; + String lockId; + try { + lockId = MusicCore.createLockReference(key); + } catch (MusicLockingException e) { + return new ReturnType(ResultType.FAILURE, e.getMessage()); + } + long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); + ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod); + + try { + if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { + ReturnType criticalPutResult = conditionalInsertAtomic(lockId, keyspace, tablename, primaryKey, + queryBank); + MusicCore.destroyLockRef(lockId); + if (criticalPutResult.getMessage().contains("insert")) + criticalPutResult + .setMessage("Insert values: "); + else if (criticalPutResult.getMessage().contains("update")) + criticalPutResult + .setMessage("Update values: " + updateColumnvalues); + return criticalPutResult; + + } else { + MusicCore.destroyLockRef(lockId); + return lockAcqResult; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger, e); + MusicCore.destroyLockRef(lockId); + return new ReturnType(ResultType.FAILURE, e.getMessage()); + } + + } + + public static ReturnType conditionalInsertAtomic(String lockId, String keyspace, String tableName, + String primaryKey, Map queryBank) { + + ResultSet results = null; + + try { + String fullyQualifiedKey = keyspace + "." + tableName + "." + primaryKey; + ReturnType lockAcqResult = MusicCore.acquireLock(fullyQualifiedKey, lockId); + if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { + try { + results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryBank.get(MusicUtil.SELECT)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger, e); + return new ReturnType(ResultType.FAILURE, e.getMessage()); + } + if (results.all().isEmpty()) { + MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), "critical"); + return new ReturnType(ResultType.SUCCESS, "insert"); + } else { + MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.UPDATE), "critical"); + return new ReturnType(ResultType.SUCCESS, "update"); + } + } else { + return new ReturnType(ResultType.FAILURE, + "Cannot perform operation since you are the not the lock holder"); + } + + } catch (Exception e) { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + String exceptionAsString = sw.toString(); + logger.error(EELFLoggerDelegate.applicationLogger, e); + return new ReturnType(ResultType.FAILURE, + "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" + + exceptionAsString); + } + + } + + public static ReturnType update(UpdateDataObject dataObj) + throws MusicLockingException, MusicQueryException, MusicServiceException { + + String key = dataObj.getKeyspace() + "." + dataObj.getTableName() + "." + dataObj.getPrimaryKeyValue(); + String lockId = MusicCore.createLockReference(key); + long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); + ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod); + + try { + + if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { + ReturnType criticalPutResult = updateAtomic(new UpdateDataObject().setLockId(lockId) + .setKeyspace(dataObj.getKeyspace()) + .setTableName( dataObj.getTableName()) + .setPrimaryKey(dataObj.getPrimaryKey()) + .setPrimaryKeyValue(dataObj.getPrimaryKeyValue()) + .setQueryBank(dataObj.getQueryBank()) + .setPlanId(dataObj.getPlanId()) + .setCascadeColumnValues(dataObj.getCascadeColumnValues()) + .setCascadeColumnName(dataObj.getCascadeColumnName())); + + MusicCore.destroyLockRef(lockId); + return criticalPutResult; + } else { + MusicCore.destroyLockRef(lockId); + return lockAcqResult; + } + + } catch (Exception e) { + MusicCore.destroyLockRef(lockId); + logger.error(EELFLoggerDelegate.applicationLogger, e); + return new ReturnType(ResultType.FAILURE, e.getMessage()); + + } + } + + public static ReturnType updateAtomic(UpdateDataObject dataObj) { + try { + String fullyQualifiedKey = dataObj.getKeyspace() + "." + dataObj.getTableName() + "." + dataObj.getPrimaryKeyValue(); + ReturnType lockAcqResult = MusicCore.acquireLock(fullyQualifiedKey, dataObj.getLockId()); + + if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { + Row row = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(dataObj.getQueryBank().get(MusicUtil.SELECT)).one(); + + if(row != null) { + Map updatedValues = cascadeColumnUpdateSpecific(row, dataObj.getCascadeColumnValues(), dataObj.getCascadeColumnName(), dataObj.getPlanId()); + JSONObject json = new JSONObject(updatedValues); + PreparedQueryObject update = new PreparedQueryObject(); + String vector_ts = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + update.appendQueryString("UPDATE " + dataObj.getKeyspace() + "." + dataObj.getTableName() + " SET " + dataObj.getCascadeColumnName() + "['" + dataObj.getPlanId() + + "'] = ?, vector_ts = ? WHERE " + dataObj.getPrimaryKey() + " = ?"); + update.addValue(MusicUtil.convertToActualDataType(DataType.text(), json.toString())); + update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector_ts)); + update.addValue(MusicUtil.convertToActualDataType(DataType.text(), dataObj.getPrimaryKeyValue())); + try { + MusicDataStoreHandle.getDSHandle().executePut(update, "critical"); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.applicationLogger, ex); + return new ReturnType(ResultType.FAILURE, ex.getMessage()); + } + }else { + return new ReturnType(ResultType.FAILURE,"Cannot find data related to key: "+dataObj.getPrimaryKey()); + } + MusicDataStoreHandle.getDSHandle().executePut(dataObj.getQueryBank().get(MusicUtil.UPSERT), "critical"); + return new ReturnType(ResultType.SUCCESS, "update success"); + + } else { + return new ReturnType(ResultType.FAILURE, + "Cannot perform operation since you are the not the lock holder"); + } + + } catch (Exception e) { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + String exceptionAsString = sw.toString(); + logger.error(EELFLoggerDelegate.applicationLogger, e); + return new ReturnType(ResultType.FAILURE, + "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" + + exceptionAsString); + } + + } + + @SuppressWarnings("unchecked") + public static Map getValues(boolean isExists, Map casscadeColumnData, + Map status) { + + Map returnMap = new HashMap<>(); + Object key = casscadeColumnData.get("key"); + String setStatus = ""; + Map value = (Map) casscadeColumnData.get("value"); + + if (isExists) + setStatus = status.get("exists"); + else + setStatus = status.get("nonexists"); + + value.put("status", setStatus); + JSONObject valueJson = new JSONObject(value); + returnMap.put(key.toString(), valueJson.toString()); + return returnMap; + + } + + public static PreparedQueryObject extractQuery(Map valuesMap, TableMetadata tableInfo, String tableName, + String keySpaceName,String primaryKeyName,String primaryKey,String casscadeColumn,Object casscadeColumnValues) throws Exception { + + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder fieldsString = new StringBuilder("(vector_ts"+","); + StringBuilder valueString = new StringBuilder("(" + "?" + ","); + String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + String localPrimaryKey; + queryObject.addValue(vector); + if(casscadeColumn!=null && casscadeColumnValues!=null) { + fieldsString.append(casscadeColumn).append(" ,"); + valueString.append("?,"); + queryObject.addValue(casscadeColumnValues); + } + + int counter = 0; + for (Map.Entry entry : valuesMap.entrySet()) { + + fieldsString.append(entry.getKey()); + Object valueObj = entry.getValue(); + if (primaryKeyName.equals(entry.getKey())) { + localPrimaryKey = entry.getValue() + ""; + localPrimaryKey = localPrimaryKey.replace("'", "''"); + } + DataType colType = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + } catch(NullPointerException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey(), + AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR, ex); + } + + Object formattedValue = null; + try { + formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e); + } + + valueString.append("?"); + queryObject.addValue(formattedValue); + + + if (counter == valuesMap.size() - 1) { + fieldsString.append(")"); + valueString.append(")"); + } else { + fieldsString.append(","); + valueString.append(","); + } + counter = counter + 1; + } + queryObject.appendQueryString("INSERT INTO " + keySpaceName + "." + tableName + " " + + fieldsString + " VALUES " + valueString); + return queryObject; + } + + public static Object getColValue(Row row, String colName, DataType colType) { + switch (colType.getName()) { + case VARCHAR: + return row.getString(colName); + case UUID: + return row.getUUID(colName); + case VARINT: + return row.getVarint(colName); + case BIGINT: + return row.getLong(colName); + case INT: + return row.getInt(colName); + case FLOAT: + return row.getFloat(colName); + case DOUBLE: + return row.getDouble(colName); + case BOOLEAN: + return row.getBool(colName); + case MAP: + return row.getMap(colName, String.class, String.class); + default: + return null; + } + } + + @SuppressWarnings("unchecked") + public static Map cascadeColumnUpdateSpecific(Row row, Map changeOfStatus, + String cascadeColumnName, String planId) { + + ColumnDefinitions colInfo = row.getColumnDefinitions(); + DataType colType = colInfo.getType(cascadeColumnName); + Object columnValue = getColValue(row, cascadeColumnName, colType); + + Map finalValues = new HashMap<>(); + Map values = (Map) columnValue; + if (values != null && values.keySet().contains(planId)) { + String valueString = values.get(planId); + String tempValueString = valueString.replaceAll("\\{", "").replaceAll("\"", "").replaceAll("\\}", ""); + String[] elements = tempValueString.split(","); + for (String str : elements) { + String[] keyValue = str.split(":"); + if ((changeOfStatus.keySet().contains(keyValue[0].replaceAll("\\s", "")))) + keyValue[1] = changeOfStatus.get(keyValue[0].replaceAll("\\s", "")); + finalValues.put(keyValue[0], keyValue[1]); + } + } + return finalValues; + + } + +} diff --git a/music-rest/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java b/music-rest/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java new file mode 100644 index 00000000..584a9e47 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java @@ -0,0 +1,205 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.conductor.conditionals; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +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.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.conductor.*; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TableMetadata; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiParam; + +@Path("/v2/conditional") +@Api(value = "Conditional Api", hidden = true) +public class RestMusicConditionalAPI { + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicConditionalAPI.class); + private static final String XMINORVERSION = "X-minorVersion"; + private static final String XPATCHVERSION = "X-patchVersion"; + private static final String NS = "ns"; + private static final String VERSION = "v2"; + + @POST + @Path("/insert/keyspaces/{keyspace}/tables/{tablename}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response insertConditional( + @ApiParam(value = "Major Version", required = true) + @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) + @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version", required = false) + @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = true) + @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) + @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) + @HeaderParam("Authorization") String authorization, + @ApiParam(value = "Keyspace Name", required = true) + @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) + @PathParam("tablename") String tablename, + JsonConditional jsonObj) throws Exception { + ResponseBuilder response = + MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + String primaryKey = jsonObj.getPrimaryKey(); + String primaryKeyValue = jsonObj.getPrimaryKeyValue(); + String casscadeColumnName = jsonObj.getCasscadeColumnName(); + Map tableValues = jsonObj.getTableValues(); + Map casscadeColumnData = jsonObj.getCasscadeColumnData(); + Map> conditions = jsonObj.getConditions(); + + if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null + || tableValues.isEmpty() || casscadeColumnData.isEmpty() || conditions.isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE) + .setError(String.valueOf("One or more input values missing")).toMap()).build(); + } + Map authMap = null; + Map valuesMap = new LinkedHashMap<>(); + for (Map.Entry entry : tableValues.entrySet()) { + valuesMap.put(entry.getKey(), entry.getValue()); + } + + Map status = new HashMap<>(); + status.put("exists", conditions.get("exists").get("status")); + status.put("nonexists", conditions.get("nonexists").get("status")); + ReturnType out = null; + + out = MusicConditional.conditionalInsert(keyspace, tablename, + casscadeColumnName, casscadeColumnData,primaryKeyValue, valuesMap, status); + return response.status(Status.OK).entity(new JsonResponse( + out.getResult()).setMessage(out.getMessage()).toMap()) + .build(); + + } + + @SuppressWarnings("unchecked") + @PUT + @Path("/update/keyspaces/{keyspace}/tables/{tablename}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response updateConditional( + @ApiParam(value = "Major Version", required = true) + @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) + @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version", required = false) + @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = true) + @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) + @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) + @HeaderParam("Authorization") String authorization, + @ApiParam(value = "Major Version", required = true) + @PathParam("keyspace") String keyspace, + @ApiParam(value = "Major Version", required = true) + @PathParam("tablename") String tablename, + JsonConditional upObj) throws Exception { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + + String primaryKey = upObj.getPrimaryKey(); + String primaryKeyValue = upObj.getPrimaryKeyValue(); + String casscadeColumnName = upObj.getCasscadeColumnName(); + Map casscadeColumnData = upObj.getCasscadeColumnData(); + Map tableValues = upObj.getTableValues(); + + if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null + || casscadeColumnData.isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE) + .setError(String.valueOf("One or more input values missing")).toMap()).build(); + + } + + Map casscadeColumnValueMap = + (Map) casscadeColumnData.get("value"); + TableMetadata tableInfo = null; + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); + String primaryId = tableInfo.getPrimaryKey().get(0).getName(); + + PreparedQueryObject select = new PreparedQueryObject(); + select.appendQueryString("SELECT * FROM " + keyspace + "." + + tablename + " where " + primaryId + " = ?"); + select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue)); + + PreparedQueryObject upsert = + MusicConditional.extractQuery(tableValues, tableInfo, tablename, + keyspace, primaryKey, primaryKeyValue, null, null); + Map queryBank = new HashMap<>(); + queryBank.put(MusicUtil.SELECT, select); + queryBank.put(MusicUtil.UPSERT, upsert); + String planId = casscadeColumnData.get("key").toString(); + ReturnType result = MusicConditional.update(new UpdateDataObject().setQueryBank(queryBank) + .setKeyspace(keyspace) + .setTableName(tablename) + .setPrimaryKey(primaryKey) + .setPrimaryKeyValue(primaryKeyValue) + .setPlanId(planId) + .setCascadeColumnName(casscadeColumnName) + .setCascadeColumnValues(casscadeColumnValueMap)); + if (result.getResult() == ResultType.SUCCESS) { + return response.status(Status.OK) + .entity(new JsonResponse(result.getResult()) + .setMessage(result.getMessage()).toMap()).build(); + } + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(result.getResult()) + .setMessage(result.getMessage()).toMap()).build(); + + } + +} \ No newline at end of file diff --git a/music-rest/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java b/music-rest/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java new file mode 100644 index 00000000..1ea8994e --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Samsung Electronics Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.music.conductor.conditionals; + +import java.util.Map; +import org.onap.music.datastore.PreparedQueryObject; + +public class UpdateDataObject { + + Map queryBank; + String keyspace; + String tableName; + String primaryKey; + String primaryKeyValue; + String planId; + String cascadeColumnName; + Map cascadeColumnValues; + String lockId; + + public Map getQueryBank() { + return queryBank; + } + + public UpdateDataObject setQueryBank(Map queryBank) { + this.queryBank = queryBank; + return this; + } + + public String getKeyspace() { + return keyspace; + } + + public UpdateDataObject setKeyspace(String keyspace) { + this.keyspace = keyspace; + return this; + } + + public String getTableName() { + return tableName; + } + + public UpdateDataObject setTableName(String tableName) { + this.tableName = tableName; + return this; + } + + public String getPrimaryKey() { + return primaryKey; + } + + public UpdateDataObject setPrimaryKey(String primaryKey) { + this.primaryKey = primaryKey; + return this; + } + + public String getPrimaryKeyValue() { + return primaryKeyValue; + } + + public UpdateDataObject setPrimaryKeyValue(String primaryKeyValue) { + this.primaryKeyValue = primaryKeyValue; + return this; + } + + public String getPlanId() { + return planId; + } + + public UpdateDataObject setPlanId(String planId) { + this.planId = planId; + return this; + } + + public String getCascadeColumnName() { + return cascadeColumnName; + } + + public UpdateDataObject setCascadeColumnName(String cascadeColumnName) { + this.cascadeColumnName = cascadeColumnName; + return this; + } + + public Map getCascadeColumnValues() { + return cascadeColumnValues; + } + + public UpdateDataObject setLockId(String lockId) { + this.lockId=lockId; + return this; + } + + public String getLockId() { + return lockId; + } + + public UpdateDataObject setCascadeColumnValues(Map cascadeColumnValues) { + this.cascadeColumnValues = cascadeColumnValues; + return this; + } + + +} diff --git a/music-rest/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java b/music-rest/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java new file mode 100644 index 00000000..fbfc0de6 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java @@ -0,0 +1,130 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.eelf.healthcheck; + +import java.util.UUID; + +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.MusicCore; + +import com.datastax.driver.core.ConsistencyLevel; + +/** + * @author inam + * + */ +public class MusicHealthCheck { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + + private String cassandrHost; + + public String getCassandraStatus(String consistency) { + logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra"); + + boolean result = false; + UUID randomUUID = UUID.randomUUID(); + try { + result = getAdminKeySpace(consistency, randomUUID); + } catch( Exception e) { + if(e.getMessage().toLowerCase().contains("unconfigured table healthcheck")) { + logger.error("Error", e); + logger.debug("Creating table...."); + try { + boolean ksresult = createKeyspace(); + if(ksresult) { + result = getAdminKeySpace(consistency, randomUUID); + } + } catch (MusicServiceException e1) { + logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN, e1); + } catch (MusicQueryException e1) { + logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN,e1); + } + } else { + logger.error("Error", e); + return "One or more nodes are down or not responding."; + } + } + try { + cleanHealthCheckId(randomUUID); + } catch (MusicServiceException | MusicQueryException e) { + logger.error("Error while cleaning healthcheck record id...", e); + } + if (result) { + return "ACTIVE"; + } else { + logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra Service is not responding"); + return "INACTIVE"; + } + } + + private Boolean getAdminKeySpace(String consistency, UUID randomUUID) throws MusicServiceException,MusicQueryException { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("insert into admin.healthcheck (id) values (?)"); + pQuery.addValue(randomUUID); + ResultType rs = null; + rs = MusicCore.nonKeyRelatedPut(pQuery, consistency); + logger.info(rs.toString()); + return null != rs; + + } + + private void cleanHealthCheckId(UUID randomUUID) throws MusicServiceException, MusicQueryException { + String cleanQuery = "delete from admin.healthcheck where id = ?"; + PreparedQueryObject deleteQueryObject = new PreparedQueryObject(); + deleteQueryObject.appendQueryString(cleanQuery); + deleteQueryObject.addValue(randomUUID); + MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "eventual"); + logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra healthcheck responded and cleaned up."); + } + + + + private boolean createKeyspace() throws MusicServiceException,MusicQueryException { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("CREATE TABLE admin.healthcheck (id uuid PRIMARY KEY)"); + ResultType rs = null ; + rs = MusicCore.nonKeyRelatedPut(pQuery, ConsistencyLevel.ONE.toString()); + return rs != null && rs.getResult().toLowerCase().contains("success"); + } + + public String getCassandrHost() { + return cassandrHost; + } + + public void setCassandrHost(String cassandrHost) { + this.cassandrHost = cassandrHost; + } + +} \ No newline at end of file diff --git a/music-rest/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java b/music-rest/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java new file mode 100644 index 00000000..bac02afa --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java @@ -0,0 +1,68 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.eelf.logging; + +import java.io.IOException; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; + +import org.springframework.stereotype.Component; + + +/** + * This filter filter/modifies outbound http responses just before sending back to client. + * + * @author sp931a + * + */ +@Component +public class MusicContainerFilter implements ContainerResponseFilter { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicContainerFilter.class); + + public MusicContainerFilter() { + + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) + throws IOException { + if (null != EELFLoggerDelegate.mdcGet("transactionId")) { + EELFLoggerDelegate.mdcRemove("transactionId"); + } + + if (null != EELFLoggerDelegate.mdcGet("conversationId")) { + EELFLoggerDelegate.mdcRemove("conversationId"); + } + + if (null != EELFLoggerDelegate.mdcGet("clientId")) { + EELFLoggerDelegate.mdcRemove("clientId"); + } + + if (null != EELFLoggerDelegate.mdcGet("messageId")) { + EELFLoggerDelegate.mdcRemove("messageId"); + } + } + +} diff --git a/music-rest/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java b/music-rest/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java new file mode 100644 index 00000000..c8c6ba65 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java @@ -0,0 +1,207 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ +package org.onap.music.eelf.logging; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.music.authentication.AuthorizationError; +import org.onap.music.main.MusicUtil; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * This is the first filter in the chain to be executed before cadi + * authentication. The priority has been set in MusicApplication + * through filter registration bean + * + * The responsibility of this filter is to validate header values as per + * contract and write it to MDC and http response header back. + * + * + * @author sp931a + * + */ + +public class MusicLoggingServletFilter implements Filter { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicLoggingServletFilter.class); + // client transaction id, specific to client system, set in properties + public static final String CONVERSATION_ID = MusicUtil.getConversationIdPrefix() + "ConversationId"; + + // can be used as correlation-id in case of callback, also this can be passed to + // other services for tracking. + public static final String MESSAGE_ID = MusicUtil.getMessageIdPrefix() + "MessageId"; + + // client id would be the unique client source-system-id, i;e VALET or CONDUCTOR + // etc + public static final String CLIENT_ID = MusicUtil.getClientIdPrefix() + "ClientId"; + + // unique transaction of the source system + private static final String TRANSACTION_ID = MusicUtil.getTransIdPrefix() + "Transaction-Id"; + + public MusicLoggingServletFilter() throws ServletException { + super(); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + + logger.info(EELFLoggerDelegate.securityLogger, + "In MusicLogginServletFilter doFilter start() :: [\"+MusicUtil.getTransIdRequired()+\",\"+MusicUtil.getConversationIdRequired()+\",\"+MusicUtil.getClientIdRequired()+\",\"+MusicUtil.getMessageIdRequired()"); + + HttpServletRequest httpRequest = null; + HttpServletResponse httpResponse = null; + Map headerMap = null; + Map upperCaseHeaderMap = null; + + if (null != request && null != response) { + httpRequest = (HttpServletRequest) request; + httpResponse = (HttpServletResponse) response; + + headerMap = getHeadersInfo(httpRequest); + + // The custom header values automatically converted into lower case, not sure + // why ? So i had to covert all keys to upper case + // The response header back to client will have all custom header values as + // upper case. + upperCaseHeaderMap = headerMap.entrySet().stream() + .collect(Collectors.toMap(entry -> entry.getKey().toUpperCase(), entry -> entry.getValue())); + // Enable/disable keys are present in /opt/app/music/etc/music.properties + + if (MusicUtil.getTransIdRequired() + && !upperCaseHeaderMap.containsKey(TRANSACTION_ID.toUpperCase())) { + populateError(httpResponse, "Transaction id '" + TRANSACTION_ID + + "' required on http header"); + return; + } else { + populateMDCAndResponseHeader(upperCaseHeaderMap, TRANSACTION_ID, "transactionId", + MusicUtil.getTransIdRequired(), httpResponse); + } + + if (MusicUtil.getConversationIdRequired() + && !upperCaseHeaderMap.containsKey(CONVERSATION_ID.toUpperCase())) { + populateError(httpResponse, "Conversation Id '" + CONVERSATION_ID + + "' required on http header"); + return; + } else { + populateMDCAndResponseHeader(upperCaseHeaderMap, CONVERSATION_ID, "conversationId", + MusicUtil.getConversationIdRequired(), httpResponse); + } + + if (MusicUtil.getMessageIdRequired() + && !upperCaseHeaderMap.containsKey(MESSAGE_ID.toUpperCase())) { + populateError(httpResponse, "Message Id '" + MESSAGE_ID + + "' required on http header"); + return; + } else { + populateMDCAndResponseHeader(upperCaseHeaderMap, MESSAGE_ID, "messageId", + MusicUtil.getMessageIdRequired(), httpResponse); + } + + if (MusicUtil.getClientIdRequired() + && !upperCaseHeaderMap.containsKey(CLIENT_ID.toUpperCase())) { + populateError(httpResponse, "Client Id '" + CLIENT_ID + + "' required on http header"); + return; + } else { + populateMDCAndResponseHeader(upperCaseHeaderMap, CLIENT_ID, "clientId", + MusicUtil.getClientIdRequired(), httpResponse); + } + + } + + logger.info(EELFLoggerDelegate.securityLogger, + "In MusicLogginServletFilter doFilter. Header values validated sucessfully"); + + chain.doFilter(request, response); + } + + private void populateError(HttpServletResponse httpResponse, String errMsg) throws IOException { + AuthorizationError authError = new AuthorizationError(); + authError.setResponseCode(HttpServletResponse.SC_BAD_REQUEST); + authError.setResponseMessage(errMsg); + + byte[] responseToSend = restResponseBytes(authError); + httpResponse.setHeader("Content-Type", "application/json"); + + // ideally the http response code should be 200, as this is a biz validation + // failure. For now, keeping it consistent with other places. + httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + httpResponse.getOutputStream().write(responseToSend); + } + + private void populateMDCAndResponseHeader(Map headerMap, String idKey, String mdcKey, + boolean isRequired, HttpServletResponse httpResponse) { + + idKey = idKey.trim().toUpperCase(); + + // 1. setting the keys & value in MDC for future use 2.setting the values in + // http response header back to client. + if (isRequired && (headerMap.containsKey(idKey))) { + EELFLoggerDelegate.mdcPut(mdcKey, headerMap.get(idKey)); + httpResponse.addHeader(idKey, headerMap.get(idKey)); + } else { + // do nothing + } + } + + private Map getHeadersInfo(HttpServletRequest request) { + + Map map = new HashMap(); + + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String key = (String) headerNames.nextElement(); + String value = request.getHeader(key); + map.put(key, value); + } + + return map; + } + + private byte[] restResponseBytes(AuthorizationError eErrorResponse) throws IOException { + String serialized = new ObjectMapper().writeValueAsString(eErrorResponse); + return serialized.getBytes(); + } +} diff --git a/music-rest/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java b/music-rest/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java new file mode 100644 index 00000000..ab44fd6e --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +/** + * @author inam + * + */ +public class MusicAuthenticationException extends Exception { + + /** + * + */ + public MusicAuthenticationException() { + + } + + /** + * @param message + */ + public MusicAuthenticationException(String message) { + super(message); + + } + + /** + * @param cause + */ + public MusicAuthenticationException(Throwable cause) { + super(cause); + + } + + /** + * @param message + * @param cause + */ + public MusicAuthenticationException(String message, Throwable cause) { + super(message, cause); + + } + + /** + * @param message + * @param cause + * @param enableSuppression + * @param writableStackTrace + */ + public MusicAuthenticationException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + + } + +} diff --git a/music-rest/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java b/music-rest/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java new file mode 100644 index 00000000..c31fcf73 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java @@ -0,0 +1,56 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +import java.io.EOFException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.codehaus.jackson.map.exc.UnrecognizedPropertyException; +import org.onap.music.main.ResultType; +import org.onap.music.response.jsonobjects.JsonResponse; + +@Provider +public class MusicExceptionMapper implements ExceptionMapper { + @Override + public Response toResponse(Exception exception) { + if(exception instanceof UnrecognizedPropertyException) { + return Response.status(Response.Status.BAD_REQUEST). + entity(new JsonResponse(ResultType.FAILURE).setError("Unknown field :"+((UnrecognizedPropertyException) exception).getUnrecognizedPropertyName()).toMap()). + build(); + } else if(exception instanceof EOFException) { + return Response.status(Response.Status.BAD_REQUEST). + entity(new JsonResponse(ResultType.FAILURE).setError("Request body cannot be empty").toMap()). + build(); + } else if(exception instanceof NullPointerException) { + return Response.status(Response.Status.BAD_REQUEST). + entity(new JsonResponse(ResultType.FAILURE).setError("NullPointerException - Please check to make sure all inputs are valid.").toMap()). + build(); + } else { + return Response.status(Response.Status.BAD_REQUEST). + entity(new JsonResponse(ResultType.FAILURE).setError(exception.getMessage()).toMap()). + build(); + } + } +} diff --git a/music-rest/src/main/java/org/onap/music/main/PropertiesLoader.java b/music-rest/src/main/java/org/onap/music/main/PropertiesLoader.java new file mode 100644 index 00000000..8aac2672 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/main/PropertiesLoader.java @@ -0,0 +1,295 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.main; + +import java.util.Properties; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.stereotype.Component; + +@PropertySource(value = {"file:/opt/app/music/etc/music.properties", "classpath:/project.properties","file:/opt/app/music/etc/key.properties"}) +@Component +public class PropertiesLoader implements InitializingBean { + + @Value("${cassandra.host}") + public String cassandraHost; +/* + @Value("${music.ip}") + public String musicIp; +*/ + @Value("${debug}") + public String debug; + + @Value("${version}") + public String version; + + @Value("${build}") + public String build; + + @Value("${music.properties}") + public String musicProperties; + + @Value("${lock.lease.period}") + public String lockLeasePeriod; + + @Value("${cassandra.user}") + public String cassandraUser; + + @Value("${cassandra.password}") + public String cassandraPassword; + + @Value("${cassandra.port}") + public String cassandraPort; + + @Value("${cadi}") + public String isCadi; + + @Value("${keyspace.active}") + public String isKeyspaceActive; + + @Value("${retry.count}") + public String rertryCount; + + @Value("${transId.header.prefix}") + private String transIdPrefix; + + @Value("${conversation.header.prefix}") + private String conversationIdPrefix; + + @Value("${clientId.header.prefix}") + private String clientIdPrefix; + + @Value("${messageId.header.prefix}") + private String messageIdPrefix; + + @Value("${transId.header.required}") + private Boolean transIdRequired; + + @Value("${conversation.header.required}") + private Boolean conversationIdRequired; + + @Value("${clientId.header.required}") + private Boolean clientIdRequired; + + @Value("${messageId.header.required}") + private Boolean messageIdRequired; + + @Value("${music.aaf.ns}") + private String musicAafNs; + + @Value("${cipher.enc.key}") + private String cipherEncKey; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesLoader.class); + + @Bean + public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { + //return new PropertySourcesPlaceholderConfigurer(); + PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); + pspc.setIgnoreResourceNotFound(true); + pspc.setIgnoreUnresolvablePlaceholders(true); + return pspc; + } + + /** + * . + */ + public void loadProperties() { + if(cipherEncKey != null) { + MusicUtil.setCipherEncKey(cipherEncKey); + } + if (musicAafNs != null) { + MusicUtil.setMusicAafNs(musicAafNs); + } + if (cassandraPort != null && !cassandraPort.equals("${cassandra.port}")) { + MusicUtil.setCassandraPort(Integer.parseInt(cassandraPort)); + } + if (cassandraUser != null && !cassandraUser.equals("${cassandra.user}")) { + MusicUtil.setCassName(cassandraUser); + } + if (cassandraPassword != null && !cassandraPassword.equals("${cassandra.password}")) { + MusicUtil.setCassPwd(cassandraPassword); + } + if (debug != null && !debug.equals("${debug}")) { + MusicUtil.setDebug(Boolean.parseBoolean(debug)); + } + if (lockLeasePeriod != null && !lockLeasePeriod.equals("${lock.lease.period}")) { + MusicUtil.setDefaultLockLeasePeriod(Long.parseLong(lockLeasePeriod)); + } + if (musicProperties != null && !musicProperties.equals("${music.properties}")) { + MusicUtil.setMusicPropertiesFilePath(musicProperties); + } + if (cassandraHost != null && !cassandraHost.equals("${cassandra.host}")) { + MusicUtil.setMyCassaHost(cassandraHost); + } + if (version != null && !version.equals("${version}")) { + MusicUtil.setVersion(version); + } + if (build != null && !version.equals("${build}")) { + MusicUtil.setBuild(build); + } + if (isCadi != null && !isCadi.equals("${cadi}")) { + MusicUtil.setIsCadi(Boolean.parseBoolean(isCadi)); + } + if (rertryCount != null && !rertryCount.equals("${retry.count}")) { + MusicUtil.setRetryCount(Integer.parseInt(rertryCount)); + } + if (isKeyspaceActive != null && !isKeyspaceActive.equals("${keyspace.active}")) { + MusicUtil.setKeyspaceActive(Boolean.parseBoolean(isKeyspaceActive)); + } + if(transIdPrefix!=null) { + MusicUtil.setTransIdPrefix(transIdPrefix); + } + + if(conversationIdPrefix!=null) { + MusicUtil.setConversationIdPrefix(conversationIdPrefix); + } + + if(clientIdPrefix!=null) { + MusicUtil.setClientIdPrefix(clientIdPrefix); + } + + if(messageIdPrefix!=null) { + MusicUtil.setMessageIdPrefix(messageIdPrefix); + } + + if(transIdRequired!=null) { + MusicUtil.setTransIdRequired(transIdRequired); + } + + if(conversationIdRequired!=null) { + MusicUtil.setConversationIdRequired(conversationIdRequired); + } + + if(clientIdRequired!=null) { + MusicUtil.setClientIdRequired(clientIdRequired); + } + + if(messageIdRequired!=null) { + MusicUtil.setMessageIdRequired(messageIdRequired); + } + } + + public static void loadProperties(Properties properties) { + if (properties.getProperty("cassandra.host")!=null) { + MusicUtil.setMyCassaHost(properties.getProperty("cassandra.host")); + } + + if (properties.getProperty("cassandra.port")!=null) { + MusicUtil.setCassandraPort(Integer.parseInt(properties.getProperty("cassandra.port"))); + } + + if (properties.getProperty("cassandra.user")!=null) { + MusicUtil.setCassName(properties.getProperty("cassandra.user")); + } + + if (properties.getProperty("cassandra.password")!=null) { + MusicUtil.setCassPwd(properties.getProperty("cassandra.password")); + } + + if (properties.getProperty("music.properties")!=null) { + MusicUtil.setMusicPropertiesFilePath(properties.getProperty("music.properties")); + } + + if (properties.getProperty("debug")!=null) { + MusicUtil.setDebug(Boolean.parseBoolean(properties.getProperty("debug"))); + } + + if (properties.getProperty("version")!=null) { + MusicUtil.setVersion(properties.getProperty("version")); + } + + if (properties.getProperty("build")!=null) { + MusicUtil.setBuild(properties.getProperty("build")); + } + + if (properties.getProperty("lock.lease.period")!=null) { + MusicUtil.setDefaultLockLeasePeriod(Long.parseLong(properties.getProperty("lock.lease.period"))); + } + + if (properties.getProperty("cadi")!=null) { + MusicUtil.setIsCadi(Boolean.parseBoolean(properties.getProperty("cadi"))); + } + + if (properties.getProperty("keyspace.active")!=null) { + MusicUtil.setKeyspaceActive(Boolean.parseBoolean(properties.getProperty("keyspace.active"))); + } + + if (properties.getProperty("retry.count")!=null) { + MusicUtil.setRetryCount(Integer.parseInt(properties.getProperty("retry.count"))); + } + + if (properties.getProperty("transId.header.prefix")!=null) { + MusicUtil.setTransIdPrefix(properties.getProperty("transId.header.prefix")); + } + + if (properties.getProperty("conversation.header.prefix")!=null) { + MusicUtil.setConversationIdPrefix(properties.getProperty("conversation.header.prefix")); + } + + if (properties.getProperty("clientId.header.prefix")!=null) { + MusicUtil.setClientIdPrefix(properties.getProperty("clientId.header.prefix")); + } + + if (properties.getProperty("messageId.header.prefix")!=null) { + MusicUtil.setMessageIdPrefix(properties.getProperty("messageId.header.prefix")); + } + + if (properties.getProperty("transId.header.required")!=null) { + MusicUtil.setTransIdRequired(Boolean.parseBoolean(properties.getProperty("transId.header.required"))); + } + + if (properties.getProperty("conversation.header.required")!=null) { + MusicUtil.setConversationIdRequired(Boolean.parseBoolean(properties.getProperty("conversation.header.required"))); + } + + if (properties.getProperty("clientId.header.required")!=null) { + MusicUtil.setClientIdRequired(Boolean.parseBoolean(properties.getProperty("clientId.header.required"))); + } + + if (properties.getProperty("messageId.header.required")!=null) { + MusicUtil.setMessageIdRequired(Boolean.parseBoolean(properties.getProperty("messageId.header.required"))); + } + + if (properties.getProperty("music.aaf.ns")!=null) { + MusicUtil.setMusicAafNs(properties.getProperty("music.aaf.ns")); + } + + if (properties.getProperty("cipher.enc.key")!=null) { + MusicUtil.setCipherEncKey(properties.getProperty("cipher.enc.key")); + } + + } + + @Override + public void afterPropertiesSet() throws Exception { + // TODO Auto-generated method stub + + } + +} diff --git a/music-rest/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java b/music-rest/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java new file mode 100644 index 00000000..5ae49f5d --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java @@ -0,0 +1,322 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.response.jsonobjects; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; +import org.onap.music.main.ResultType; + + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "JsonResponse", description = "General Response JSON") +public class JsonResponse { + + /* Status is required */ + private ResultType status; + + /* Standard informational fields */ + private String error; + private String message; + + /* versioning */ + private String musicVersion; + private String musicBuild; + + /* Data Fields */ + private Map> dataResult; + + /* Locking fields */ + private String lock; + private LockStatus lockStatus; + private List lockHolders; + private String lockLease; + private boolean isLockHolders=false; + + /** + * Create a JSONLock Response + * Use setters to provide more information as in + * JsonLockResponse(ResultType.SUCCESS).setMessage("We did it").setLock(mylockname) + * @param status + */ + public JsonResponse(ResultType status) { + this.status = status; + } + + public boolean isLockHolders() { + return isLockHolders; + } + + public JsonResponse setisLockHolders(boolean isLockHolders) { + this.isLockHolders = isLockHolders; + return this; + } + + /** + * + * @return + */ + @ApiModelProperty(value = "Overall status of the response.", + allowableValues = "Success,Failure") + public ResultType getStatus() { + return status; + } + + /** + * + * @param status + */ + public JsonResponse setStatus(ResultType status) { + this.status = status; + return this; + } + + /** + * + * @return the error + */ + @ApiModelProperty(value = "Error value") + public String getError() { + return error; + } + + /** + * + * @param error + */ + public JsonResponse setError(String error) { + this.error = error; + return this; + } + + /** + * + * @return the message + */ + @ApiModelProperty(value = "Message value") + public String getMessage() { + return message; + } + + /** + * + * @param message + */ + public JsonResponse setMessage(String message) { + this.message = message; + return this; + } + + + /** + * . + * @return the music version + */ + public String getMusicVersion() { + return this.musicVersion; + } + + /** + * . + * @param version of music + * @return + */ + public JsonResponse setMusicVersion(String version) { + this.musicVersion = version; + return this; + } + + /** + * . + * @return the music version + */ + public String getMusicBuild() { + return this.musicBuild; + } + + /** + * . + * @param build of music + * @return + */ + public JsonResponse setMusicBuild(String build) { + this.musicBuild = build; + return this; + } + + + public Map> getDataResult() { + return this.dataResult; + } + + public JsonResponse setDataResult(Map> map) { + this.dataResult = map; + return this; + } + + /** + * + * @return + */ + public String getLock() { + return lock; + } + + /** + * + * @param lock + */ + public JsonResponse setLock(String lock) { + this.lock = lock; + return this; + } + + /** + * + * @return the lockStatus + */ + @ApiModelProperty(value = "Status of the lock") + public LockStatus getLockStatus() { + return lockStatus; + } + + /** + * + * @param lockStatus + */ + public JsonResponse setLockStatus(LockStatus lockStatus) { + this.lockStatus = lockStatus; + return this; + } + + /** + * + * + * @return the lockHolder + */ + @ApiModelProperty(value = "Holder of the Lock") + public List getLockHolder() { + return lockHolders; + } + + /** + * + * @param lockHolder + */ + public JsonResponse setLockHolder(String lockHolder) { + this.lockHolders = new ArrayList(); + this.lockHolders.add(lockHolder); + return this; + } + + public JsonResponse setLockHolder(List lockHolders) { + this.lockHolders = lockHolders; + return this; + } + + + /** + * @return the lockLease + */ + public String getLockLease() { + return lockLease; + } + + /** + * @param lockLease the lockLease to set + */ + public JsonResponse setLockLease(String lockLease) { + this.lockLease = lockLease; + return this; + } + + /** + * Convert to Map + * + * @return + */ + public Map toMap() { + Map fullMap = new HashMap<>(); + fullMap.put("status", status); + if (error != null && !"".equals(error)) { + fullMap.put("error", error); + } + if (message != null) { + fullMap.put("message", message); + } + + if (musicVersion != null) { + fullMap.put("version", musicVersion); + } + + if (musicBuild != null) { + fullMap.put("build", musicBuild); + } + + if (dataResult != null) { + fullMap.put("result", dataResult); + } + + if (lock != null) { + Map lockMap = new HashMap<>(); + if (lock != null) { + lockMap.put("lock", lock); + } + if (lockStatus != null) { + lockMap.put("lock-status", lockStatus); + } + if (lockHolders != null && !lockHolders.isEmpty()) { + if (lockHolders.size()==1 && !isLockHolders) { + //for backwards compatability + lockMap.put("lock-holder", lockHolders.get(0)); + } else { + lockMap.put("lock-holder", lockHolders); + } + } + if (lockLease != null) { + lockMap.put("lock-lease", lockLease); + } + fullMap.put("lock", lockMap); + } + + return fullMap; + } + + /** + * Convert to String + */ + @Override + public String toString() { + return "JsonLockResponse [status=" + status + ", error=" + error + ", message=" + message + + ", lock=" + lock + ", lockStatus=" + lockStatus + ", lockHolder=" + + lockHolders + "]"; + } + +} diff --git a/music-rest/src/main/java/org/onap/music/rest/Application.java b/music-rest/src/main/java/org/onap/music/rest/Application.java new file mode 100644 index 00000000..5375155b --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/rest/Application.java @@ -0,0 +1,79 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.rest; + +public class Application { + + private String application_name; + private String username; + private String password; + private String keyspace_name; + private boolean is_aaf; + private String uuid; + private boolean is_api; + + public String getApplication_name() { + return application_name; + } + public void setApplication_name(String application_name) { + this.application_name = application_name; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + public String getKeyspace_name() { + return keyspace_name; + } + public void setKeyspace_name(String keyspace_name) { + this.keyspace_name = keyspace_name; + } + public boolean isIs_aaf() { + return is_aaf; + } + public void setIs_aaf(boolean is_aaf) { + this.is_aaf = is_aaf; + } + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public boolean getIs_api() { + return is_api; + } + public void setIs_api(boolean is_api) { + this.is_api = is_api; + } + + +} diff --git a/music-rest/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/music-rest/src/main/java/org/onap/music/rest/RestMusicDataAPI.java new file mode 100755 index 00000000..756856d0 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -0,0 +1,1052 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Modifications Copyright (C) 2019 IBM + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.rest; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +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 javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; + +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonIndex; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.response.jsonobjects.JsonResponse; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.TableMetadata; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Example; +import io.swagger.annotations.ExampleProperty; + +/* Version 2 Class */ +//@Path("/v{version: [0-9]+}/keyspaces") +@Path("/v2/keyspaces") +@Api(value = "Data Api") +public class RestMusicDataAPI { + /* + * Header values for Versioning X-minorVersion *** - Used to request or communicate a MINOR + * version back from the client to the server, and from the server back to the client - This + * will be the MINOR version requested by the client, or the MINOR version of the last MAJOR + * version (if not specified by the client on the request) - Contains a single position value + * (e.g. if the full version is 1.24.5, X-minorVersion = "24") - Is optional for the client on + * request; however, this header should be provided if the client needs to take advantage of + * MINOR incremented version functionality - Is mandatory for the server on response + * + *** X-patchVersion *** - Used only to communicate a PATCH version in a response for + * troubleshooting purposes only, and will not be provided by the client on request - This will + * be the latest PATCH version of the MINOR requested by the client, or the latest PATCH version + * of the MAJOR (if not specified by the client on the request) - Contains a single position + * value (e.g. if the full version is 1.24.5, X-patchVersion = "5") - Is mandatory for the + * server on response (CURRENTLY NOT USED) + * + *** X-latestVersion *** - Used only to communicate an API's latest version - Is mandatory for the + * server on response, and shall include the entire version of the API (e.g. if the full version + * is 1.24.5, X-latestVersion = "1.24.5") - Used in the response to inform clients that they are + * not using the latest version of the API (CURRENTLY NOT USED) + * + */ + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); + private static final String XMINORVERSION = "X-minorVersion"; + private static final String XPATCHVERSION = "X-patchVersion"; + private static final String NS = "ns"; + private static final String VERSION = "v2"; + private static final String PARAMETER_ERROR = "Missing Row Identifier. Please provide the parameter of key=value for the row being selected."; + + + private class RowIdentifier { + public String primarKeyValue; + public StringBuilder rowIdString; + @SuppressWarnings("unused") + public PreparedQueryObject queryObject; // the string with all the row + // identifiers separated by AND + + public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, + PreparedQueryObject queryObject) { + this.primarKeyValue = primaryKeyValue; + this.rowIdString = rowIdString; + this.queryObject = queryObject; + } + } + + + /** + * Create Keyspace REST + * + * @param kspObject + * @param keyspaceName + * @return + * @throws Exception + */ + @POST + @Path("/{name}") + @ApiOperation(value = "Create Keyspace", response = String.class, + notes = "This API will not work if MUSIC properties has keyspace.active=false ") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"message\" : \"Keysapce Created\"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response createKeySpace( + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, + JsonKeySpace kspObject, + @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); + logger.info(EELFLoggerDelegate.applicationLogger,"In Create Keyspace " + keyspaceName); + if (MusicUtil.isKeyspaceActive() ) { + logger.info(EELFLoggerDelegate.applicationLogger,"Creating Keyspace " + keyspaceName); + + if(kspObject == null || kspObject.getReplicationInfo() == null) { + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } + ResultType result = ResultType.FAILURE; + try { + kspObject.setKeyspaceName(keyspaceName); + result = MusicCore.createKeyspace(kspObject, MusicUtil.EVENTUAL); + logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result); + } catch ( MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.QUERYERROR + ,ErrorSeverity.WARN, ErrorTypes.QUERYERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } catch ( MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build(); + } else { + String vError = "Keyspace Creation has been turned off. Contact DBA to create the keyspace or set keyspace.active to true."; + logger.info(EELFLoggerDelegate.applicationLogger,vError); + logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + + } + + /** + * + * @param kspObject + * @param keyspaceName + * @return + * @throws Exception + */ + @DELETE + @Path("/{name}") + @ApiOperation(value = "Delete Keyspace", response = String.class, + notes = "This API will not work if MUSIC properties has keyspace.active=false ") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"message\" : \"Keysapce Deleted\"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response dropKeySpace( + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName); + if (MusicUtil.isKeyspaceActive()) { + String consistency = MusicUtil.EVENTUAL;// for now this needs only + String droperror = "Error Deleteing Keyspace " + keyspaceName; + JsonKeySpace kspObject = new JsonKeySpace(); + kspObject.setKeyspaceName(keyspaceName); + try{ + ResultType result = MusicCore.dropKeyspace(kspObject, consistency); + if ( result.equals(ResultType.FAILURE) ) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError(droperror).toMap()).build(); + } + } catch ( MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.QUERYERROR + ,ErrorSeverity.WARN, ErrorTypes.QUERYERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(droperror + " " + ex.getMessage()).toMap()).build(); + } catch ( MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR + ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(droperror + " " + ex.getMessage()).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build(); + } else { + String vError = "Keyspace deletion has been turned off. Contact DBA to delete the keyspace or set keyspace.active to true."; + logger.info(EELFLoggerDelegate.applicationLogger,vError); + logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param tableObj + * @param version + * @param keyspace + * @param tablename + * @param headers + * @return + * @throws Exception - + */ + @POST + @Path("/{keyspace: .*}/tables/{tablename: .*}") + @ApiOperation(value = "Create Table", response = String.class, + notes = "Create a table with the required json in the body.") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"message\" : \"Tablename Created under keyspace \"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response createTable( + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonTable tableObj, + @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if ( null == tableObj ) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } + if(keyspace == null || keyspace.isEmpty() || tablename == null || tablename.isEmpty()){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("One or more path parameters are not set, please check and try again." + + "Parameter values: keyspace='" + keyspace + "' tablename='" + tablename + "'") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + String consistency = MusicUtil.EVENTUAL; + // for now this needs only eventual consistency + ResultType result = ResultType.FAILURE; + try { + tableObj.setKeyspaceName(keyspace); + tableObj.setTableName(tablename); + result = MusicCore.createTable(tableObj, consistency); + } catch (MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + if ( result.equals(ResultType.FAILURE) ) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename.trim() + " Created under keyspace " + keyspace.trim()).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param keyspace + * @param tablename + * @param fieldName + * @param info + * @throws Exception + */ + @POST + @Path("/{keyspace: .*}/tables/{tablename: .*}/index/{field: .*}") + @ApiOperation(value = "Create Index", response = String.class, + notes = "An index provides a means to access data using attributes " + + "other than the partition key. The benefit is fast, efficient lookup " + + "of data matching a given condition.") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"message\" : \"Index Created on ..\"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Unknown Error in create index.\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response createIndex( + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename, + @ApiParam(value = "Field Name",required = true) @PathParam("field") String fieldName, + @Context UriInfo info) throws Exception { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if ((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty()) || (fieldName == null || fieldName.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + MultivaluedMap rowParams = info.getQueryParameters(); + String indexName = ""; + if (rowParams.getFirst("index_name") != null) + indexName = rowParams.getFirst("index_name"); + + JsonIndex jsonIndexObject = new JsonIndex(indexName, keyspace, tablename, fieldName); + + ResultType result = ResultType.FAILURE; + try { + result = MusicCore.createIndex(jsonIndexObject, MusicUtil.EVENTUAL); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .CRITICAL, ErrorTypes.GENERALSERVICEERROR, ex); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + if ( result.equals(ResultType.SUCCESS) ) { + return response.status(Status.OK).entity(new JsonResponse(result).setMessage("Index Created on " + keyspace+"."+tablename+"."+fieldName).toMap()).build(); + } else { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param insObj + * @param keyspace + * @param tablename + * @return + * @throws Exception + */ + @POST + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") + @ApiOperation(value = "Insert Into Table", response = String.class, + notes = "Insert into table with data in json body.") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"message\" : \"Insert Successful\"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure - Generic",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response insertIntoTable( + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonInsert insObj, + @ApiParam(value = "Keyspace Name", + required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", + required = true) @PathParam("tablename") String tablename) { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if ( null == insObj ) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace","(" + keyspace + ")"); + ReturnType result = null; + String consistency = insObj.getConsistencyInfo().get("type"); + try { + insObj.setKeyspaceName(keyspace); + insObj.setTableName(tablename); + if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + String lockId = insObj.getConsistencyInfo().get("lockId"); + if(lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); + } + } + result = MusicCore.insertIntoTable(insObj); + }catch (MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + }catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + if (result==null) { + logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); + }else if(result.getResult() == ResultType.FAILURE) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result.getResult()).setError(result.getMessage()).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(result.getResult()).setMessage("Insert Successful").toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param insObj + * @param keyspace + * @param tablename + * @param info + * @return + * @throws MusicServiceException + * @throws MusicQueryException + * @throws Exception + */ + @PUT + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") + @ApiOperation(value = "Update Table", response = String.class, + notes = "Update the table with the data in the JSON body.") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response updateTable( + @ApiParam(value = "Major Version", + required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", + required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version", + required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonUpdate updateObj, + @ApiParam(value = "Keyspace Name", + required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", + required = true) @PathParam("tablename") String tablename, + @Context UriInfo info) throws MusicQueryException, MusicServiceException { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if ( null == updateObj ) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + long startTime = System.currentTimeMillis(); + String operationId = UUID.randomUUID().toString(); // just for infoging + // purposes. + String consistency = updateObj.getConsistencyInfo().get("type"); + ReturnType operationResult = null; + logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency + + " update-" + operationId + "-------------------------"); + + updateObj.setKeyspaceName(keyspace); + updateObj.setTableName(tablename); + + try { + if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + String lockId = updateObj.getConsistencyInfo().get("lockId"); + if(lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); + } + } + operationResult = MusicCore.updateTable(updateObj,info.getQueryParameters()); + }catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, + ErrorTypes.GENERALSERVICEERROR, e); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + }catch (MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + }catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + long actualUpdateCompletionTime = System.currentTimeMillis(); + + long endTime = System.currentTimeMillis(); + long jsonParseCompletionTime = System.currentTimeMillis(); + String timingString = "Time taken in ms for Music " + consistency + " update-" + operationId + + ":" + "|total operation time:" + (endTime - startTime) + + "|json parsing time:" + (jsonParseCompletionTime - startTime) + + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime) + + "|"; + + if (operationResult != null && operationResult.getTimingInfo() != null) { + String lockManagementTime = operationResult.getTimingInfo(); + timingString = timingString + lockManagementTime; + } + logger.info(EELFLoggerDelegate.applicationLogger, timingString); + + if (operationResult==null) { + logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); + } + if ( operationResult.getResult() == ResultType.SUCCESS ) { + return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build(); + } else { + logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(operationResult.getResult()).setError(operationResult.getMessage()).toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param delObj + * @param keyspace + * @param tablename + * @param info + * @return + * @throws MusicServiceException + * @throws MusicQueryException + * @throws Exception + */ + @DELETE + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") + @ApiOperation(value = "Delete From table", response = String.class, + notes = "Delete from a table, the row or parts of a row. Based on JSON body.") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response deleteFromTable( + @ApiParam(value = "Major Version", + required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", + required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version", + required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonDelete delObj, + @ApiParam(value = "Keyspace Name", + required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", + required = true) @PathParam("tablename") String tablename, + @Context UriInfo info) throws MusicQueryException, MusicServiceException { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + if(delObj == null) { + logger.error(EELFLoggerDelegate.errorLogger,ResultType.BODYMISSING.getResult(), AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } + ReturnType operationResult = null; + String consistency = delObj.getConsistencyInfo().get("type"); + delObj.setKeyspaceName(keyspace); + delObj.setTableName(tablename); + try { + if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + String lockId = delObj.getConsistencyInfo().get("lockId"); + if(lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); + } + } + + operationResult = MusicCore.deleteFromTable(delObj,info.getQueryParameters()); + } catch (MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Unable to perform Delete operation. Exception from music").toMap()).build(); + } + if (operationResult==null) { + logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); + } + if (operationResult.getResult().equals(ResultType.SUCCESS)) { + return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build(); + } else { + logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param tabObj + * @param keyspace + * @param tablename + * @throws Exception + */ + @DELETE + @Path("/{keyspace: .*}/tables/{tablename: .*}") + @ApiOperation(value = "Drop Table", response = String.class) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response dropTable( + @ApiParam(value = "Major Version", + required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", + required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version", + required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Keyspace Name", + required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", + required = true) @PathParam("tablename") String tablename) throws Exception { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + JsonTable jsonTable = new JsonTable(); + jsonTable.setKeyspaceName(keyspace); + jsonTable.setTableName(tablename); + try { + return response.status(Status.OK).entity(new JsonResponse(MusicCore.dropTable(jsonTable, MusicUtil.EVENTUAL)).toMap()).build(); + } catch (MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.WARN + , ErrorTypes.QUERYERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN + , ErrorTypes.GENERALSERVICEERROR,ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param selObj + * @param keyspace + * @param tablename + * @param info + * @return + */ + @PUT + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows/criticalget") + @ApiOperation(value = "** Depreciated ** - Select Critical", response = Map.class, + notes = "This API is depreciated in favor of the regular select api.\n" + + "Avaliable to use with the select api by providing a minorVersion of 1 " + + "and patchVersion of 0.\n" + + "Critical Get requires parameter rowId=value and consistency in order to work.\n" + + "It will fail if either are missing.") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"result\":{\"row 0\":{\"address\":" + + "{\"city\":\"Someplace\",\"street\":\"1 Some way\"}," + + "\"emp_salary\":50,\"emp_name\":\"tom\",\"emp_id\":" + + "\"cfd66ccc-d857-4e90-b1e5-df98a3d40cd6\"}},\"status\":\"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response selectCritical( + @ApiParam(value = "Major Version", + required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",example = "0", + required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",example = "0", + required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonInsert selObj, + @ApiParam(value = "Keyspace Name", + required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", + required = true) @PathParam("tablename") String tablename, + @Context UriInfo info) throws Exception { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspace + " )"); + if (info.getQueryParameters().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger,RestMusicDataAPI.PARAMETER_ERROR, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes + .GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(RestMusicDataAPI.PARAMETER_ERROR).toMap()).build(); + } + if (selObj == null || selObj.getConsistencyInfo().isEmpty()) { + String error = " Missing Body or Consistency type."; + logger.error(EELFLoggerDelegate.errorLogger,ResultType.BODYMISSING.getResult() + error, AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult() + error).toMap()).build(); + } + ResultSet results = null; + String consistency = selObj.getConsistencyInfo().get("type"); + String lockId = selObj.getConsistencyInfo().get("lockId"); + selObj.setKeyspaceName(keyspace); + selObj.setTableName(tablename); + try { + if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + if(lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); + } + } + results = MusicCore.selectCritical(selObj, info.getQueryParameters()); + }catch (MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + + }catch(Exception ex) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + + if(results!=null && results.getAvailableWithoutFetching() >0) { + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * This API will replace the original select and provide a single API fro select and critical. + * The idea is to depreciate the older api of criticalGet and use a single API. + * + * @param selObj + * @param keyspace + * @param tablename + * @param info + * @return + */ + @GET + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") + @ApiOperation(value = "Select", response = Map.class, + notes = "This has 2 versions: if minorVersion and patchVersion is null or 0, this will be a Eventual Select only.\n" + + "If minorVersion is 1 and patchVersion is 0, this will act like the Critical Select \n" + + "Critical Get requires parameter rowId=value and consistency in order to work.\n" + + "If parameters are missing or consistency information is missing. An eventual select will be preformed.") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"result\":{\"row 0\":{\"address\":" + + "{\"city\":\"Someplace\",\"street\":\"1 Some way\"}," + + "\"emp_salary\":50,\"emp_name\":\"tom\",\"emp_id\":" + + "\"cfd66ccc-d857-4e90-b1e5-df98a3d40cd6\"}},\"status\":\"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response selectWithCritical( + @ApiParam(value = "Major Version",example = "v2", + required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",example = "1", + required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",example = "0", + required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false,hidden = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonInsert selObj, + @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, + @Context UriInfo info) throws Exception { + if ((minorVersion != null && patchVersion != null) && + (Integer.parseInt(minorVersion) == 1 && Integer.parseInt(patchVersion) == 0) && + (!(null == selObj) && !selObj.getConsistencyInfo().isEmpty())) { + return selectCritical(version, minorVersion, patchVersion, aid, ns, authorization, selObj, keyspace, tablename, info); + } else { + return select(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename, info); + } + } + + /** + * + * @param keyspace + * @param tablename + * @param info + * @return + * @throws Exception + */ + private Response select( + String version,String minorVersion,String patchVersion, + String aid,String ns,String authorization,String keyspace, + String tablename,UriInfo info) throws Exception { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspace + " ) "); + try { + JsonSelect jsonSelect = new JsonSelect(); + jsonSelect.setKeyspaceName(keyspace); + jsonSelect.setTableName(tablename); + ResultSet results = MusicCore.select(jsonSelect, info.getQueryParameters()); + if(results.getAvailableWithoutFetching() >0) { + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).setError("No data found").toMap()).build(); + } catch (MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, + ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param keyspace + * @param tablename + * @param info + * @param limit + * @return + * @throws MusicServiceException + */ + public PreparedQueryObject selectSpecificQuery(String keyspace, + String tablename, UriInfo info, int limit) + throws MusicServiceException { + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder rowIdString = getRowIdentifier(keyspace, + tablename,info.getQueryParameters(),queryObject).rowIdString; + queryObject.appendQueryString( + "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowIdString); + if (limit != -1) { + queryObject.appendQueryString(" LIMIT " + limit); + } + queryObject.appendQueryString(";"); + return queryObject; + } + + /** + * + * @param keyspace + * @param tablename + * @param rowParams + * @param queryObject + * @return + * @throws MusicServiceException + */ + private RowIdentifier getRowIdentifier(String keyspace, String tablename, + MultivaluedMap rowParams, PreparedQueryObject queryObject) + throws MusicServiceException { + StringBuilder rowSpec = new StringBuilder(); + int counter = 0; + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + if (tableInfo == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + throw new MusicServiceException( + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + } + StringBuilder primaryKey = new StringBuilder(); + for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { + String keyName = entry.getKey(); + List valueList = entry.getValue(); + String indValue = valueList.get(0); + DataType colType = null; + Object formattedValue = null; + try { + colType = tableInfo.getColumn(entry.getKey()).getType(); + formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e); + } + if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { + primaryKey.append(indValue); + } + rowSpec.append(keyName + "= ?"); + queryObject.addValue(formattedValue); + if (counter != rowParams.size() - 1) { + rowSpec.append(" AND "); + } + counter = counter + 1; + } + return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); + } +} diff --git a/music-rest/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java b/music-rest/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java new file mode 100644 index 00000000..eef3aa3a --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java @@ -0,0 +1,124 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * + * Modifications Copyright (C) 2018 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.rest; + +import java.util.HashMap; +/** + * @author inam + * + */ +import java.util.Map; + +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 javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + + +import org.onap.music.eelf.healthcheck.MusicHealthCheck; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.main.MusicUtil; + +import com.datastax.driver.core.ConsistencyLevel; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + + + + +@Path("/v2/service") +@Api(value="Healthcheck Api") +public class RestMusicHealthCheckAPI { + + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + private static final String ACTIVE_STATUS = "ACTIVE"; + private static final String INVALID_STATUS = "INVALID"; + private static final String INACTIVE_STATUS = "INACTIVE"; + private static final String INVALID_MESSAGE = "Consistency level is invalid..."; + private static final String INACTIVE_MESSAGE = "One or more nodes in the Cluster is/are down or not responding."; + private static final String ACTIVE_MESSAGE = "Cassandra Running and Listening to requests"; + private static final String STATUS_KEY = "status"; + private static final String MESSAGE_KEY = "message"; + + @GET + @Path("/pingCassandra/{consistency}") + @ApiOperation(value = "Get Health Status", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Response cassandraStatus( + @Context HttpServletResponse response, + @ApiParam(value = "Consistency level",required = true) + @PathParam("consistency") String consistency) { + logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra"); + + Map resultMap = new HashMap<>(); + if(ConsistencyLevel.valueOf(consistency) == null) { + resultMap.put(STATUS_KEY,INVALID_STATUS); + resultMap.put(MESSAGE_KEY, INVALID_MESSAGE); + resultMap.put(INVALID_STATUS, INVALID_STATUS); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + MusicHealthCheck cassHealthCheck = new MusicHealthCheck(); + String status = cassHealthCheck.getCassandraStatus(consistency); + if(status.equals(ACTIVE_STATUS)) { + resultMap.put(STATUS_KEY,ACTIVE_STATUS); + resultMap.put(MESSAGE_KEY, ACTIVE_MESSAGE); + resultMap.put(ACTIVE_STATUS, ACTIVE_MESSAGE); + return Response.status(Status.OK).entity(resultMap).build(); + } else { + resultMap.put(STATUS_KEY,INACTIVE_STATUS); + resultMap.put(MESSAGE_KEY, INACTIVE_MESSAGE); + resultMap.put(INACTIVE_STATUS, INACTIVE_MESSAGE); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + } + + @GET + @Path("/musicHealthCheck") + @ApiOperation(value = "Get Health Status", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Response musicHealthCheck() { + logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for Health Check status for MUSIC"); + Map resultMap = new HashMap<>(); + MusicHealthCheck healthCheck = new MusicHealthCheck(); + + String status = healthCheck.getCassandraStatus(ConsistencyLevel.ANY.toString()); + if(status.equals(ACTIVE_STATUS)) { + resultMap.put("Cassandra", "Active"); + } else { + resultMap.put("Cassandra", "Inactive"); + } + resultMap.put("MUSIC", "Active"); + return Response.status(Status.OK).entity(resultMap).build(); + } + +} diff --git a/music-rest/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/music-rest/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java new file mode 100644 index 00000000..321e2561 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -0,0 +1,632 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.rest; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +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.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.jsonobjects.JsonLeasedLock; +import org.onap.music.datastore.jsonobjects.JsonLock; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.response.jsonobjects.JsonResponse; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Example; +import io.swagger.annotations.ExampleProperty; + + +@Path("/v2/locks/") +@Api(value="Locking Api") +public class RestMusicLocksAPI { + + private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicLocksAPI.class); + private static final String XMINORVERSION = "X-minorVersion"; + private static final String XPATCHVERSION = "X-patchVersion"; + private static final String VERSION = "v2"; + + /** + * Puts the requesting process in the q for this lock. The corresponding + * node will be created if it did not already exist + * + * @param lockName + * @return + * @throws Exception + */ + @POST + @Path("/create/{lockname}") + @ApiOperation(value = "Create and Acquire a Lock Id for a single row.", + notes = "Creates and Acquires a Lock Id for a specific Row in a table based on the key of that row.\n" + + " The corresponding lock will be created if it did not already exist." + + " Lock Name also the Lock is in the form of keyspaceName.tableName.rowId.\n" + + " The Response will be in the form of \"$kesypaceName.tableName.rowId$lockRef\" " + + " where the lockRef is a integer representing the Lock Name buffered by \"$\" " + + " followed by the lock number. This term for " + + " this response is a lockId and it will be used in other /locks API calls where a " + + " lockId is required. If just a lock is required then the form that would be " + + " the original lockname(without the buffered \"$\").", + response = Map.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Unable to aquire lock\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response createLockReference( + @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + JsonLock lockObject, + @ApiParam(value = "Lock Owner", required = false) @HeaderParam("owner") String owner, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockName); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + + //default lock type is write, as this is always semantically safe + LockType locktype = LockType.WRITE; + if (lockObject!=null && lockObject.getLocktype()!=null) { + locktype = lockObject.getLocktype(); + } + String lockId; + try { + lockId= MusicCore.createLockReference(lockName, locktype, owner); + } catch (MusicLockingException e) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } + + if (lockId == null) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.LOCKINGERROR ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Lock Id is null").toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setLock(lockId).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * Checks if the node is in the top of the queue and hence acquires the lock + * + * @param lockId + * @return + * @throws Exception + */ + @GET + @Path("/acquire/{lockId}") + @ApiOperation(value = "Aquire Lock Id ", + notes = "Checks if the node is in the top of the queue and hence acquires the lock", + response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," + + "\"message\" : \" is the lock holder for the key\"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Unable to aquire lock\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response accquireLock( + @ApiParam(value="Lock Id",required=true) @PathParam("lockId") String lockId, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockId); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + try { + String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); + ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId); + if ( lockStatus.getResult().equals(ResultType.SUCCESS)) { + response.status(Status.OK); + } else { + response.status(Status.BAD_REQUEST); + } + return response.entity(new JsonResponse(lockStatus.getResult()).setLock(lockId).setMessage(lockStatus.getMessage()).toMap()).build(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, + ErrorTypes.LOCKINGERROR, e); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + + @POST + @Path("/acquire-with-lease/{lockId}") + @ApiOperation( + hidden = false, + value = " ** DEPRECATED ** - Aquire Lock with Lease", + notes = "Acquire the lock with a lease, where lease period is in Milliseconds.\n" + + "This will ensure that a lock will expire in set milliseconds.\n" + + "This is no longer available after v3.2.0", + response = Map.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"," + + "\"lock-lease\" : \"6000\"}," + + "\"message\" : \" is the lock holder for the key\"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Unable to aquire lock\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + @Deprecated + public Response accquireLockWithLease( + JsonLeasedLock lockObj, + @ApiParam(value="Lock Id",required=true) @PathParam("lockId") String lockId, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockId); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); + ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()); + if ( lockLeaseStatus.getResult().equals(ResultType.SUCCESS)) { + response.status(Status.OK); + } else { + response.status(Status.BAD_REQUEST); + } + return response.entity(new JsonResponse(lockLeaseStatus.getResult()).setLock(lockName) + .setMessage(lockLeaseStatus.getMessage()) + .setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + + + } + + + @GET + @Path("/enquire/{lockname}") + @ApiOperation(value = "Get the top of the lock queue", + notes = "Gets the current single lockholder at top of lock queue", + response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"lock\" : {\"lock\" : \"keyspace.table.rowId\"," + + "\"lock-holder\" : \"$tomtest.employees.tom$\"}}," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Error Message\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response enquireLock( + @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockName); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + String who = MusicCore.whoseTurnIsIt(lockName); + ResultType status = ResultType.SUCCESS; + String error = ""; + if ( who == null ) { + status = ResultType.FAILURE; + error = "There was a problem getting the lock holder"; + logger.error(EELFLoggerDelegate.errorLogger,"There was a problem getting the lock holder", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + @GET + @Path("/holders/{lockname}") + @ApiOperation(value = "Get Lock Holders", + notes = "Gets the current Lock Holders.\n" + + "Will return an array of READ Lock References.", + response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"lock\" : {\"lock\" : \"keyspace.table.rowId\"," + + "\"lock-holder\" : [\"$keyspace.table.rowId$\",\"$keyspace.table.rowId$\"]}}," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Error message\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response currentLockHolder(@ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam("ns") String ns) { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockName); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, + ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity( + new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()) + .build(); + } + String keyspaceName = (String) resultMap.get("keyspace"); + List who = MusicCore.getCurrentLockHolders(lockName); + ResultType status = ResultType.SUCCESS; + String error = ""; + if (who == null || who.isEmpty()) { + status = ResultType.FAILURE; + error = (who !=null && who.isEmpty()) ? "No lock holders for the key":"There was a problem getting the lock holder"; + logger.error(EELFLoggerDelegate.errorLogger, "There was a problem getting the lock holder", + AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()) + .build(); + } + return response.status(Status.OK) + .entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).setisLockHolders(true).toMap()) + .build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + + @GET + @Path("/{lockname}") + @ApiOperation(value = "Lock State", + notes = "Returns current Lock State and Holder.", + response = Map.class,hidden = true) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," + + "\"message\" : \" is the lock holder for the key\"," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Unable to aquire lock\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response currentLockState( + @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam("ns") String ns) { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockName); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); + String who = MusicCore.whoseTurnIsIt(lockName); + ResultType status = ResultType.SUCCESS; + String error = ""; + if ( who == null ) { + status = ResultType.FAILURE; + error = "There was a problem getting the lock holder"; + logger.error(EELFLoggerDelegate.errorLogger,"There was a problem getting the lock holder", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + + } + + /** + * + * deletes the process from the lock queue + * + * @param lockId + * @throws Exception + */ + @DELETE + @Path("/release/{lockreference}") + @ApiOperation(value = "Release Lock", + notes = "Releases the lock from the lock queue.", + response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success - UNLOCKED = Lock Removed.",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," + + "\"lock-status\" : \"UNLOCKED\"}," + + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Unable to aquire lock\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response unLock(@PathParam("lockreference") String lockId, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockId); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); + boolean voluntaryRelease = true; + MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease); + if(mls.getErrorMessage() != null) { + resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage()); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + Map returnMap = null; + if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) { + returnMap = new JsonResponse(ResultType.SUCCESS).setLock(lockId) + .setLockStatus(mls.getLockStatus()).toMap(); + response.status(Status.OK); + } + if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.LOCKINGERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + returnMap = new JsonResponse(ResultType.FAILURE).setLock(lockId) + .setLockStatus(mls.getLockStatus()).toMap(); + response.status(Status.BAD_REQUEST); + } + return response.entity(returnMap).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + /** + * + * @param lockName + * @throws Exception + */ + @Deprecated + @DELETE + @Path("/delete/{lockname}") + @ApiOperation( + hidden = true, + value = "-DEPRECATED- Delete Lock", response = Map.class, + notes = "-DEPRECATED- Delete the lock.") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Error Message if any\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response deleteLock(@PathParam("lockname") String lockName, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Application namespace", + required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockName); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + try{ + MusicCore.destroyLockRef(lockName); + }catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } + + + /** + * Puts the requesting process in the q for this lock. The corresponding + * node will be created if it did not already exist + * + * @param lockName + * @return + * @throws Exception + */ + @POST + @Path("/promote/{lockname}") + @ApiOperation(value = "Attempt to promote the lock for a single row.", + response = Map.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value={ + @ApiResponse(code=200, message = "Success",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "\"status\" : \"SUCCESS\"}") + })), + @ApiResponse(code=400, message = "Failure",examples = @Example( value = { + @ExampleProperty(mediaType="application/json",value = + "{\"error\" : \"Unable to promote lock\"," + + "\"status\" : \"FAILURE\"}") + })) + }) + public Response promoteLock( + @ApiParam(value="Lock Id",required=true) @PathParam("lockId") String lockId, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) + throws Exception { + try { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map resultMap = MusicCore.validateLock(lockId); + if (resultMap.containsKey("Error")) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + } + + String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + + try { + ReturnType lockStatus = MusicCore.promoteLock(lockId); + if ( lockStatus.getResult().equals(ResultType.SUCCESS)) { + response.status(Status.OK); + } else { + response.status(Status.BAD_REQUEST); + } + return response.entity(new JsonResponse(lockStatus.getResult()).setLock(lockId).setMessage(lockStatus.getMessage()).toMap()).build(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, + ErrorTypes.LOCKINGERROR, e); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Unable to promote lock").toMap()).build(); + } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } + } +} diff --git a/music-rest/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/music-rest/src/main/java/org/onap/music/rest/RestMusicQAPI.java new file mode 100755 index 00000000..4def0e45 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -0,0 +1,441 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (C) 2019 IBM. + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.rest; + +import java.util.Map; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +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 javax.ws.rs.core.UriInfo; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.eelf.logging.EELFLoggerDelegate; + +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.apache.commons.lang3.StringUtils; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import com.datastax.driver.core.ResultSet; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.response.jsonobjects.JsonResponse; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +@Path("/v2/priorityq/") +@Api(value = "Q Api",hidden = true) +public class RestMusicQAPI { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class); + + + /** + * + * @param tableObj + * @param keyspace + * @param tablename + * @throws Exception + */ + + @POST + @Path("/keyspaces/{keyspace}/{qname}") // qname same as tablename + @ApiOperation(value = "Create Q", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response createQ( + @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, + @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonTable tableObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + + Map fields = tableObj.getFields(); + if (fields == null) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ/Required table fields are empty or not set").toMap()) + .build(); + } + + String primaryKey = tableObj.getPrimaryKey(); + String partitionKey = tableObj.getPartitionKey(); + String clusteringKey = tableObj.getClusteringKey(); + String filteringKey = tableObj.getFilteringKey(); + String clusteringOrder = tableObj.getClusteringOrder(); + + if(primaryKey == null) { + primaryKey = tableObj.getFields().get("PRIMARY KEY"); + } + + if ((primaryKey == null) && (partitionKey == null)) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Partition key cannot be empty").toMap()) + .build(); + } + + if ((primaryKey == null) && (clusteringKey == null)) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Clustering key cannot be empty").toMap()) + .build(); + } + + if (clusteringOrder == null) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Clustering Order cannot be empty").toMap()) + .build(); + } + + if ((primaryKey!=null) && (partitionKey == null)) { + primaryKey = primaryKey.trim(); + int count1 = StringUtils.countMatches(primaryKey,')'); + int count2 = StringUtils.countMatches(primaryKey,'('); + if (count1 != count2) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ Error: primary key '(' and ')' do not match, primary key=" + primaryKey) + .toMap()).build(); + } + + if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) ) { + if (primaryKey.contains(",") ) { + partitionKey= primaryKey.substring(0,primaryKey.indexOf(',')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + clusteringKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index + clusteringKey=clusteringKey.replaceAll("[)]+", ""); + } else { + partitionKey=primaryKey; + partitionKey=partitionKey.replaceAll("[\\)]+",""); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + clusteringKey=""; + } + } else { + partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + partitionKey = partitionKey.trim(); + clusteringKey= primaryKey.substring(primaryKey.indexOf(')')); + clusteringKey=clusteringKey.replaceAll("[\\(]+",""); + clusteringKey=clusteringKey.replaceAll("[\\)]+",""); + clusteringKey = clusteringKey.trim(); + if (clusteringKey.indexOf(',') == 0) clusteringKey=clusteringKey.substring(1); + clusteringKey = clusteringKey.trim(); + if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),) + } + } + + if (partitionKey.trim().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Partition key cannot be empty").toMap()) + .build(); + } + + if (clusteringKey.trim().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Clustering key cannot be empty").toMap()) + .build(); + } + + if((filteringKey != null) && (filteringKey.equalsIgnoreCase(partitionKey))) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Filtering key cannot be same as Partition Key").toMap()) + .build(); + } + + return new RestMusicDataAPI().createTable(version, minorVersion, patchVersion, aid, ns, authorization, tableObj, keyspace, tablename); + } + + /** + * + * @param insObj + * @param keyspace + * @param tablename + * @throws Exception + */ + @POST + @Path("/keyspaces/{keyspace}/{qname}/rows") + @ApiOperation(value = "", response = Void.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + // public Map insertIntoQ( + public Response insertIntoQ( + @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, + @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonInsert insObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) { + + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (insObj.getValues().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Required HTTP Request body is missing.").toMap()).build(); + } + return new RestMusicDataAPI().insertIntoTable(version, minorVersion, patchVersion, aid, ns, + authorization, insObj, keyspace, tablename); + } + + /** + * + * @param updateObj + * @param keyspace + * @param tablename + * @param info + * @return + * @throws Exception + */ + @PUT + @Path("/keyspaces/{keyspace}/{qname}/rows") + @ApiOperation(value = "updateQ", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response updateQ( + @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, + @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonUpdate updateObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws MusicServiceException, MusicQueryException { + + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (updateObj.getValues().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Required HTTP Request body is missing. JsonUpdate updateObj.getValues() is empty. ") + .toMap()) + .build(); + } + return new RestMusicDataAPI().updateTable(version, minorVersion, patchVersion, aid, ns, + authorization,updateObj, keyspace, tablename, info); + } + + /** + * + * @param delObj + * @param keyspace + * @param tablename + * @param info + * + * @return + * @throws Exception + */ + + @DELETE + @Path("/keyspaces/{keyspace}/{qname}/rows") + @ApiOperation(value = "deleteQ", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response deleteFromQ( + @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, + @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonDelete delObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws MusicServiceException, MusicQueryException { + // added checking as per RestMusicDataAPI + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (delObj == null) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("deleteFromQ JsonDelete delObjis empty").toMap()).build(); + } + + return new RestMusicDataAPI().deleteFromTable(version, minorVersion, patchVersion, aid, ns, + authorization, delObj, keyspace, tablename, info); + } + + /** + * + * @param keyspace + * @param tablename + * @param info + * @return + * @throws Exception + */ + @GET + @Path("/keyspaces/{keyspace}/{qname}/peek") + @ApiOperation(value = "", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + //public Map> peek( + public Response peek( + @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, + @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) { + int limit =1; //peek must return just the top row + // Map auth = new HashMap<>(); + // String userId =auth.get(MusicUtil.USERID); + // String password =auth.get(MusicUtil.PASSWORD); + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + + PreparedQueryObject queryObject = new PreparedQueryObject(); + if (info.getQueryParameters() == null ) { //|| info.getQueryParameters().isEmpty()) + queryObject.appendQueryString( + "SELECT * FROM " + keyspace + "." + tablename + " LIMIT " + limit + ";"); + } else { + try { + queryObject = new RestMusicDataAPI().selectSpecificQuery(keyspace, tablename, info, limit); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, + ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()) + .build(); + } + } + + try { + ResultSet results = MusicCore.get(queryObject); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS) + .setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, + ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()) + .build(); + } + } + + /** + * + * + * @param keyspace + * @param tablename + * @param info + * @return + * @throws Exception + */ + @GET + @Path("/keyspaces/{keyspace}/{qname}/filter") + @ApiOperation(value = "filter", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + // public Map> filter( + public Response filter( + @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, + @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws Exception { + + return new RestMusicDataAPI().selectWithCritical(version, minorVersion, patchVersion, aid, ns, authorization,null, keyspace, tablename, info);// , limit) + + } + + /** + * + * @param tabObj + * @param keyspace + * @param tablename + * @throws Exception + */ + @DELETE + @ApiOperation(value = "DropQ", response = String.class) + @Path("/keyspaces/{keyspace}/{qname}") + @Produces(MediaType.APPLICATION_JSON) + public Response dropQ( + @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", + required = false) @HeaderParam("X-minorVersion") String minorVersion, + @ApiParam(value = "Patch Version", + required = false) @HeaderParam("X-patchVersion") String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { + + return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename); + + } +} diff --git a/music-rest/src/main/java/org/onap/music/rest/RestMusicTestAPI.java b/music-rest/src/main/java/org/onap/music/rest/RestMusicTestAPI.java new file mode 100644 index 00000000..c1c04b09 --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicTestAPI.java @@ -0,0 +1,70 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.rest; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.main.MusicUtil; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + + +@Path("/v{version: [0-9]+}/test") +@Api(value="Test Api") +public class RestMusicTestAPI { + + @SuppressWarnings("unused") + private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicTestAPI.class); + + /** + * Returns a test JSON. This will confirm that REST is working. + * @return + */ + @GET + @Path("/") + @ApiOperation(value = "Get Test", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Map> simpleTests( + @Context HttpServletResponse response) { + response.addHeader("X-latestVersion",MusicUtil.getVersion()); + Map> testMap = new HashMap<>(); + for(int i=0; i < 3; i++){ + HashMap innerMap = new HashMap<>(); + innerMap.put("Music Version",MusicUtil.getVersion()); + innerMap.put("Music Build",MusicUtil.getBuild()); + innerMap.put(i+1+"", i+2+""); + testMap.put(i+"", innerMap); + } + return testMap; + } +} diff --git a/music-rest/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/music-rest/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java new file mode 100644 index 00000000..8c86152e --- /dev/null +++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.rest; + +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + + +@Path("/v{version: [0-9]+}/version") +@Api(value="Version Api") +public class RestMusicVersionAPI { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class); + private static final String MUSIC_KEY = "MUSIC:"; + /** + * Get the version of MUSIC. + * @return + */ + @GET + @ApiOperation(value = "Get Version", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Map version(@Context HttpServletResponse response) { + logger.info("Replying to request for MUSIC version with MUSIC:" + MusicUtil.getVersion()); + response.addHeader("X-latestVersion",MusicUtil.getVersion()); + return new JsonResponse(ResultType.SUCCESS). + setMusicVersion(MUSIC_KEY + MusicUtil.getVersion()).toMap(); + } + + /** + * Get the version of MUSIC. + * @return + */ + @GET + @Path("/build") + @ApiOperation(value = "Get Version", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Map build(@Context HttpServletResponse response) { + logger.info("Replying to request for MUSIC build with MUSIC:" + MusicUtil.getBuild()); + response.addHeader("X-latestVersion",MusicUtil.getVersion()); + return new JsonResponse(ResultType.SUCCESS) + .setMusicBuild(MUSIC_KEY + MusicUtil.getBuild()) + .setMusicVersion(MUSIC_KEY + MusicUtil.getVersion()).toMap(); + } + + +} \ No newline at end of file diff --git a/music-rest/src/main/resources/key.properties b/music-rest/src/main/resources/key.properties new file mode 100644 index 00000000..5ce266fa --- /dev/null +++ b/music-rest/src/main/resources/key.properties @@ -0,0 +1 @@ +cipher.enc.key= nothing to see here diff --git a/music-rest/src/test/java/LICENSE.txt b/music-rest/src/test/java/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/music-rest/src/test/java/LICENSE.txt @@ -0,0 +1,24 @@ + +The following license applies to all files in this and sub-directories. Licenses +are included in individual source files where appropriate, and if it differs +from this text, it supersedes this. Any file that does not have license text +defaults to being covered by this text; not all files support the addition of +licenses. +# +# ------------------------------------------------------------------------- +# Copyright (c) 2017 AT&T Intellectual Property +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +# \ No newline at end of file diff --git a/music-rest/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java b/music-rest/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java new file mode 100644 index 00000000..58135551 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java @@ -0,0 +1,61 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.exceptions; + +import org.codehaus.jackson.map.exc.UnrecognizedPropertyException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.ws.rs.core.Response; +import java.io.EOFException; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +@RunWith(SpringJUnit4ClassRunner.class) +public class MusicExceptionMapperTest { + + @Test + public void testToResponse() { + MusicExceptionMapper musicExceptionMapper = new MusicExceptionMapper(); + UnrecognizedPropertyException unrecognizedPropertyException = mock(UnrecognizedPropertyException.class); + Response response = musicExceptionMapper.toResponse(unrecognizedPropertyException); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertTrue(((Map)response.getEntity()).get("error").toString().startsWith("Unknown field :")); + + EOFException eofException = mock(EOFException.class); + response = musicExceptionMapper.toResponse(eofException); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertTrue(((Map)response.getEntity()).get("error").toString().equals("Request body cannot be empty".trim())); + + IllegalArgumentException illegalArgumentException = mock(IllegalArgumentException.class); + Mockito.when(illegalArgumentException.getMessage()).thenReturn("ERROR MSG"); + response = musicExceptionMapper.toResponse(illegalArgumentException); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertTrue(((Map)response.getEntity()).get("error").toString().equals("ERROR MSG".trim())); + } +} \ No newline at end of file diff --git a/music-rest/src/test/java/org/onap/music/rest/ApplicationTest.java b/music-rest/src/test/java/org/onap/music/rest/ApplicationTest.java new file mode 100644 index 00000000..66983312 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/rest/ApplicationTest.java @@ -0,0 +1,94 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * + * Modifications Copyright (C) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.rest; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ApplicationTest { + + Application apl=new Application(); + private String application_name="music"; + private String username="music"; + private String password="music"; + private String keyspace_name="music"; + private boolean is_aaf=false; + private String uuid="123"; + private boolean is_api=true; + + @Test + public void testsetApplication_name() { + apl.setApplication_name(application_name); + assertEquals("music",apl.getApplication_name()); + } + + @Test + public void testsetUsername() + { + apl.setUsername(username); + assertEquals("music",apl.getUsername()); + } + + @Test + public void testsetPassword() + { + apl.setPassword(password); + assertEquals("music",apl.getPassword()); + } + + @Test + public void testsetKeyspace_name() + { + apl.setKeyspace_name(keyspace_name); + assertEquals("music",apl.getKeyspace_name()); + } + + @Test + public void testsetIs_aaf() + { + apl.setIs_aaf(is_aaf); + assertEquals(false,apl.isIs_aaf()); + } + + + @Test + public void testsetUuid() + { + apl.setUuid(uuid); + assertEquals("123",apl.getUuid()); + } + + @Test + public void testsetIs_api() + { + apl.setIs_api(is_api); + assertEquals(true,apl.getIs_api()); + + } + + + +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java b/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java new file mode 100644 index 00000000..7b116bc8 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java @@ -0,0 +1,247 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +/** + * @author srupane + * + */ + +import java.math.BigInteger; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +//import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.lockingservice.cassandra.LockType; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.extras.codecs.enums.EnumNameCodec; + +public class CassandraCQL { + public static final String createAdminKeyspace = "CREATE KEYSPACE admin WITH REPLICATION = " + + "{'class' : 'SimpleStrategy' , 'replication_factor': 1} AND DURABLE_WRITES = true"; + + public static final String createAdminTable = "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text," + + " application_name text, is_api boolean," + + " password text, username text," + + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");"; + + public static final String createKeySpace = + "CREATE KEYSPACE IF NOT EXISTS testcassa WITH replication = " + +"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;"; + + public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testcassa"; + + public static final String createTableEmployees = + "CREATE TABLE IF NOT EXISTS testcassa.employees " + + "(vector_ts text,empid uuid,empname text,empsalary varint,address Map,PRIMARY KEY (empname)) " + + "WITH comment='Financial Info of employees' " + + "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} " + + "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};"; + + public static final String insertIntoTablePrepared1 = + "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary) VALUES (?,?,?,?); "; + + public static final String insertIntoTablePrepared2 = + "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary,address) VALUES (?,?,?,?,?);"; + + public static final String selectALL = "SELECT * FROM testcassa.employees;"; + + public static final String selectSpecific = + "SELECT * FROM testcassa.employees WHERE empname= ?;"; + + public static final String updatePreparedQuery = + "UPDATE testcassa.employees SET vector_ts=?,address= ? WHERE empname= ?;"; + + public static final String deleteFromTable = " "; + + public static final String deleteFromTablePrepared = " "; + + // Set Values for Prepared Query + + public static List setPreparedInsertValues1() { + + List preppreparedInsertValues1 = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6"); + BigInteger empSalary = BigInteger.valueOf(23443); + String empName = "Mr Test one"; + preppreparedInsertValues1.add(vectorTs); + preppreparedInsertValues1.add(empId); + preppreparedInsertValues1.add(empName); + preppreparedInsertValues1.add(empSalary); + return preppreparedInsertValues1; + } + + public static List setPreparedInsertValues2() { + + List preparedInsertValues2 = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6"); + BigInteger empSalary = BigInteger.valueOf(45655); + String empName = "Mr Test two"; + Map address = new HashMap<>(); + preparedInsertValues2.add(vectorTs); + preparedInsertValues2.add(empId); + preparedInsertValues2.add(empName); + preparedInsertValues2.add(empSalary); + address.put("Street", "1 some way"); + address.put("City", "Some town"); + preparedInsertValues2.add(address); + return preparedInsertValues2; + } + + public static List setPreparedUpdateValues() { + + List preparedUpdateValues = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + Map address = new HashMap<>(); + preparedUpdateValues.add(vectorTs); + String empName = "Mr Test one"; + address.put("Street", "101 Some Way"); + address.put("City", "New York"); + preparedUpdateValues.add(address); + preparedUpdateValues.add(empName); + return preparedUpdateValues; + } + + // Generate Different Prepared Query Objects + /** + * Query Object for Get. + * + * @return + */ + public static PreparedQueryObject setPreparedGetQuery() { + + PreparedQueryObject queryObject = new PreparedQueryObject(); + String empName1 = "Mr Test one"; + queryObject.appendQueryString(selectSpecific); + queryObject.addValue(empName1); + return queryObject; + } + + /** + * Query Object 1 for Insert. + * + * @return {@link PreparedQueryObject} + */ + public static PreparedQueryObject setPreparedInsertQueryObject1() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(insertIntoTablePrepared1); + List values = setPreparedInsertValues1(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + /** + * Query Object 2 for Insert. + * + * @return {@link PreparedQueryObject} + */ + public static PreparedQueryObject setPreparedInsertQueryObject2() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(insertIntoTablePrepared2); + List values = setPreparedInsertValues2(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + /** + * Query Object for Update. + * + * @return {@link PreparedQueryObject} + */ + public static PreparedQueryObject setPreparedUpdateQueryObject() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(updatePreparedQuery); + List values = setPreparedUpdateValues(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + private static ArrayList getAllPossibleLocalIps() { + ArrayList allPossibleIps = new ArrayList(); + try { + Enumeration en = NetworkInterface.getNetworkInterfaces(); + while (en.hasMoreElements()) { + NetworkInterface ni = (NetworkInterface) en.nextElement(); + Enumeration ee = ni.getInetAddresses(); + while (ee.hasMoreElements()) { + InetAddress ia = (InetAddress) ee.nextElement(); + allPossibleIps.add(ia.getHostAddress()); + } + } + } catch (SocketException e) { + System.out.println(e.getMessage()); + } + return allPossibleIps; + } + + public static MusicDataStore connectToEmbeddedCassandra() throws Exception { + System.setProperty("log4j.configuration", "log4j.properties"); + + String address = "localhost"; + + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + Cluster cluster = new Cluster.Builder().withoutJMXReporting().withoutMetrics().addContactPoint(address).withPort(9142).build(); + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(5000); + EnumNameCodec lockTypeCodec = new EnumNameCodec(LockType.class); + cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec); + + Session session = cluster.connect(); + + return new MusicDataStore(cluster, session); + } + +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java b/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java new file mode 100644 index 00000000..6af8c0d9 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java @@ -0,0 +1,167 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018-2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; +import org.onap.music.main.ResultType; +import org.onap.music.response.jsonobjects.JsonResponse; + +public class JsonResponseTest { + + JsonResponse result = null; + + @Test + public void testJsonResponseBooleanStringString() { + result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("version"); + assertEquals("error",result.getError()); + } + + @Test + public void testStatus() { + result = new JsonResponse(ResultType.SUCCESS); + result.setStatus(ResultType.SUCCESS); + assertEquals(ResultType.SUCCESS, result.getStatus()); + result = new JsonResponse(ResultType.FAILURE).setError("error").setMusicVersion("version"); + assertEquals(ResultType.FAILURE, result.getStatus()); + } + + @Test + public void testError() { + result = new JsonResponse(ResultType.FAILURE); + result.setError("error"); + assertTrue(result.getError().equals("error")); + result.setError(""); + assertFalse(result.getError().equals("error")); + } + + @Test + public void testVersion() { + result = new JsonResponse(ResultType.SUCCESS); + result.setMusicVersion("version"); + assertTrue(result.getMusicVersion().equals("version")); + result.setMusicVersion(""); + assertFalse(result.getMusicVersion().equals("version")); + } + + @Test + public void testToMap() { + result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("1.0"); + Map myMap = result.toMap(); + assertTrue(myMap.containsKey("status")); + assertEquals(ResultType.SUCCESS, myMap.get("status")); + assertEquals("error", myMap.get("error")); + assertEquals("1.0", myMap.get("version")); + + result = new JsonResponse(ResultType.FAILURE); + myMap = result.toMap(); + assertTrue(myMap.containsKey("status")); + assertEquals(ResultType.FAILURE, myMap.get("status")); + } + + @Test + public void testMessage() { + result = new JsonResponse(ResultType.SUCCESS); + result.setMessage("message"); + assertEquals("message", result.getMessage()); + + } + + @Test + public void testDataResult() { + result = new JsonResponse(ResultType.SUCCESS); + Map> dataResult= new HashMap<>(); + result.setDataResult(dataResult); + assertEquals(dataResult, result.getDataResult()); + + } + + @Test + public void testLock() { + result = new JsonResponse(ResultType.SUCCESS); + result.setLock("lock"); + assertEquals("lock", result.getLock()); + + } + + @Test + public void testLockLease() { + result = new JsonResponse(ResultType.SUCCESS); + result.setLockLease("lockLease"); + assertEquals("lockLease", result.getLockLease()); + } + + @Test + public void testMusicBuild() { + result = new JsonResponse(ResultType.SUCCESS); + result.setMusicBuild("Build"); + assertEquals("Build", result.getMusicBuild()); + } + + @Test + public void testLockHolder() { + result = new JsonResponse(ResultType.SUCCESS); + List lockHolders = new ArrayList<>(); + result.setLockHolder(lockHolders); + assertEquals(lockHolders, result.getLockHolder()); + } + + @Test + public void testLockStatus() { + result = new JsonResponse(ResultType.SUCCESS); + LockStatus status = LockStatus.LOCKED; + result.setLockStatus(status); + assertEquals(status, result.getLockStatus()); + + } + + @Test + public void testToString() { + result = new JsonResponse(ResultType.SUCCESS); + assertTrue(result.toString() instanceof String); + + } + + @Test + public void testLockHolders() { + result = new JsonResponse(ResultType.SUCCESS).setLock("lockName").setLockHolder("lockholder1"); + Map lockMap = (Map) result.toMap().get("lock"); + // assure that this is string for backwards compatibility + assertEquals("lockholder1", lockMap.get("lock-holder")); + + List lockholders = new ArrayList<>(); + lockholders.add("lockholder1"); + lockholders.add("lockholder2"); + result.setLockHolder(lockholders); + lockMap = (Map) result.toMap().get("lock"); + assertEquals(lockMap.get("lock-holder"), lockholders); + } +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java new file mode 100644 index 00000000..68e6f3dc --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java @@ -0,0 +1,170 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.mockito.Mock; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.PreparedQueryObject; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.TableMetadata; + +@RunWith(SpringJUnit4ClassRunner.class) +//@ActiveProfiles(profiles = "OrderRepositoryTest") +@ContextConfiguration +public class MusicDataStoreTest { + + static MusicDataStore dataStore; + static PreparedQueryObject testObject; + + @BeforeClass + public static void init()throws Exception { + dataStore = CassandraCQL.connectToEmbeddedCassandra(); + //CachingUtil.resetStatementBank(); + + } + + @AfterClass + public static void close() throws MusicServiceException, MusicQueryException { + + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.dropKeyspace); + dataStore.executePut(testObject, "eventual"); + //dataStore.close(); + //CachingUtil.resetStatementBank(); + } + + @Test + public void Test1_SetUp() throws MusicServiceException, MusicQueryException { + boolean result = false; + //CachingUtil.resetStatementBank(); + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createKeySpace); + result = dataStore.executePut(testObject, "eventual");; + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createTableEmployees); + result = dataStore.executePut(testObject, "eventual"); + assertEquals(true, result); + + } + + @Test + public void Test2_ExecutePut_eventual_insert() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedInsertQueryObject1(); + boolean result = dataStore.executePut(testObject, "eventual"); + assertEquals(true, result); + } + + @Test + public void Test3_ExecutePut_critical_insert() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedInsertQueryObject2(); + boolean result = dataStore.executePut(testObject, "Critical"); + assertEquals(true, result); + } + + @Test + public void Test4_ExecutePut_eventual_update() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedUpdateQueryObject(); + boolean result = false; + result = dataStore.executePut(testObject, "eventual"); + assertEquals(true, result); + } + + @Test + public void Test5_ExecuteEventualGet() throws MusicServiceException, MusicQueryException { + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.selectALL); + boolean result = false; + int count = 0; + ResultSet output = null; + output = dataStore.executeOneConsistencyGet(testObject); + System.out.println(output); + ; + for (Row row : output) { + count++; + System.out.println(row.toString()); + } + if (count == 2) { + result = true; + } + assertEquals(false, result); + } + + @Test + public void Test6_ExecuteCriticalGet() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedGetQuery(); + boolean result = false; + int count = 0; + ResultSet output = null; + output = dataStore.executeQuorumConsistencyGet(testObject); + System.out.println(output); + ; + for (Row row : output) { + count++; + System.out.println(row.toString()); + } + if (count == 1) { + result = true; + } + assertEquals(false, result); + } + + @Test(expected = NullPointerException.class) + public void Test7_exception() { + PreparedQueryObject queryObject = null; + try { + dataStore.executePut(queryObject, "critical"); + } catch (MusicQueryException | MusicServiceException e) { + System.out.println(e.getMessage()); + } + } + + @Test + public void Test8_columnDataType() { + DataType data = dataStore.returnColumnDataType("testCassa", "employees", "empName"); + String datatype = data.toString(); + assertEquals("text",datatype); + } + + @Test + public void Test8_columnMetdaData() { + TableMetadata data = dataStore.returnColumnMetadata("testCassa", "employees"); + assertNotNull(data); + } +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java b/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java new file mode 100644 index 00000000..385a4698 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java @@ -0,0 +1,975 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +//cjc import static org.junit.Assert.assertTrue; +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.List; +//cjc import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.mindrot.jbcrypt.BCrypt; +//cjcimport org.mindrot.jbcrypt.BCrypt; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +//cjc import org.onap.music.datastore.jsonobjects.JsonKeySpace; +//import org.onap.music.datastore.jsonobjects.JsonOnboard; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +//import org.onap.music.main.ResultType; +//import org.onap.music.rest.RestMusicAdminAPI; +import org.onap.music.rest.RestMusicDataAPI; +import org.onap.music.rest.RestMusicQAPI; +import org.springframework.test.util.ReflectionTestUtils; +import org.onap.music.rest.RestMusicLocksAPI; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.sun.jersey.core.util.Base64; +//import com.datastax.driver.core.DataType; +//import com.datastax.driver.core.ResultSet; +//import com.datastax.driver.core.Row; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@RunWith(MockitoJUnitRunner.class) +public class TestRestMusicQAPI { + + + //RestMusicAdminAPI admin = new RestMusicAdminAPI(); + RestMusicLocksAPI lock = new RestMusicLocksAPI(); + RestMusicQAPI qData = new RestMusicQAPI(); + static PreparedQueryObject testObject; + + @Mock + static HttpServletResponse http; + + @Mock + UriInfo info; + + static String appName = "TestApp"; + static String userId = "TestUser"; + static String password = "TestPassword"; + /* + static String appName = "com.att.ecomp.portal.demeter.aid";//"TestApp"; + static String userId = "m00468@portal.ecomp.att.com";//"TestUser"; + static String password = "happy123";//"TestPassword"; + */ + static String authData = userId+":"+password; + static String wrongAuthData = userId+":"+"pass"; + static String authorization = new String(Base64.encode(authData.getBytes())); + static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); + + static boolean isAAF = false; + static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); + static String uuidS = "abc66ccc-d857-4e90-b1e5-df98a3d40ce6"; + static String keyspaceName = "testkscjc"; + static String tableName = "employees"; + static String xLatestVersion = "X-latestVersion"; + static String onboardUUID = null; + static String lockId = null; + static String lockName = "testkscjc.employees.sample3"; + static String majorV="3"; + static String minorV="0"; + static String patchV="1"; + static String aid=null; + static JsonKeySpace kspObject=null; + static RestMusicDataAPI data = new RestMusicDataAPI(); + static Response resp; + + @BeforeClass + public static void init() throws Exception { + try { + ReflectionTestUtils.setField(MusicDataStoreHandle.class, "mDstoreHandle", + CassandraCQL.connectToEmbeddedCassandra()); + MusicCore.setmLockHandle(new CassaLockStore(MusicDataStoreHandle.getDSHandle())); + + // System.out.println("before class keysp"); + //resp=data.createKeySpace(majorV,minorV,patchV,aid,appName,userId,password,kspObject,keyspaceName); + //System.out.println("after keyspace="+keyspaceName); + } catch (Exception e) { + System.out.println("before class exception "); + e.printStackTrace(); + } + // admin keyspace and table + testObject = new PreparedQueryObject(); + testObject.appendQueryString("CREATE KEYSPACE admin WITH REPLICATION = " + + "{'class' : 'SimpleStrategy' , " + + "'replication_factor': 1} AND DURABLE_WRITES = true"); + MusicCore.eventualPut(testObject); + testObject = new PreparedQueryObject(); + testObject.appendQueryString( + "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text," + + " application_name text, is_api boolean," + + " password text, username text," + + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");"); + MusicCore.eventualPut(testObject); + + testObject = new PreparedQueryObject(); + testObject.appendQueryString( + "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), + MusicUtil.DEFAULTKEYSPACENAME)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + MusicCore.eventualPut(testObject); + + testObject = new PreparedQueryObject(); + testObject.appendQueryString( + "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), + UUID.fromString("bbc66ccc-d857-4e90-b1e5-df98a3d40de6"))); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), + MusicUtil.DEFAULTKEYSPACENAME)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestApp1")); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestUser1")); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + MusicCore.eventualPut(testObject); + + testObject = new PreparedQueryObject(); + testObject.appendQueryString( + "select uuid from admin.keyspace_master where application_name = ? allow filtering"); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + ResultSet rs = MusicCore.get(testObject); + List rows = rs.all(); + if (rows.size() > 0) { + System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid")); + } + + JsonKeySpace jsonKeyspace = new JsonKeySpace(); + Map consistencyInfo = new HashMap<>(); + Map replicationInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + replicationInfo.put("class", "SimpleStrategy"); + replicationInfo.put("replication_factor", 1); + jsonKeyspace.setConsistencyInfo(consistencyInfo); + jsonKeyspace.setDurabilityOfWrites("true"); + jsonKeyspace.setKeyspaceName(keyspaceName); + jsonKeyspace.setReplicationInfo(replicationInfo); + Response response = data.createKeySpace(majorV, minorV, patchV, null, authorization, appName, + jsonKeyspace, keyspaceName); + System.out.println("#######status is " + response.getStatus()+" keyspace="+keyspaceName); + + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + System.out.println("After class"); + testObject = new PreparedQueryObject(); + testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); + MusicCore.eventualPut(testObject); + testObject = new PreparedQueryObject(); + testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin"); + MusicCore.eventualPut(testObject); + MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle"); + if (mds != null) + mds.close(); + } + + +/* @Test + public void Test1_createQ_good() throws Exception { + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setTableName(tableName); + jsonTable.setFields(fields); + jsonTable.setPartitionKey("emp_name"); + jsonTable.setClusteringKey("uuid"); + jsonTable.setClusteringOrder("uuid ASC"); + //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableName); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()); + System.out.println("Entity" + response.getEntity()); + assertEquals(200, response.getStatus()); + }*/ + + @Test + public void Test1_createQ_FieldsEmpty() throws Exception { + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + /* + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + */ + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableName); + jsonTable.setFields(fields); + //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableName); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("EmptyFields #######status is " + response.getStatus()); + System.out.println("Entity" + response.getEntity()); + assertNotEquals(200, response.getStatus()); + } +/* @Test + public void Test1_createQ_Clustergood() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPartitionKey("emp_name"); + jsonTable.setClusteringKey("emp_id"); + jsonTable.setClusteringOrder("emp_id DESC"); + jsonTable.setTableName(tableNameC); + jsonTable.setFields(fields); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(200, response.getStatus()); + }*/ + +/* @Test + public void Test1_createQ_ClusterOrderGood1() throws Exception { + String tableNameC="testcjcO"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name,emp_id)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_id DESC"); + jsonTable.setFields(fields); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(200, response.getStatus()); + } */ + +/* @Test + public void Test1_createQ_PartitionKeygood() throws Exception { + String tableNameP="testcjcP"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setTableName(tableNameP); + jsonTable.setClusteringOrder("emp_id DESC"); + jsonTable.setFields(fields); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameP); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameP); + System.out.println("Entity" + response.getEntity()); + assertEquals(200, response.getStatus()); + } */ + + @Test + public void Test1_createQ_PartitionKeybadclose() throws Exception { + String tableNameC="testcjcP1"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id))"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name,emp_id"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_id DESC"); + jsonTable.setFields(fields); + //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + //assertEquals(400, response.getStatus()); + assertTrue(200 != response.getStatus()); + } + +/* @Test + public void Test1_createQ_ClusterOrderGood2() throws Exception { + String tableNameC="testcjcO1g"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name,emp_salary,emp_id)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name,emp_id"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC"); + jsonTable.setFields(fields); + //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(200, response.getStatus()); + } */ + + /* @Test + public void Test1_createQ_ColPkeyoverridesPrimaryKeyGood() throws Exception { + String tableNameC="testcjcPr"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name),emp_salary,emp_id)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name,emp_id"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC"); + jsonTable.setFields(fields); + //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(200, response.getStatus()); + //assertTrue(200 != response.getStatus()); + } */ + + @Test + public void Test1_createQ_ClusterOrderBad() throws Exception { + String tableNameC="testcjcO1b"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name,emp_id)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name,emp_id"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_id DESCx"); + jsonTable.setFields(fields); + //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + + @Test + public void Test3_createQ_0() throws Exception { + //duplicate testing ... + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + String tableNameDup=tableName+"X"; + jsonTable.setTableName(tableNameDup); + jsonTable.setFields(fields); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + jsonTable, keyspaceName, tableNameDup); + System.out.println("#######status for 1st time " + response.getStatus()); + System.out.println("Entity" + response.getEntity()); + + Response response0 = qData.createQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + jsonTable, keyspaceName, tableNameDup); + // 400 is the duplicate status found in response + // Music 113 duplicate testing + //import static org.junit.Assert.assertNotEquals; + System.out.println("#######status for 2nd time " + response0.getStatus()); + System.out.println("Entity" + response0.getEntity()); + + assertFalse("Duplicate table not created for "+tableNameDup, 200==response0.getStatus()); + //assertEquals(400, response0.getStatus()); + //assertNotEquals(200,response0.getStatus()); + } + + + // Improper keyspace + @Ignore + @Test + public void Test3_createQ2() throws Exception { + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPartitionKey("emp_name"); + jsonTable.setTableName(tableName); + jsonTable.setClusteringKey("emp_salary"); + jsonTable.setClusteringOrder("emp_salary DESC"); + jsonTable.setFields(fields); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + jsonTable, "wrong", tableName); + System.out.println("#######status is " + response.getStatus()); + System.out.println("Entity" + response.getEntity()); + assertEquals(401, response.getStatus()); + } + + + +/* @Test + public void Test4_insertIntoQ() throws Exception { + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testName"); + values.put("emp_salary", 500); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, keyspaceName, tableName); + assertEquals(200, response.getStatus()); + }*/ + + + @Test + public void Test4_insertIntoQ_valuesEmpty() throws Exception { + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + /* + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testName"); + values.put("emp_salary", 500); + */ + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, keyspaceName, tableName); + assertNotEquals(200, response.getStatus()); + } + +/* @Test + public void Test4_insertIntoQ2() throws Exception { + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "test1"); + values.put("emp_salary", 1500); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.insertIntoQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + jsonInsert, keyspaceName, tableName); + assertEquals(200, response.getStatus()); + }*/ + + + +/* @Test + public void Test5_updateQ() throws Exception { + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + Map values = new HashMap<>(); + row.add("emp_name", "testName"); + row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_salary", "2500"); + consistencyInfo.put("type", "atomic"); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName(tableName); + jsonUpdate.setValues(values); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = qData.updateQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, keyspaceName, tableName, info); + assertEquals(200, response.getStatus()); + }*/ + + @Test + public void Test5_updateQEmptyValues() throws Exception { + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + Map values = new HashMap<>(); + row.add("emp_name", "testName"); + //values.put("emp_salary", 2500); + consistencyInfo.put("type", "atomic"); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName(tableName); + jsonUpdate.setValues(values); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + //Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = qData.updateQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, keyspaceName, tableName, info); + assertNotEquals(200, response.getStatus()); + } + +/* @Test + public void Test6_filterQ() throws Exception { //select + JsonSelect jsonSelect = new JsonSelect(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testName"); + row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + consistencyInfo.put("type", "atomic"); + jsonSelect.setConsistencyInfo(consistencyInfo); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = qData.filter(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, keyspaceName, tableName, info); + HashMap> map = (HashMap>) response.getEntity(); + HashMap result = map.get("result"); + assertEquals("2500", ((HashMap) result.get("row 0")).get("emp_salary").toString()); + }*/ + +/* @Test + public void Test6_peekQ() throws Exception { //select + JsonSelect jsonSelect = new JsonSelect(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testName"); + consistencyInfo.put("type", "atomic"); + jsonSelect.setConsistencyInfo(consistencyInfo); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = qData.peek(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, keyspaceName, tableName, info); + HashMap> map = (HashMap>) response.getEntity(); + HashMap result = map.get("result"); + if (result.isEmpty() ) assertTrue(true); + else assertFalse(false); + //assertEquals("2500", ((HashMap) result.get("row 0")).get("emp_salary").toString()); + }*/ +/* + @Test + public void Test6_peekQ_empty() throws Exception { //select + // row is not needed in thhis test + JsonSelect jsonSelect = new JsonSelect(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testName"); + consistencyInfo.put("type", "atomic"); + jsonSelect.setConsistencyInfo(consistencyInfo); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + UriInfo infoe= mockUriInfo("/peek?");//empty queryParam: cause exception + // infoe.setQueryParameters(""); + System.out.println("uriinfo="+infoe.getQueryParameters()); + Mockito.when(infoe.getQueryParameters()).thenReturn(row); + Response response = qData.peek(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, keyspaceName, tableName, infoe); + HashMap> map = (HashMap>) response.getEntity(); + HashMap result = map.get("result"); + if (result.isEmpty() ) assertTrue(true); + else assertFalse(false); + //assertEquals("2500", ((HashMap) result.get("row 0")).get("emp_salary").toString()); + }*/ + +/* @Test + public void Test6_deleteFromQ1() throws Exception { + JsonDelete jsonDelete = new JsonDelete(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "test1"); + consistencyInfo.put("type", "atomic"); + jsonDelete.setConsistencyInfo(consistencyInfo); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = qData.deleteFromQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + jsonDelete, keyspaceName, tableName, info); + assertEquals(200, response.getStatus()); + }*/ + + // Values + @Test + @Ignore + public void Test6_deleteFromQ() throws Exception { + JsonDelete jsonDelete = new JsonDelete(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + consistencyInfo.put("type", "atomic"); + jsonDelete.setConsistencyInfo(consistencyInfo); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = qData.deleteFromQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + jsonDelete, keyspaceName, tableName, info); + assertEquals(400, response.getStatus()); + } + + // delObj + @Test + public void Test6_deleteFromQ2() throws Exception { + JsonDelete jsonDelete = new JsonDelete(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "test1"); + consistencyInfo.put("type", "atomic"); + jsonDelete.setConsistencyInfo(consistencyInfo); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + //Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = qData.deleteFromQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + null, keyspaceName, tableName, info); + assertEquals(400, response.getStatus()); + } +/* + @Test + public void Test7_dropQ() throws Exception { + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "atomic"); + jsonTable.setConsistencyInfo(consistencyInfo); + Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.dropQ(majorV, minorV,patchV, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + keyspaceName, tableName); + assertEquals(200, response.getStatus()); + }*/ + + private UriInfo mockUriInfo(String urix) throws URISyntaxException { + String uri="http://localhost:8080/MUSIC/rest/v"+majorV+"/priorityq/keyspaces/"+keyspaceName+"/"+tableName+urix; + UriInfo uriInfo = Mockito.mock(UriInfo.class); + System.out.println("mock urix="+urix+" uri="+uri); + Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI(uri)); + return uriInfo; + } + + + //Empty Fields + @Test + public void Test8_createQ_fields_empty() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPartitionKey("emp_name"); + jsonTable.setClusteringKey("emp_id"); + jsonTable.setClusteringOrder("emp_id DESC"); + jsonTable.setTableName(tableNameC); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + //Partition key null + @Test + public void Test8_createQ_partitionKey_empty() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setClusteringKey("emp_id"); + jsonTable.setClusteringOrder("emp_id DESC"); + jsonTable.setTableName(tableNameC); + jsonTable.setFields(fields); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + //Clustering key null + @Test + public void Test8_createQ_ClusteringKey_empty() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPartitionKey("emp_name"); + jsonTable.setClusteringOrder("emp_id DESC"); + jsonTable.setTableName(tableNameC); + jsonTable.setFields(fields); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + //Clustering Order null + @Test + public void Test8_createQ_ClusteringOrder_empty() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPartitionKey("emp_name"); + jsonTable.setClusteringKey("emp_id"); + jsonTable.setTableName(tableNameC); + jsonTable.setFields(fields); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + //Invalid primary key + @Test + public void Test8_createQ_primaryKey_invalid() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setPrimaryKey("(emp_name"); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setClusteringKey("emp_id"); + jsonTable.setClusteringOrder("emp_id ASC"); + jsonTable.setTableName(tableNameC); + jsonTable.setFields(fields); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + //Primary key with no clustering key + @Test + public void Test8_createQ_primaryKey_with_empty_clusteringKey() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableNameC); + jsonTable.setFields(fields); + jsonTable.setClusteringOrder("emp_id ASC"); + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + + } + + //Primary key with no partition key + @Test + public void Test8_createQ_primaryKey_with_empty_partitionKey() throws Exception { + String tableNameC="testcjcC"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "text"); + fields.put("emp_salary", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey(" "); + jsonTable.setTableName(tableNameC); + jsonTable.setFields(fields); + jsonTable.setClusteringOrder("emp_id ASC"); + + //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = qData.createQ(majorV, minorV,patchV, + aid, appName, authorization, + jsonTable, keyspaceName, tableNameC); + System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); + System.out.println("Entity" + response.getEntity()); + assertEquals(400, response.getStatus()); + } + +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java b/music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java new file mode 100644 index 00000000..cc7c5146 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java @@ -0,0 +1,116 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +import java.util.List; +import java.util.UUID; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.springframework.test.util.ReflectionTestUtils; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.sun.jersey.core.util.Base64; + +@RunWith(Suite.class) +@SuiteClasses({ TstRestMusicDataAPI.class, TstRestMusicLockAPI.class, + TstRestMusicConditionalAPI.class}) +public class TestsUsingCassandra { + + static String appName = "TestApp"; + static String userId = "TestUser"; + static String password = "TestPassword"; + static String authData = userId+":"+password; + static String wrongAuthData = userId+":"+"pass"; + static String authorization = new String(Base64.encode(authData.getBytes())); + static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); + static boolean isAAF = false; + static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); + static String keyspaceName = "testcassa"; + static String tableName = "employees"; + static String xLatestVersion = "X-latestVersion"; + static String onboardUUID = null; + static String aid = "abc66ccc-d857-4e90-b1e5-df98a3d40ce6"; + + @BeforeClass + public static void beforeClass() throws Exception { + ReflectionTestUtils.setField(MusicDataStoreHandle.class, "mDstoreHandle", + CassandraCQL.connectToEmbeddedCassandra()); + MusicCore.setmLockHandle(new CassaLockStore(MusicDataStoreHandle.getDSHandle())); + createAdminTable(); + } + + @AfterClass + public static void afterClass() { + PreparedQueryObject testObject = new PreparedQueryObject(); + testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin"); + MusicCore.eventualPut(testObject); + MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle"); + if (mds != null) + mds.close(); + } + + private static void createAdminTable() throws Exception { + PreparedQueryObject testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createAdminKeyspace); + MusicCore.eventualPut(testObject); + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createAdminTable); + MusicCore.eventualPut(testObject); + + testObject = new PreparedQueryObject(); + testObject.appendQueryString( + "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), + keyspaceName)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + MusicCore.eventualPut(testObject); + + testObject = new PreparedQueryObject(); + testObject.appendQueryString( + "select uuid from admin.keyspace_master where application_name = ? allow filtering"); + testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + ResultSet rs = MusicCore.get(testObject); + List rows = rs.all(); + if (rows.size() > 0) { + System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid")); + onboardUUID = rows.get(0).getUUID("uuid").toString(); + } + } +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java b/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java new file mode 100644 index 00000000..7021178e --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java @@ -0,0 +1,373 @@ +/* + * ============LICENSE_START========================================== org.onap.music + * =================================================================== Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== Licensed under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the + * License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR 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.music.unittests; + +import static org.junit.Assert.assertEquals; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mindrot.jbcrypt.BCrypt; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.conductor.conditionals.JsonConditional; +import org.onap.music.conductor.conditionals.RestMusicConditionalAPI; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.rest.RestMusicDataAPI; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.sun.jersey.core.util.Base64; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +@RunWith(MockitoJUnitRunner.class) +public class TstRestMusicConditionalAPI { + + RestMusicDataAPI data = new RestMusicDataAPI(); + RestMusicConditionalAPI cond = new RestMusicConditionalAPI(); + static PreparedQueryObject testObject; + + @Mock + HttpServletResponse http; + + @Mock + UriInfo info; + + static String appName = "TestApp"; + static String userId = "TestUser"; + static String password = "TestPassword"; + static String authData = userId + ":" + password; + static String wrongAuthData = userId + ":" + "pass"; + static String authorization = new String(Base64.encode(authData.getBytes())); + static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); + static boolean isAAF = false; + static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); + static String keyspaceName = "testcassa"; + static String tableName = "employees"; + static String xLatestVersion = "X-latestVersion"; + static String onboardUUID = null; + + @BeforeClass + public static void init() throws Exception { + System.out.println("Testing RestMusicConditional class"); + try { + createKeyspace(); + } catch (Exception e) { + e.printStackTrace(); + throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage()); + } + } + + @After + public void afterEachTest() throws MusicServiceException { + clearAllTablesFromKeyspace(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + testObject = new PreparedQueryObject(); + testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); + MusicCore.eventualPut(testObject); + } + + @Test + public void test_insertIntoTable() throws Exception { + System.out.println("Testing conditional insert into table"); + createTable(); + + JsonConditional jsonCond = new JsonConditional(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("id", "test_id"); + consistencyInfo.put("type", "eventual"); + HashMap cascadeData = new HashMap<>(); + HashMap cascadeValue = new HashMap<>(); + cascadeValue.put("created", "hello"); + cascadeValue.put("updated", "world"); + cascadeData.put("key", "p1"); + cascadeData.put("value", cascadeValue); + HashMap> condition = new HashMap<>(); + HashMap exists = new HashMap<>(); + exists.put("status", "parked"); + HashMap nonexists = new HashMap<>(); + nonexists.put("status", "underway"); + condition.put("exists", exists); + condition.put("nonexists", nonexists); + + jsonCond.setPrimaryKey("id"); + jsonCond.setPrimaryKeyValue("testname"); + jsonCond.setCasscadeColumnName("plans"); + jsonCond.setTableValues(values); + jsonCond.setCasscadeColumnData(cascadeData); + jsonCond.setConditions(condition); + + Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, keyspaceName, tableName, jsonCond); + + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + /* + * @Test public void test4_insertIntoTable2() throws Exception { System.out.println("Testing insert into table #2"); + * createTable(); JsonInsert jsonInsert = new JsonInsert(); Map consistencyInfo = new HashMap<>(); + * Map values = new HashMap<>(); values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + * values.put("emp_name", "test1"); values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual"); + * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName); + * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1", + * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonInsert, keyspaceName, tableName); + * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + * + * assertEquals(200, response.getStatus()); } + * + * // Auth Error + * + * @Test public void test4_insertIntoTable3() throws Exception { + * System.out.println("Testing insert into table with bad credentials"); createTable(); JsonInsert jsonInsert = new + * JsonInsert(); Map consistencyInfo = new HashMap<>(); Map values = new + * HashMap<>(); values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); values.put("emp_name", "test1"); + * values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual"); + * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName); + * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1", + * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, wrongAuthorization, jsonInsert, keyspaceName, + * tableName); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + * + * assertEquals(401, response.getStatus()); } + * + * // Table wrong + * + * @Test public void test4_insertIntoTable4() throws Exception { + * System.out.println("Testing insert into wrong table"); createTable(); JsonInsert jsonInsert = new JsonInsert(); + * Map consistencyInfo = new HashMap<>(); Map values = new HashMap<>(); + * values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); values.put("emp_name", "test1"); + * values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual"); + * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName); + * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1", + * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonInsert, keyspaceName, "wrong"); + * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + * + * assertEquals(400, response.getStatus()); } + */ + + @Test + public void test5_updateTable() throws Exception { + System.out.println("Testing conditional update table"); + createAndInsertIntoTable(); + + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + + JsonConditional jsonCond = new JsonConditional(); + Map values = new HashMap<>(); + values.put("id", "test_id"); + HashMap cascadeData = new HashMap<>(); + HashMap cascadeValue = new HashMap<>(); + cascadeValue.put("created", "hello"); + cascadeValue.put("updated", "world"); + cascadeData.put("key", "p1"); + cascadeData.put("value", cascadeValue); + + jsonCond.setPrimaryKey("id"); + jsonCond.setPrimaryKeyValue("test_id"); + jsonCond.setCasscadeColumnName("plans"); + jsonCond.setTableValues(values); + jsonCond.setCasscadeColumnData(cascadeData); + + Response response = cond.updateConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, keyspaceName, tableName, jsonCond); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + /* + * // need mock code to create error for MusicCore methods + * + * @Test public void test5_updateTableAuthE() throws Exception { System.out.println("Testing update table #2"); + * createTable(); //MockitoAnnotations.initMocks(this); JsonUpdate jsonUpdate = new JsonUpdate(); Map consistencyInfo = new HashMap<>(); MultivaluedMap row = new MultivaluedMapImpl(); + * Map values = new HashMap<>(); row.add("emp_name", "testname"); values.put("emp_salary", 2500); + * consistencyInfo.put("type", "atomic"); jsonUpdate.setConsistencyInfo(consistencyInfo); + * jsonUpdate.setKeyspaceName(keyspaceName); jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values); //add + * ttl & timestamp //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + * Mockito.when(info.getQueryParameters()).thenReturn(row); //Map m1= new HashMap<>() ; + * //Mockito.when(MusicCore.autheticateUser(appName,userId,password,keyspaceName, + * "abc66ccc-d857-4e90-b1e5-df98a3d40ce6","updateTable")).thenReturn(m1); Response response = data.updateTable("1", + * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonUpdate, keyspaceName, tableName, + * info); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + * + * assertEquals(200, response.getStatus()); } + * + * @Ignore + * + * @Test public void test5_updateTableAuthException1() throws Exception { + * System.out.println("Testing update table authentication error"); createTable(); JsonUpdate jsonUpdate = new + * JsonUpdate(); Map consistencyInfo = new HashMap<>(); MultivaluedMap row = new + * MultivaluedMapImpl(); Map values = new HashMap<>(); row.add("emp_name", "testname"); + * values.put("emp_salary", 2500); consistencyInfo.put("type", "atomic"); + * jsonUpdate.setConsistencyInfo(consistencyInfo); jsonUpdate.setKeyspaceName(keyspaceName); + * jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values); + * + * Mockito.when(info.getQueryParameters()).thenReturn(row); String authDatax = ":"; String authorizationx = new + * String(Base64.encode(authDatax.getBytes())); Response response = data.updateTable("1", "1", "1", + * "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorizationx, jsonUpdate, keyspaceName, tableName, info); + * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + * + * assertEquals(401, response.getStatus()); } + * + * @Ignore + * + * @Test public void test5_updateTableAuthEmpty() throws Exception { + * System.out.println("Testing update table without authentication"); createTable(); + * + * JsonUpdate jsonUpdate = new JsonUpdate(); Map consistencyInfo = new HashMap<>(); + * MultivaluedMap row = new MultivaluedMapImpl(); Map values = new HashMap<>(); + * row.add("emp_name", "testname"); values.put("emp_salary", 2500); consistencyInfo.put("type", "atomic"); + * jsonUpdate.setConsistencyInfo(consistencyInfo); jsonUpdate.setKeyspaceName(keyspaceName); + * jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values); + * + * Mockito.when(info.getQueryParameters()).thenReturn(row); String authDatax =":"+password; String authorizationx = + * new String(Base64.encode(authDatax.getBytes())); String appNamex="xx"; Response response = data.updateTable("1", + * "1", "1", "", appNamex, authorizationx, jsonUpdate, keyspaceName, tableName, info); System.out.println("Status: " + * + response.getStatus() + ". Entity " + response.getEntity()); + * + * assertEquals(401, response.getStatus()); } + * + */ + + private static void createKeyspace() throws Exception { + // shouldn't really be doing this here, but create keyspace is currently turned off + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString(CassandraCQL.createKeySpace); + MusicCore.eventualPut(query); + + boolean isAAF = false; + String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); + query = new PreparedQueryObject(); + query.appendQueryString("INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); + query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + MusicCore.eventualPut(query); + } + + private void clearAllTablesFromKeyspace() throws MusicServiceException { + ArrayList tableNames = new ArrayList<>(); + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString( + "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '" + keyspaceName + "';"); + ResultSet rs = MusicCore.get(query); + for (Row row : rs) { + tableNames.add(row.getString("table_name")); + } + for (String table : tableNames) { + query = new PreparedQueryObject(); + query.appendQueryString("DROP TABLE " + keyspaceName + "." + table); + MusicCore.eventualPut(query); + } + } + + /** + * Create a table {@link tableName} in {@link keyspaceName} + * + * @throws Exception + */ + private void createTable() throws Exception { + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("id", "text"); + fields.put("plans", "map"); + fields.put("PRIMARY KEY", "(id)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("id"); + jsonTable.setTableName(tableName); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableName); + } + + /** + * Create table {@link createTable} and insert into said table + * + * @throws Exception + */ + private void createAndInsertIntoTable() throws Exception { + createTable(); + + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + JsonConditional jsonCond = new JsonConditional(); + Map values = new HashMap<>(); + values.put("id", "test_id"); + HashMap cascadeData = new HashMap<>(); + HashMap cascadeValue = new HashMap<>(); + cascadeValue.put("created", "hello"); + cascadeValue.put("updated", "world"); + cascadeData.put("key", "p1"); + cascadeData.put("value", cascadeValue); + HashMap> condition = new HashMap<>(); + HashMap exists = new HashMap<>(); + exists.put("status", "parked"); + HashMap nonexists = new HashMap<>(); + nonexists.put("status", "underway"); + condition.put("exists", exists); + condition.put("nonexists", nonexists); + + jsonCond.setPrimaryKey("id"); + jsonCond.setPrimaryKeyValue("test_id"); + jsonCond.setCasscadeColumnName("plans"); + jsonCond.setTableValues(values); + jsonCond.setCasscadeColumnData(cascadeData); + jsonCond.setConditions(condition); + + Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, keyspaceName, tableName, jsonCond); + } +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java b/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java new file mode 100644 index 00000000..407d0323 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java @@ -0,0 +1,1161 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +import static org.junit.Assert.assertEquals; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mindrot.jbcrypt.BCrypt; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.rest.RestMusicDataAPI; +import org.onap.music.rest.RestMusicLocksAPI; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.sun.jersey.core.util.Base64; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +@RunWith(MockitoJUnitRunner.class) +public class TstRestMusicDataAPI { + + RestMusicDataAPI data = new RestMusicDataAPI(); + RestMusicLocksAPI lock = new RestMusicLocksAPI(); + static PreparedQueryObject testObject; + + @Mock + HttpServletResponse http; + + @Mock + UriInfo info; + + static String appName = "TestApp"; + static String userId = "TestUser"; + static String password = "TestPassword"; + static String authData = userId + ":" + password; + static String wrongAuthData = userId + ":" + "pass"; + static String authorization = new String(Base64.encode(authData.getBytes())); + static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); + static boolean isAAF = false; + static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); + static String keyspaceName = "testcassa"; + static String tableName = "employees"; + static String xLatestVersion = "X-latestVersion"; + static String onboardUUID = null; + static String aid = TestsUsingCassandra.aid; + + @BeforeClass + public static void init() throws Exception { + System.out.println("Testing RestMusicData class"); + try { + createKeyspace(); + } catch (Exception e) { + e.printStackTrace(); + throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage()); + } + } + + @After + public void afterEachTest() throws MusicServiceException { + clearAllTablesFromKeyspace(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + testObject = new PreparedQueryObject(); + testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); + MusicCore.eventualPut(testObject); + } + + @Test + public void test1_createKeyspace() throws Exception { + System.out.println("Testing create keyspace"); + JsonKeySpace jsonKeyspace = new JsonKeySpace(); + Map consistencyInfo = new HashMap<>(); + Map replicationInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + replicationInfo.put("class", "SimpleStrategy"); + replicationInfo.put("replication_factor", 1); + jsonKeyspace.setConsistencyInfo(consistencyInfo); + jsonKeyspace.setDurabilityOfWrites("true"); + jsonKeyspace.setKeyspaceName(keyspaceName); + jsonKeyspace.setReplicationInfo(replicationInfo); + // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = + data.createKeySpace("1", "1", "1", null, authorization, appName, jsonKeyspace, keyspaceName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + Map respMap = (Map) response.getEntity(); + assertEquals(ResultType.FAILURE, respMap.get("status")); + } + + @Test + public void test1_createKeyspaceSuccess() throws Exception { + System.out.println("Testing successful creation and deletion of keyspace"); + MusicUtil.setKeyspaceActive(true); + + String keyspaceToCreate = "temp"+keyspaceName; + + + JsonKeySpace jsonKeyspace = new JsonKeySpace(); + Map consistencyInfo = new HashMap<>(); + Map replicationInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + replicationInfo.put("class", "SimpleStrategy"); + replicationInfo.put("replication_factor", 1); + jsonKeyspace.setConsistencyInfo(consistencyInfo); + jsonKeyspace.setDurabilityOfWrites("true"); + //don't overwrite a keyspace we already have + jsonKeyspace.setKeyspaceName(keyspaceToCreate); + jsonKeyspace.setReplicationInfo(replicationInfo); + // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = + data.createKeySpace("1", "1", "1", null, authorization, appName, jsonKeyspace, keyspaceToCreate); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + Map respMap = (Map) response.getEntity(); + assertEquals(ResultType.SUCCESS, respMap.get("status")); + + response = data.dropKeySpace("1", "1", "1", null, authorization, appName, keyspaceToCreate); + assertEquals(200, response.getStatus()); + respMap = (Map) response.getEntity(); + assertEquals(ResultType.SUCCESS, respMap.get("status")); + + //unset to not mess up any further tests + MusicUtil.setKeyspaceActive(false); + } + + @Test + public void test3_createTable() throws Exception { + System.out.println("Testing create table"); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableName); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + @Test + public void test3_createTableNoBody() throws Exception { + System.out.println("Testing create table w/o body"); + + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, null, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test3_createTableNoName() throws Exception { + System.out.println("Testing create table without name"); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(""); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, ""); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test3_createTableNoFields() throws Exception { + System.out.println("Testing create table without fields"); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(""); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, ""); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + + @Test + public void test3_createTableClusterOrderBad() throws Exception { + System.out.println("Testing create table bad clustering"); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name,emp_salary)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name,emp_salary"); + jsonTable.setClusteringOrder("ASC"); + jsonTable.setTableName(tableName); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test3_createTable_withPropertiesNotNull() throws Exception { + System.out.println("Testing create table with properties"); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + Map properties = new HashMap<>(); + properties.put("comment", "Testing prperties not null"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + String tableName_prop = tableName + "_Prop"; + jsonTable.setTableName(tableName_prop); + jsonTable.setFields(fields); + jsonTable.setProperties(properties); + + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableName_prop); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + @Test + public void test3_createTable_duplicateTable() throws Exception { + System.out.println("Testing creating duplicate tables"); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + String tableNameDup = tableName + "x"; + jsonTable.setTableName(tableNameDup); + jsonTable.setFields(fields); + // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response1 = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameDup); + + Response response2 = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameDup); + System.out.println("Status: " + response2.getStatus() + ". Entity " + response2.getEntity()); + + assertEquals(400, response2.getStatus()); + Map respMap = (Map) response2.getEntity(); + assertEquals(ResultType.FAILURE, respMap.get("status")); + assertEquals("AlreadyExistsException: Table " + keyspaceName + "." + tableNameDup + " already exists", respMap.get("error")); + } + + + // Improper parenthesis in key field + @Test + public void test3_createTable_badParanthesis() throws Exception { + System.out.println("Testing malformed create table request"); + String tableNameC = "testTable0"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name),emp_id)"); + fields.put("emp_id", "varint"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_id Desc"); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameC); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + + // good clustering key + @Test + public void test3_createTable_1_clusterKey_good() throws Exception { + System.out.println("Testing create w/ clusterKey"); + + String tableNameC = "testTableC1"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name),emp_salary)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + // jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_salary ASC"); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameC); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + // bad partition key=clustering key + @Test + public void test3_createTable_2_clusterKey_bad() throws Exception { + System.out.println("Testing create w/ bad clusterKey"); + String tableNameC = "testTableC2"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name),emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); // "PRIMARY KEY" overrides if primaryKey present + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_salary ASC"); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameC); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + // good composite partition key,clustering key + @Test + public void test3_createTable_3_pfartition_clusterKey_good() throws Exception { + System.out.println("Testing create w/ composite partition key, clusterKey"); + + String tableNameC = "testTableC3"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "varint"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name,emp_id),emp_salary)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_salary ASC"); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameC); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + // bad - wrong cols in order by of composite partition key,clustering key + @Test + public void test3_createTable_5_clusteringOrder_bad() throws Exception { + System.out.println("Testing create table bad request with clustering & composite keys"); + String tableNameC = "testTableC5"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_id", "varint"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((uuid,emp_name),emp_id,emp_salary)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_idx desc, emp_salary ASC"); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameC); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + + // good clustering key, need to pass queryparameter + @Test + public void test3_createTableIndex_1() throws Exception { + System.out.println("Testing index in create table"); + String tableNameC = "testTableCinx"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name),emp_salary)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_salary ASC"); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameC); + // if 200 print to log otherwise fail assertEquals(200, response.getStatus()); + // info.setQueryParameters("index_name=inx_uuid"); + Map queryParametersMap = new HashMap(); + + queryParametersMap.put("index_name", "inxuuid"); + Mockito.when(info.getQueryParameters()).thenReturn(new MultivaluedHashMap(queryParametersMap)); + response = data.createIndex("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + keyspaceName, tableNameC, "uuid", info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + // create index without table name + @Test + public void test3_createTableIndexNoName() throws Exception { + System.out.println("Testing index in create table w/o tablename"); + String tableNameC = "testTableCinx"; + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "((emp_name),emp_salary)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setTableName(tableNameC); + jsonTable.setClusteringOrder("emp_salary ASC"); + jsonTable.setFields(fields); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableNameC); + // if 200 print to log otherwise fail assertEquals(200, response.getStatus()); + // info.setQueryParameters("index_name=inx_uuid"); + Map queryParametersMap = new HashMap(); + + queryParametersMap.put("index_name", "inxuuid"); + response = data.createIndex("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, "", + "", "uuid", info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test4_insertIntoTable() throws Exception { + System.out.println("Testing insert into table"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname"); + values.put("emp_salary", 500); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + @Test + public void test4_insertIntoTableNoBody() throws Exception { + System.out.println("Testing insert into table w/o body"); + createTable(); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, null, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test4_insertIntoTableNoaValues() throws Exception { + System.out.println("Testing insert into table"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test4_insertIntoTableNoValues() throws Exception { + System.out.println("Testing insert into table"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test4_insertIntoTableCriticalNoLockID() throws Exception { + System.out.println("Testing critical insert into table without lockid"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname"); + values.put("emp_salary", 500); + consistencyInfo.put("type", "critical"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test4_insertIntoTableAtomic() throws Exception { + System.out.println("Testing atomic insert into table without lockid"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname"); + values.put("emp_salary", 500); + consistencyInfo.put("type", "atomic"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + @Test + public void test4_insertIntoTableNoName() throws Exception { + System.out.println("Testing insert into table w/o table name"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname"); + values.put("emp_salary", 500); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, "", ""); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test4_insertIntoTable2() throws Exception { + System.out.println("Testing insert into table #2"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "test1"); + values.put("emp_salary", 1500); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + // Table wrong + @Test + public void test4_insertIntoTable4() throws Exception { + System.out.println("Testing insert into wrong table"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "test1"); + values.put("emp_salary", 1500); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, "wrong"); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test4_insertBlobIntoTable() throws Exception { + System.out.println("Testing insert a blob into table"); + createTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname"); + values.put("emp_salary", 500); + values.put("binary", "somestuffhere"); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + @Test + public void test5_updateTable() throws Exception { + System.out.println("Testing update table"); + createTable(); + + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + Map values = new HashMap<>(); + row.add("emp_name", "testname"); + values.put("emp_salary", 2500); + consistencyInfo.put("type", "atomic"); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName(tableName); + jsonUpdate.setValues(values); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, keyspaceName, tableName, info); + + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + + public void test5_updateTableNoBody() throws Exception { + System.out.println("Testing update table no body"); + createTable(); + + Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, null, keyspaceName, tableName, info); + + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test5_updateTable_tableDNE() throws Exception { + System.out.println("Testing update table that does not exist"); + createTable(); + + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("emp_salary", 2500); + consistencyInfo.put("type", "atomic"); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName("wrong_"+tableName); + jsonUpdate.setValues(values); + Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, keyspaceName, "wrong_"+ tableName, info); + + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test5_updateTableNoName() throws Exception { + System.out.println("Testing update table without tablename"); + createTable(); + + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("emp_salary", 2500); + consistencyInfo.put("type", "atomic"); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName(tableName); + jsonUpdate.setValues(values); + Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, "", "", info); + + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + // need mock code to create error for MusicCore methods + @Test + public void test5_updateTableAuthE() throws Exception { + System.out.println("Testing update table #2"); + createTable(); + // MockitoAnnotations.initMocks(this); + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + Map values = new HashMap<>(); + row.add("emp_name", "testname"); + values.put("emp_salary", 2500); + consistencyInfo.put("type", "atomic"); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName(tableName); + jsonUpdate.setValues(values); + // add ttl & timestamp + // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Mockito.when(info.getQueryParameters()).thenReturn(row); + // Map m1= new HashMap<>() ; + // Mockito.when(MusicCore.autheticateUser(appName,userId,password,keyspaceName,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6","updateTable")).thenReturn(m1); + Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, keyspaceName, tableName, info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + @Test + public void test6_critical_selectAtomic() throws Exception { + System.out.println("Testing critical select atomic"); + createAndInsertIntoTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testname"); + consistencyInfo.put("type", "atomic"); + jsonInsert.setConsistencyInfo(consistencyInfo); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, keyspaceName, tableName,info); + HashMap> map = (HashMap>) response.getEntity(); + HashMap result = map.get("result"); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + Map row0 = (Map) result.get("row 0"); + assertEquals("testname", row0.get("emp_name")); + assertEquals(BigInteger.valueOf(500), row0.get("emp_salary")); + } + + + @Test + public void test6_critical_select() throws Exception { + System.out.println("Testing critical select w/o body"); + createAndInsertIntoTable(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testname"); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, null, keyspaceName, tableName,info); + HashMap> map = (HashMap>) response.getEntity(); + HashMap result = map.get("result"); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + // Added during merge? + @Test + public void test6_critical_selectCritical_nolockid() throws Exception { + System.out.println("Testing critical select critical w/o lockid"); + createAndInsertIntoTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testname"); + consistencyInfo.put("type", "critical"); + jsonInsert.setConsistencyInfo(consistencyInfo); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, keyspaceName, tableName,info); + HashMap> map = (HashMap>) response.getEntity(); + HashMap result = map.get("result"); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test6_critical_select_nulltable() throws Exception { + System.out.println("Testing critical select w/ null tablename"); + createAndInsertIntoTable(); + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "atomic"); + jsonInsert.setConsistencyInfo(consistencyInfo); + Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, authorization, jsonInsert, keyspaceName, null,info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test6_select() throws Exception { + System.out.println("Testing select"); + createAndInsertIntoTable(); + JsonSelect jsonSelect = new JsonSelect(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testname"); + consistencyInfo.put("type", "atomic"); + jsonSelect.setConsistencyInfo(consistencyInfo); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = data.selectWithCritical("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, + null,keyspaceName, tableName, info); + HashMap> map = (HashMap>) response.getEntity(); + HashMap result = map.get("result"); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + Map row0 = (Map) result.get("row 0"); + assertEquals("testname", row0.get("emp_name")); + assertEquals(BigInteger.valueOf(500), row0.get("emp_salary")); + } + + @Test + public void test6_select_nullTablename() throws Exception { + System.out.println("Testing select w/ null tablename"); + createAndInsertIntoTable(); + JsonSelect jsonSelect = new JsonSelect(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "atomic"); + jsonSelect.setConsistencyInfo(consistencyInfo); + Response response = data.selectWithCritical("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", + appName, wrongAuthorization,null, keyspaceName, null, info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test6_deleteFromTable() throws Exception { + System.out.println("Testing delete from table"); + createAndInsertIntoTable(); + JsonDelete jsonDelete = new JsonDelete(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "test1"); + consistencyInfo.put("type", "atomic"); + jsonDelete.setConsistencyInfo(consistencyInfo); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonDelete, keyspaceName, tableName, info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + @Test + public void test6_deleteFromTable_missingTablename() throws Exception { + System.out.println("Testing delete from table w/ null tablename"); + createAndInsertIntoTable(); + JsonDelete jsonDelete = new JsonDelete(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "atomic"); + jsonDelete.setConsistencyInfo(consistencyInfo); + Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + wrongAuthorization, jsonDelete, keyspaceName, null, info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + // Values + @Ignore + @Test + public void test6_deleteFromTable1() throws Exception { + System.out.println("Testing delete from table missing delete object"); + createAndInsertIntoTable(); + + JsonDelete jsonDelete = new JsonDelete(); + Map consistencyInfo = new HashMap<>(); + MultivaluedMap row = new MultivaluedMapImpl(); + consistencyInfo.put("type", "atomic"); + jsonDelete.setConsistencyInfo(consistencyInfo); + Mockito.when(info.getQueryParameters()).thenReturn(row); + Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonDelete, keyspaceName, tableName, info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + // delObj + @Test + public void test6_deleteFromTable2() throws Exception { + System.out.println("Testing delete from table missing delete object"); + createAndInsertIntoTable(); + JsonDelete jsonDelete = new JsonDelete(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "atomic"); + jsonDelete.setConsistencyInfo(consistencyInfo); + Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, null, keyspaceName, tableName, info); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test7_dropTable() throws Exception { + System.out.println("Testing drop table"); + createTable(); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "atomic"); + jsonTable.setConsistencyInfo(consistencyInfo); + Response response = data.dropTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, keyspaceName, tableName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + } + + @Test + public void test7_dropTable_nullTablename() throws Exception { + System.out.println("Testing drop table w/ null tablename"); + createTable(); + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "atomic"); + jsonTable.setConsistencyInfo(consistencyInfo); + Response response = data.dropTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, keyspaceName, null); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + + @Test + public void test8_deleteKeyspace() throws Exception { + System.out.println("Testing drop keyspace"); + + JsonKeySpace jsonKeyspace = new JsonKeySpace(); + Map consistencyInfo = new HashMap<>(); + Map replicationInfo = new HashMap<>(); + consistencyInfo.put("type", "eventual"); + replicationInfo.put("class", "SimpleStrategy"); + replicationInfo.put("replication_factor", 1); + jsonKeyspace.setConsistencyInfo(consistencyInfo); + jsonKeyspace.setDurabilityOfWrites("true"); + jsonKeyspace.setKeyspaceName("TestApp1"); + jsonKeyspace.setReplicationInfo(replicationInfo); + Response response = data.dropKeySpace("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", authorization, + appName, keyspaceName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + private static void createKeyspace() throws Exception { + // shouldn't really be doing this here, but create keyspace is currently turned off + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString(CassandraCQL.createKeySpace); + MusicCore.eventualPut(query); + + boolean isAAF = false; + String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); + query = new PreparedQueryObject(); + query.appendQueryString("INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); + query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + MusicCore.eventualPut(query); + } + + private void clearAllTablesFromKeyspace() throws MusicServiceException { + ArrayList tableNames = new ArrayList<>(); + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString( + "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '" + keyspaceName + "';"); + ResultSet rs = MusicCore.get(query); + for (Row row : rs) { + tableNames.add(row.getString("table_name")); + } + for (String table : tableNames) { + query = new PreparedQueryObject(); + query.appendQueryString("DROP TABLE " + keyspaceName + "." + table); + MusicCore.eventualPut(query); + } + } + + /** + * Create a table {@link tableName} in {@link keyspaceName} + * + * @throws Exception + */ + private void createTable() throws Exception { + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("binary", "blob"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableName); + jsonTable.setFields(fields); + // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableName); + } + + /** + * Create table {@link createTable} and insert into said table + * + * @throws Exception + */ + private void createAndInsertIntoTable() throws Exception { + createTable(); + + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname"); + values.put("emp_salary", 500); + values.put("binary", "binarydatahere"); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + } +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java b/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java new file mode 100644 index 00000000..e9321d25 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java @@ -0,0 +1,768 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mindrot.jbcrypt.BCrypt; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonLeasedLock; +import org.onap.music.datastore.jsonobjects.JsonLock; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.rest.RestMusicDataAPI; +import org.onap.music.rest.RestMusicLocksAPI; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.sun.jersey.core.util.Base64; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +@RunWith(MockitoJUnitRunner.class) +public class TstRestMusicLockAPI { + + + @Mock + UriInfo info; + + RestMusicLocksAPI lock = new RestMusicLocksAPI(); + RestMusicDataAPI data = new RestMusicDataAPI(); + static PreparedQueryObject testObject; + + static String appName = "TestApp"; + static String userId = "TestUser"; + static String password = "TestPassword"; + static String authData = userId + ":" + password; + static String wrongAuthData = userId + ":" + "pass"; + static String authorization = new String(Base64.encode(authData.getBytes())); + static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); + static boolean isAAF = false; + static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); + static String keyspaceName = "testcassa"; + static String tableName = "employees"; + static String onboardUUID = null; + static String lockName = "testcassa.employees.testname"; + + @BeforeClass + public static void init() throws Exception { + System.out.println("Testing RestMusicLock class"); + try { + createKeyspace(); + } catch (Exception e) { + e.printStackTrace(); + throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage()); + } + } + + @After + public void afterEachTest() throws MusicServiceException { + clearAllTablesFromKeyspace(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + testObject = new PreparedQueryObject(); + testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); + MusicCore.eventualPut(testObject); + } + + @SuppressWarnings("unchecked") + @Test + public void test_createLockReference() throws Exception { + System.out.println("Testing create lockref"); + createAndInsertIntoTable(); + Response response = lock.createLockReference(lockName, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", null, null, appName); + Map respMap = (Map) response.getEntity(); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + assertTrue(respMap.containsKey("lock")); + assertTrue(((Map) respMap.get("lock")).containsKey("lock")); + } + + @Test + public void test_createBadLockReference() throws Exception { + System.out.println("Testing create bad lockref"); + createAndInsertIntoTable(); + Response response = lock.createLockReference("badlock", "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", null, null, appName); + Map respMap = (Map) response.getEntity(); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test_createReadLock() throws Exception { + System.out.println("Testing create read lockref"); + createAndInsertIntoTable(); + JsonLock jsonLock = createJsonLock(LockType.READ); + Response response = lock.createLockReference(lockName, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", jsonLock, null, appName); + Map respMap = (Map) response.getEntity(); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + assertTrue(respMap.containsKey("lock")); + assertTrue(((Map) respMap.get("lock")).containsKey("lock")); + } + + @Test + public void test_createWriteLock() throws Exception { + System.out.println("Testing create read lockref"); + createAndInsertIntoTable(); + JsonLock jsonLock = createJsonLock(LockType.WRITE); + Response response = lock.createLockReference(lockName, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", jsonLock, null, appName); + Map respMap = (Map) response.getEntity(); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + + assertEquals(200, response.getStatus()); + assertTrue(respMap.containsKey("lock")); + assertTrue(((Map) respMap.get("lock")).containsKey("lock")); + } + + @Test + public void test_accquireLock() throws Exception { + System.out.println("Testing acquire lock"); + createAndInsertIntoTable(); + String lockRef = createLockReference(); + + Response response = + lock.accquireLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + @Test + public void test_acquireReadLock() throws Exception { + System.out.println("Testing acquire read lock"); + createAndInsertIntoTable(); + String lockRef = createLockReference(LockType.READ); + String lockRef2 = createLockReference(LockType.READ); + + Response response = + lock.accquireLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + response = + lock.accquireLock(lockRef2, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + @Test + public void test_acquireReadLockaFail() throws Exception { + System.out.println("Testing acquire read lock"); + createAndInsertIntoTable(); + String lockRef = createLockReference(LockType.WRITE); + String lockRef2 = createLockReference(LockType.READ); + + Response response = + lock.accquireLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + response = + lock.accquireLock(lockRef2, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_writeWReadLock() throws Exception { + System.out.println("Testing writing with a read lock"); + createAndInsertIntoTable(); + String lockRef = createLockReference(LockType.READ); + + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("emp_salary", 2500); + consistencyInfo.put("type", "critical"); + consistencyInfo.put("lockId", lockRef); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName(tableName); + jsonUpdate.setValues(values); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testname"); + Mockito.when(info.getQueryParameters()).thenReturn(row); + + Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, keyspaceName, tableName, info); + + assertEquals(400, response.getStatus()); + } + + @Test + public void test_writeWWriteLock() throws Exception { + System.out.println("Testing writing with a read lock"); + createAndInsertIntoTable(); + String lockRef = createLockReference(LockType.WRITE); + + JsonUpdate jsonUpdate = new JsonUpdate(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("emp_salary", 2500); + consistencyInfo.put("type", "critical"); + consistencyInfo.put("lockId", lockRef); + jsonUpdate.setConsistencyInfo(consistencyInfo); + jsonUpdate.setKeyspaceName(keyspaceName); + jsonUpdate.setTableName(tableName); + jsonUpdate.setValues(values); + MultivaluedMap row = new MultivaluedMapImpl(); + row.add("emp_name", "testname"); + Mockito.when(info.getQueryParameters()).thenReturn(row); + + Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonUpdate, keyspaceName, tableName, info); + + assertEquals(200, response.getStatus()); + } + + @Test + public void test_accquireLockWLease() throws Exception { + System.out.println("Testing acquire lock with lease"); + createAndInsertIntoTable(); + String lockRef = createLockReference(); + + JsonLeasedLock jsonLock = new JsonLeasedLock(); + jsonLock.setLeasePeriod(10000); // 10 second lease period? + Response response = lock.accquireLockWithLease(jsonLock, lockRef, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + @Test + public void test_accquireBadLockWLease() throws Exception { + System.out.println("Testing acquire bad lock ref with lease"); + createAndInsertIntoTable(); + String lockRef = createLockReference(); + + JsonLeasedLock jsonLock = new JsonLeasedLock(); + jsonLock.setLeasePeriod(10000); // 10 second lease period? + Response response = lock.accquireLockWithLease(jsonLock, "badlock", "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_accquireBadLock() throws Exception { + System.out.println("Testing acquire lock that is not lock-holder"); + createAndInsertIntoTable(); + // This is required to create an initial loc reference. + String lockRef1 = createLockReference(); + // This will create the next lock reference, whcih will not be avalale yet. + String lockRef2 = createLockReference(); + + Response response = lock.accquireLock(lockRef2, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_accquireBadLockRef() throws Exception { + System.out.println("Testing acquire bad lock ref"); + createAndInsertIntoTable(); + // This is required to create an initial loc reference. + String lockRef1 = createLockReference(); + + Response response = lock.accquireLock("badlockref", "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_currentLockHolder() throws Exception { + System.out.println("Testing get current lock holder"); + createAndInsertIntoTable(); + + String lockRef = createLockReference(); + + Response response = + lock.enquireLock(lockName, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + Map respMap = (Map) response.getEntity(); + assertEquals(lockRef, ((Map) respMap.get("lock")).get("lock-holder")); + } + + @Test + public void test_nocurrentLockHolder() throws Exception { + System.out.println("Testing get current lock holder w/ bad lockref"); + createAndInsertIntoTable(); + + Response response = + lock.enquireLock(lockName, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_badcurrentLockHolder() throws Exception { + System.out.println("Testing get current lock holder w/ bad lockref"); + createAndInsertIntoTable(); + + String lockRef = createLockReference(); + + Response response = + lock.enquireLock("badlock", "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_holders() throws Exception { + System.out.println("Testing holders api"); + createAndInsertIntoTable(); + + String lockRef = createLockReference(); + + Response response = + lock.currentLockHolder(lockName, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + Map respMap = (Map) response.getEntity(); + assertEquals(lockRef, ((Map) respMap.get("lock")).get("lock-holder").get(0)); + } + + @Test + public void test_holdersbadRef() throws Exception { + System.out.println("Testing holders api w/ bad lockref"); + createAndInsertIntoTable(); + + String lockRef = createLockReference(); + + Response response = + lock.currentLockHolder("badname", "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_unLock() throws Exception { + System.out.println("Testing unlock"); + createAndInsertIntoTable(); + String lockRef = createLockReference(); + + Response response = + lock.unLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + @Test + public void test_unLockBadRef() throws Exception { + System.out.println("Testing unlock w/ bad lock ref"); + createAndInsertIntoTable(); + String lockRef = createLockReference(); + + Response response = + lock.unLock("badref", "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @Test + public void test_getLockState() throws Exception { + System.out.println("Testing get lock state"); + createAndInsertIntoTable(); + + String lockRef = createLockReference(); + + Response response = lock.currentLockState(lockName, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + Map respMap = (Map) response.getEntity(); + assertEquals(lockRef, ((Map) respMap.get("lock")).get("lock-holder")); + } + + @Test + public void test_getLockStateBadRef() throws Exception { + System.out.println("Testing get lock state w/ bad ref"); + createAndInsertIntoTable(); + + String lockRef = createLockReference(); + + Response response = lock.currentLockState("badname", "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(400, response.getStatus()); + } + + @SuppressWarnings("unchecked") + @Test + public void test_deadlock() throws Exception { + System.out.println("Testing deadlock"); + createAndInsertIntoTable(); + insertAnotherIntoTable(); + + // Process 1 creates and acquires a lock on row 1 + JsonLock jsonLock = createJsonLock(LockType.WRITE); + Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process1", appName); + Map respMapCreate1 = (Map) responseCreate1.getEntity(); + String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); + + Response responseAcquire1 = + lock.accquireLock(lockRefCreate1, "1", "1", authorization, "abc66001-d857-4e90-b1e5-df98a3d40ce6", appName); + + // Process 2 creates and acquires a lock on row 2 + Response responseCreate2 = lock.createLockReference(lockName + "2", "1", "1", authorization, + "abcde002-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process2", appName); + Map respMapCreate2 = (Map) responseCreate2.getEntity(); + String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); + + Response responseAcquire2 = + lock.accquireLock(lockRefCreate2, "1", "1", authorization, "abc66002-d857-4e90-b1e5-df98a3d40ce6", appName); + + // Process 2 creates a lock on row 1 + Response responseCreate3 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde003-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process2", appName); + + // Process 1 creates a lock on row 2, causing deadlock + Response responseCreate4 = lock.createLockReference(lockName + "2", "1", "1", authorization, + "abcde004-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process1", appName); + Map respMapCreate4 = (Map) responseCreate4.getEntity(); + + System.out.println("Status: " + responseCreate4.getStatus() + ". Entity " + responseCreate4.getEntity()); + assertEquals(400, responseCreate4.getStatus()); + assertTrue(respMapCreate4.containsKey("error")); + assertTrue( ((String)respMapCreate4.get("error")).toLowerCase().indexOf("deadlock") > -1 ); + } + + + @SuppressWarnings("unchecked") + @Test + public void test_lockPromotion() throws Exception { + System.out.println("Testing lock promotion"); + createAndInsertIntoTable(); + insertAnotherIntoTable(); + + // creates a lock 1 + JsonLock jsonLock = createJsonLock(LockType.READ); + Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process1", appName); + Map respMapCreate1 = (Map) responseCreate1.getEntity(); + String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); + + Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); + System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); + + assertEquals(200, respMapPromote.getStatus()); + } + + @SuppressWarnings("unchecked") + @Test + public void test_lockPromotionReadWrite() throws Exception { + System.out.println("Testing lock promotion with read and writes"); + createAndInsertIntoTable(); + insertAnotherIntoTable(); + + // creates a lock 1 + JsonLock jsonLockRead = createJsonLock(LockType.READ); + Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); + Map respMapCreate1 = (Map) responseCreate1.getEntity(); + String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); + + JsonLock jsonLockWrite = createJsonLock(LockType.WRITE); + Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockWrite, "process1", appName); + Map respMapCreate2 = (Map) responseCreate2.getEntity(); + String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); + + Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); + System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); + + assertEquals(200, respMapPromote.getStatus()); + } + + @SuppressWarnings("unchecked") + @Test + public void test_lockPromotionWriteRead() throws Exception { + System.out.println("Testing lock promotion with reads not at top of queue"); + createAndInsertIntoTable(); + insertAnotherIntoTable(); + + // creates a lock 1 + JsonLock jsonLockWrite = createJsonLock(LockType.WRITE); + Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockWrite, "process1", appName); + Map respMapCreate2 = (Map) responseCreate2.getEntity(); + String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); + + // creates a lock 2 + JsonLock jsonLockRead = createJsonLock(LockType.READ); + Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); + Map respMapCreate1 = (Map) responseCreate1.getEntity(); + String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); + + Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); + System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); + + assertEquals(200, respMapPromote.getStatus()); + } + + @SuppressWarnings("unchecked") + @Test + public void test_lockPromotion2Reads() throws Exception { + System.out.println("Testing lock promotion w/ 2 ReadLocks"); + createAndInsertIntoTable(); + insertAnotherIntoTable(); + + // creates a lock 1 + JsonLock jsonLockRead = createJsonLock(LockType.READ); + Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); + Map respMapCreate1 = (Map) responseCreate1.getEntity(); + String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); + + Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); + Map respMapCreate2 = (Map) responseCreate1.getEntity(); + String lockRefCreate2 = ((Map) respMapCreate1.get("lock")).get("lock"); + + Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); + System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); + + assertEquals(400, respMapPromote.getStatus()); + } + + @SuppressWarnings("unchecked") + @Test + public void test_2lockPromotions() throws Exception { + System.out.println("Testing 2 lock promotions"); + createAndInsertIntoTable(); + insertAnotherIntoTable(); + + // creates a lock 1 + JsonLock jsonLockRead = createJsonLock(LockType.READ); + Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); + Map respMapCreate1 = (Map) responseCreate1.getEntity(); + String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); + + Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, + "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); + Map respMapCreate2 = (Map) responseCreate2.getEntity(); + String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); + + Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); + System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); + + assertEquals(400, respMapPromote.getStatus()); + + Response respMap2Promote = lock.promoteLock(lockRefCreate2, "1", "1", authorization); + System.out.println("Status: " + respMap2Promote.getStatus() + ". Entity " + respMap2Promote.getEntity()); + + assertEquals(400, respMapPromote.getStatus()); + } + + + + // Ignoring since this is now a duplicate of delete lock ref. + @Test + @Ignore + public void test_deleteLock() throws Exception { + System.out.println("Testing get lock state"); + createAndInsertIntoTable(); + + String lockRef = createLockReference(); + + Response response = lock.deleteLock(lockName, "1", "1", + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", authorization, appName); + System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); + assertEquals(200, response.getStatus()); + } + + /** + * Create table and lock reference + * + * @return the lock ref created + * @throws Exception + */ + @SuppressWarnings("unchecked") + private String createLockReference() throws Exception { + Response response = lock.createLockReference(lockName, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", null, null, appName); + Map respMap = (Map) response.getEntity(); + return ((Map) respMap.get("lock")).get("lock"); + } + + /** + * Create table and lock reference + * + * @return the lock ref created + * @throws Exception + */ + @SuppressWarnings("unchecked") + private String createLockReference(LockType lockType) throws Exception { + JsonLock jsonLock = createJsonLock(lockType); + Response response = lock.createLockReference(lockName, "1", "1", authorization, + "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", jsonLock, null, appName); + Map respMap = (Map) response.getEntity(); + return ((Map) respMap.get("lock")).get("lock"); + } + + private static void createKeyspace() throws Exception { + // shouldn't really be doing this here, but create keyspace is currently turned off + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString(CassandraCQL.createKeySpace); + MusicCore.eventualPut(query); + + boolean isAAF = false; + String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); + query = new PreparedQueryObject(); + query.appendQueryString("INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); + query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); + query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + //CachingUtil.updateMusicCache(keyspaceName, appName); + //CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd); + MusicCore.eventualPut(query); + } + + private void clearAllTablesFromKeyspace() throws MusicServiceException { + ArrayList tableNames = new ArrayList<>(); + PreparedQueryObject query = new PreparedQueryObject(); + query.appendQueryString( + "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '" + keyspaceName + "';"); + ResultSet rs = MusicCore.get(query); + for (Row row : rs) { + tableNames.add(row.getString("table_name")); + } + for (String table : tableNames) { + query = new PreparedQueryObject(); + query.appendQueryString("DROP TABLE " + keyspaceName + "." + table); + MusicCore.eventualPut(query); + } + } + + /** + * Create a table {@link tableName} in {@link keyspaceName} + * + * @throws Exception + */ + private void createTable() throws Exception { + JsonTable jsonTable = new JsonTable(); + Map consistencyInfo = new HashMap<>(); + Map fields = new HashMap<>(); + fields.put("uuid", "text"); + fields.put("emp_name", "text"); + fields.put("emp_salary", "varint"); + fields.put("PRIMARY KEY", "(emp_name)"); + consistencyInfo.put("type", "eventual"); + jsonTable.setConsistencyInfo(consistencyInfo); + jsonTable.setKeyspaceName(keyspaceName); + jsonTable.setPrimaryKey("emp_name"); + jsonTable.setTableName(tableName); + jsonTable.setFields(fields); + // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); + Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonTable, keyspaceName, tableName); + } + + /** + * Create table {@link createTable} and insert into said table + * + * @throws Exception + */ + private void createAndInsertIntoTable() throws Exception { + createTable(); + + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname"); + values.put("emp_salary", 500); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + } + + private void insertAnotherIntoTable() throws Exception { + createTable(); + + JsonInsert jsonInsert = new JsonInsert(); + Map consistencyInfo = new HashMap<>(); + Map values = new HashMap<>(); + values.put("uuid", "cccccccc-d857-4e90-b1e5-df98a3d40cd6"); + values.put("emp_name", "testname2"); + values.put("emp_salary", 700); + consistencyInfo.put("type", "eventual"); + jsonInsert.setConsistencyInfo(consistencyInfo); + jsonInsert.setKeyspaceName(keyspaceName); + jsonInsert.setTableName(tableName); + jsonInsert.setValues(values); + Response response = data.insertIntoTable("1", "1", "1", "abcdef00-d857-4e90-b1e5-df98a3d40ce6", appName, + authorization, jsonInsert, keyspaceName, tableName); + } + + private JsonLock createJsonLock(LockType lockType) { + JsonLock jsonLock = new JsonLock(); + jsonLock.setLockType(lockType); + return jsonLock; + } + +} \ No newline at end of file diff --git a/music-rest/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java b/music-rest/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java new file mode 100644 index 00000000..b578bd66 --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java @@ -0,0 +1,123 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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.music.unittests.authentication; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.List; +import javax.servlet.ServletRequest; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aaf.cadi.CadiWrap; +import org.onap.aaf.cadi.Permission; +import org.onap.aaf.cadi.aaf.AAFPermission; +import org.onap.music.authentication.AuthUtil; + +public class AuthUtilTest { + + @Test + public void testGetAAFPermissions() { + CadiWrap cw = Mockito.mock(CadiWrap.class); + List permList = new ArrayList(); + Permission perm1 = Mockito.mock(AAFPermission.class); + permList.add(perm1); + Mockito.when(cw.getPermissions(Mockito.any())).thenReturn(permList); + + List returnedPerm = AuthUtil.getAAFPermissions(cw); + + assertEquals(perm1, returnedPerm.get(0)); + } + + @Test + public void testDecodeFunctionCode() throws Exception { + String toDecode = "some%2dthing.something.%2a"; + String decoded = AuthUtil.decodeFunctionCode(toDecode); + + assertEquals("some-thing.something.*", decoded); + } + + @Test + public void testIsAccessAllowed() throws Exception { + System.out.println("Request perms"); + assertTrue(AuthUtil.isAccessAllowed(createRequest("*", "*"), "testns")); + } + + @Test + public void testIsAccessNotAllowed() throws Exception { + System.out.println("Request to write when have read perms"); + assertFalse(AuthUtil.isAccessAllowed(createRequest("POST", "GET"), "testns")); + } + + @Test + public void testIsAccessAllowedNullRequest() { + try { + assertFalse(AuthUtil.isAccessAllowed(null, "namespace")); + fail("Should throw exception"); + } catch (Exception e) { + } + } + + @Test + public void testIsAccessAllowedNullNamespace() { + try { + assertFalse(AuthUtil.isAccessAllowed(createRequest(), null)); + fail("Should throw exception"); + } catch (Exception e) { + } + } + + @Test + public void testIsAccessAllowedEmptyNamespace() { + try { + assertFalse(AuthUtil.isAccessAllowed(createRequest(), "")); + fail("Should throw exception"); + } catch (Exception e) { + } + } + + /** + * + * @param permRequested 'PUT', 'POST', 'GET', or 'DELETE' + * @param permGranted '*' or 'GET' + * @return + */ + private ServletRequest createRequest(String permRequested, String permGranted) { + CadiWrap cw = Mockito.mock(CadiWrap.class); + List permList = new ArrayList(); + AAFPermission perm1 = Mockito.mock(AAFPermission.class); + Mockito.when(perm1.getType()).thenReturn("testns"); + Mockito.when(perm1.getKey()).thenReturn("org.onap.music.api.user.access|testns|" + permGranted); + + permList.add(perm1); + Mockito.when(cw.getPermissions(Mockito.any())).thenReturn(permList); + Mockito.when(cw.getRequestURI()).thenReturn("/v2/locks/create/testns.MyTable.Field1"); + Mockito.when(cw.getContextPath()).thenReturn("/v2/locks/create"); + Mockito.when(cw.getMethod()).thenReturn(permRequested); + + return cw; + } + + private ServletRequest createRequest() { + return createRequest("POST","*"); + } +} diff --git a/music-rest/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java b/music-rest/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java new file mode 100644 index 00000000..b432072a --- /dev/null +++ b/music-rest/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests.authentication; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.onap.music.authentication.AuthorizationError; + +public class AuthorizationErrorTest { + + private AuthorizationError authorizationError; + + @Before + public void setUp() { + authorizationError = new AuthorizationError(); + } + + @Test + public void testResponseCode() { + authorizationError.setResponseCode(400); + assertEquals(400, authorizationError.getResponseCode()); + } + + @Test + public void testResponseMessage() { + authorizationError.setResponseMessage("ResponseMessage"); + assertEquals("ResponseMessage", authorizationError.getResponseMessage()); + } +} diff --git a/music-rest/src/test/resources/logback.xml b/music-rest/src/test/resources/logback.xml new file mode 100644 index 00000000..6bc5fd5e --- /dev/null +++ b/music-rest/src/test/resources/logback.xml @@ -0,0 +1,302 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + ${logDirectory}/${generalLogName}.log + + + ${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip + 1GB + 5 + 5GB + + + ${applicationLoggerPattern} + + + + + 256 + true + + + + + + ${logDirectory}/${securityLogName}.log + + ${logDirectory}/${securityLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + 256 + 0 + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${auditLoggerPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + + ${metricsLoggerPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${errorLoggerPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 8864c0be..c3895add 100755 --- a/pom.xml +++ b/pom.xml @@ -26,10 +26,10 @@ 4.0.0 org.onap.music MUSIC - jar - 3.2.36-SNAPSHOT + pom + 3.2.37-SNAPSHOT - This is the MUSIC REST interface, packaged as a Springboot jar file. + This is the MUSIC project. @@ -39,35 +39,11 @@ - - - - - org.springframework.boot - spring-boot-dependencies - 2.1.1.RELEASE - pom - import - - - - org.onap.music.MusicApplication UTF-8 UTF-8 UTF-8 1.8 - 1.19 - 2.25.1 - 2.0.1 - 3.6.0 - - UTF-8 - UTF-8 https://nexus.onap.org https://nexus.onap.org @@ -110,430 +86,6 @@ - - ${project.artifactId} - src/main/java - src/main/webapp/WEB-INF/classes - src/test/java - target/test-classes - validate - - - src/main/resources - true - - **/*.properties - **/*.xml - **/*.ccf - - - - - - ${project.basedir}/src/test/resources - - - - - - org.springframework.boot - spring-boot-maven-plugin - 2.1.1.RELEASE - - org.onap.music.MusicApplication - ./distribution/music/ - true - ${project.artifactId}-SB - - - - install - - repackage - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - ${maven.check.skip} - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - make-a-jar - compile - - jar - - - - - **/Sample* - - - - - - - org.apache.maven.plugins - maven-install-plugin - 2.4 - - - base - install - - install-file - - - jar - ${project.artifactId} - ${project.groupId} - ${project.version} - ${project.build.directory}/${project.artifactId}.jar - - - - spring - install - - install-file - - - jar - ${project.artifactId}-SB - ${project.groupId} - ${project.version} - ${project.basedir}/distribution/music/${project.artifactId}-SB.jar - - - - - - - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.data - spring-data-cassandra - - - org.springframework.boot - spring-boot-starter-jersey - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework - spring-aop - compile - - - org.springframework.boot - spring-boot-autoconfigure - - - org.aspectj - aspectjweaver - compile - - - - - javax.servlet - servlet-api - 2.4 - provided - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - - - ch.qos.logback - logback-core - 1.2.3 - - - org.slf4j - slf4j-log4j12 - - - - - ch.qos.logback - logback-classic - 1.2.3 - - - org.slf4j - slf4j-log4j12 - - - - - com.att.eelf - eelf-core - 1.0.1-oss - - - org.powermock - powermock-api-mockito - - - org.powermock - powermock-module-junit4 - - - - - - - io.dropwizard.metrics - metrics-core - 4.1.0-rc3 - - - com.datastax.cassandra - cassandra-driver-core - ${cassandra.version} - - - com.datastax.cassandra - cassandra-driver-extras - ${cassandra.version} - - - - - com.sun.jersey - jersey-client - ${jersey1.version} - - - com.sun.jersey - jersey-server - ${jersey1.version} - - - com.sun.jersey - jersey-json - ${jersey1.version} - - - com.sun.jersey - jersey-servlet - ${jersey1.version} - - - - - org.apache.commons - commons-jcs-core - 2.2 - - - commons-codec - commons-codec - 1.11 - - - org.apache.commons - commons-lang3 - 3.8 - - - - - junit - junit - 4.12 - test - - - org.cassandraunit - cassandra-unit-spring - 3.5.0.1 - test - - - org.slf4j - slf4j-log4j12 - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - org.cassandraunit - cassandra-unit - - - io.dropwizard.metrics - metrics-core - - - com.addthis.metrics - reporter-config-base - - - - - org.cassandraunit - cassandra-unit-shaded - 3.5.0.1 - test - - - org.mockito - mockito-core - 2.23.4 - test - - - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - 2.9.9 - - - com.fasterxml.jackson.core - jackson-databind - 2.9.9.2 - - - com.fasterxml.jackson.core - jackson-core - 2.9.9 - - - com.fasterxml.jackson.core - jackson-annotations - 2.9.9 - - - org.apache.httpcomponents - httpclient - - - io.swagger - swagger-jersey-jaxrs - 1.5.22 - - - com.google.guava - guava - - - de.svenkubiak - jBCrypt - 0.4.1 - - - io.netty - netty-handler - 4.1.33.Final - - - io.netty - netty-buffer - 4.1.33.Final - - - io.netty - netty-codec - 4.1.33.Final - - - io.netty - netty-common - 4.1.33.Final - - - io.netty - netty-resolver - 4.1.33.Final - - - io.netty - netty-transport - 4.1.33.Final - - - org.onap.aaf.authz - aaf-cadi-aaf - 2.1.7 - - - log4j - log4j - - - - - org.onap.aaf.authz - aaf-cadi-client - 2.1.7 - - - org.onap.aaf.authz - aaf-cadi-core - 2.1.7 - - - com.google.code.gson - gson - 2.8.5 - - - @@ -680,4 +232,8 @@ dav:${nexusproxy}${sitePath} + + music-core + music-rest + diff --git a/src/main/java/LICENSE.txt b/src/main/java/LICENSE.txt deleted file mode 100644 index cc6cdea5..00000000 --- a/src/main/java/LICENSE.txt +++ /dev/null @@ -1,24 +0,0 @@ - -The following license applies to all files in this and sub-directories. Licenses -are included in individual source files where appropriate, and if it differs -from this text, it supersedes this. Any file that does not have license text -defaults to being covered by this text; not all files support the addition of -licenses. -# -# ------------------------------------------------------------------------- -# Copyright (c) 2017 AT&T Intellectual Property -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ------------------------------------------------------------------------- -# \ No newline at end of file diff --git a/src/main/java/org/onap/music/JerseyConfig.java b/src/main/java/org/onap/music/JerseyConfig.java deleted file mode 100755 index b64e7044..00000000 --- a/src/main/java/org/onap/music/JerseyConfig.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music; - -import io.swagger.jaxrs.config.BeanConfig; -import io.swagger.jaxrs.listing.ApiListingResource; -import io.swagger.jaxrs.listing.SwaggerSerializers; - -import javax.annotation.PostConstruct; - -import org.glassfish.jersey.server.ResourceConfig; -import org.onap.music.conductor.conditionals.RestMusicConditionalAPI; -import org.onap.music.exceptions.MusicExceptionMapper; -import org.onap.music.rest.RestMusicDataAPI; -import org.onap.music.rest.RestMusicHealthCheckAPI; -import org.onap.music.rest.RestMusicLocksAPI; -import org.onap.music.rest.RestMusicQAPI; -import org.onap.music.rest.RestMusicTestAPI; -import org.onap.music.rest.RestMusicVersionAPI; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -public class JerseyConfig extends ResourceConfig { - - @Value("${spring.jersey.application-path:/}") - private String apiPath; - - public JerseyConfig() { - this.registerEndpoints(); - register(MusicExceptionMapper.class); - } - - @PostConstruct - public void init() { - this.configureSwagger(); - } - - private void registerEndpoints() { - register(RestMusicDataAPI.class); - register(RestMusicLocksAPI.class); - register(RestMusicConditionalAPI.class); - register(RestMusicQAPI.class); - register(RestMusicTestAPI.class); - register(RestMusicVersionAPI.class); - register(RestMusicHealthCheckAPI.class); - - } - - private void configureSwagger() { - // Available at localhost:port/swagger.json - this.register(ApiListingResource.class); - this.register(SwaggerSerializers.class); - - BeanConfig config = new BeanConfig(); - config.setConfigId("MUSIC"); - config.setTitle("MUSIC"); - config.setVersion("v2"); - config.setContact("Thomas Nelson"); - config.setSchemes(new String[] {"http", "https"}); - config.setBasePath("/MUSIC/rest"); - config.setResourcePackage("org.onap.music"); - config.setPrettyPrint(true); - config.setScan(true); - } - -} diff --git a/src/main/java/org/onap/music/MusicApplication.java b/src/main/java/org/onap/music/MusicApplication.java deleted file mode 100755 index 22c9e7bf..00000000 --- a/src/main/java/org/onap/music/MusicApplication.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.onap.aaf.cadi.PropAccess; -import org.onap.music.authentication.CadiAuthFilter; -import org.onap.music.authentication.MusicAuthorizationFilter; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.MusicLoggingServletFilter; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.PropertiesLoader; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.DependsOn; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.web.context.request.RequestContextListener; - -@SpringBootApplication(scanBasePackages = { "org.onap.music.rest"}) -@EnableAutoConfiguration(exclude = { CassandraDataAutoConfiguration.class }) -@ComponentScan(value = { "org.onap.music" }) -@EnableScheduling -public class MusicApplication extends SpringBootServletInitializer { - - private static final String KEYSPACE_PATTERN = "/v2/keyspaces/*"; - private static final String LOCKS_PATTERN = "/v2/locks/*"; - private static final String Q_PATTERN = "/v2/priorityq/*"; - - @Autowired - private PropertiesLoader propertyLoader; - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicApplication.class); - - - public static void main(String[] args) { - new MusicApplication().configure(new SpringApplicationBuilder(MusicApplication.class)).run(args); - } - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - - return application.sources(MusicApplication.class); - } - - @Bean("loadProperties") - public void loadProperties() { - propertyLoader.loadProperties(); - } - - - @Bean - @DependsOn("loadProperties") - public PropAccess propAccess() { - if (MusicUtil.getIsCadi()) { - return new PropAccess(new String[] { - "cadi_prop_files=/opt/app/music/etc/cadi.properties" }); - } else { - return null; - } - } - - @Bean(name = "cadiFilter") - @DependsOn("loadProperties") - public Filter cadiFilter() throws ServletException { - propertyLoader.loadProperties(); - if (MusicUtil.getIsCadi()) { - PropAccess propAccess = propAccess(); - return new CadiAuthFilter(propAccess); - } else { - return (ServletRequest request, ServletResponse response, FilterChain chain) -> { - // do nothing for now. - }; - } - } - - /** - * Added for capturing custom header values from client. - * - * order is set to 1 for this filter - * - * sp931a - * - * @return - * @throws ServletException - */ - @Bean(name="logFilter") - @DependsOn("loadProperties") - public FilterRegistrationBean loggingFilterRegistration() throws ServletException { - logger.info("loggingFilterRegistration called for log filter.."); - propertyLoader.loadProperties(); - FilterRegistrationBean frb = new FilterRegistrationBean<>(); - frb.setFilter(new MusicLoggingServletFilter()); - frb.addUrlPatterns( - KEYSPACE_PATTERN, - LOCKS_PATTERN, - Q_PATTERN - ); - frb.setName("logFilter"); - frb.setOrder(1); - return frb; - } - - @Bean - @DependsOn("loadProperties") - public FilterRegistrationBean cadiFilterRegistration() throws ServletException { - logger.info("cadiFilterRegistration called for cadi filter.."); - FilterRegistrationBean frb = new FilterRegistrationBean<>(); - frb.setFilter(cadiFilter()); - if (MusicUtil.getIsCadi()) { - frb.addUrlPatterns( - KEYSPACE_PATTERN, - LOCKS_PATTERN, - Q_PATTERN - ); - } else { - frb.addUrlPatterns("/v0/test"); - } - frb.setName("cadiFilter"); - frb.setOrder(2); - return frb; - } - - - /** - * Added for Authorization using CADI - * - * sp931a - * - * @return - * @throws ServletException - */ - @Bean - @DependsOn("loadProperties") - public FilterRegistrationBean cadiFilterRegistrationForAuth() throws ServletException { - logger.info("cadiFilterRegistrationForAuth called for cadi auth filter.."); - FilterRegistrationBean frb = new FilterRegistrationBean<>(); - frb.setFilter(cadiMusicAuthFilter()); - - if (MusicUtil.getIsCadi()) { - frb.addUrlPatterns( - KEYSPACE_PATTERN, - LOCKS_PATTERN, - Q_PATTERN - ); - } else { - frb.addUrlPatterns("/v0/test"); - } - frb.setName("cadiMusicAuthFilter"); - frb.setOrder(3); - return frb; - } - - @Bean(name = "cadiMusicAuthFilter") - @DependsOn("loadProperties") - public Filter cadiMusicAuthFilter() throws ServletException { - propertyLoader.loadProperties(); - if (MusicUtil.getIsCadi()) { - return new MusicAuthorizationFilter(); - } else { - return (ServletRequest request, ServletResponse response, FilterChain chain) -> { - // do nothing for now. - }; - } - } - - @Bean - @ConditionalOnMissingBean(RequestContextListener.class) - public RequestContextListener requestContextListener() { - return new RequestContextListener(); - } -} diff --git a/src/main/java/org/onap/music/authentication/AuthUtil.java b/src/main/java/org/onap/music/authentication/AuthUtil.java deleted file mode 100644 index ee3b77a4..00000000 --- a/src/main/java/org/onap/music/authentication/AuthUtil.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.authentication; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.regex.Pattern; - -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.onap.aaf.cadi.CadiWrap; -import org.onap.aaf.cadi.Permission; -import org.onap.aaf.cadi.aaf.AAFPermission; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.exceptions.MusicAuthenticationException; - -public class AuthUtil { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AuthUtil.class); - - private AuthUtil() { - throw new IllegalStateException("Utility class"); - } - - /** - * Get the list of permissions from the Request object. - * - * - * @param request servlet request object - * @return returns list of AAFPermission of the requested MechId for all the - * namespaces - */ - public static List getAAFPermissions(ServletRequest request) { - CadiWrap wrapReq = (CadiWrap) request; - - List perms = wrapReq.getPermissions(wrapReq.getUserPrincipal()); - List aafPermsList = new ArrayList<>(); - for (Permission perm : perms) { - AAFPermission aafPerm = (AAFPermission) perm; - aafPermsList.add(aafPerm); - } - return aafPermsList; - } - - /** - * Here is a sample of a permission object in AAI. The key attribute will have - * Type|Instance|Action. - * AAFPermission: - * NS: null - * Type: org.onap.music.cadi.keyspace ( Permission Type ) - * Instance: tomtest ( Cassandra Keyspace ) - * Action: *|GET|ALL ( Access Level [*|ALL] for full access and [GET] for Read only) - * Key: org.onap.music.cadi.keyspace|tomtest|* - * - * This method will filter all permissions whose key starts with the requested namespace. - * The nsamespace here is the music namespace which is defined in music.property file. - * i;e is the type contains in key is org.onap.music.cadi.keyspace and the namespace - * value is org.onap.music.cadi.keyspace, it will add to list - * otherwise reject. - * - * @param nameSpace - * @param allPermissionsList - * @return - */ - private static List filterNameSpacesAAFPermissions(String nameSpace, - List allPermissionsList) { - List list = new ArrayList<>(); - for (Iterator iterator = allPermissionsList.iterator(); iterator.hasNext();) { - AAFPermission aafPermission = iterator.next(); - if(aafPermission.getType().indexOf(nameSpace) == 0) { - list.add(aafPermission); - } - } - return list; - } - - /** - * Decode certian characters from url encoded to normal. - * - * @param str - String being decoded. - * @return returns the decoded string. - * @throws Exception throws excpetion - */ - public static String decodeFunctionCode(String str) throws MusicAuthenticationException { - final String DECODEVALUE_FORWARDSLASH = "2f"; - final String DECODEVALUE_HYPHEN = "2d"; - final String DECODEVALUE_ASTERISK = "2a"; - String decodedString = str; - List decodingList = new ArrayList<>(); - decodingList.add(Pattern.compile(DECODEVALUE_FORWARDSLASH)); - decodingList.add(Pattern.compile(DECODEVALUE_HYPHEN)); - decodingList.add(Pattern.compile(DECODEVALUE_ASTERISK)); - for (Pattern xssInputPattern : decodingList) { - try { - decodedString = decodedString.replaceAll("%" + xssInputPattern, - new String(Hex.decodeHex(xssInputPattern.toString().toCharArray()))); - } catch (DecoderException e) { - logger.error(EELFLoggerDelegate.securityLogger, - "AuthUtil Decode Failed! for instance: " + str); - throw new MusicAuthenticationException("Decode failed", e); - } - } - - return decodedString; - } - - /** - * - * - * @param request servlet request object - * @param nameSpace application namespace - * @return boolean value if the access is allowed - * @throws Exception throws exception - */ - public static boolean isAccessAllowed(ServletRequest request, String nameSpace) throws MusicAuthenticationException { - - if (request==null) { - throw new MusicAuthenticationException("Request cannot be null"); - } - - if (nameSpace==null || nameSpace.isEmpty()) { - throw new MusicAuthenticationException("NameSpace not Declared!"); - } - - boolean isauthorized = false; - List aafPermsList = getAAFPermissions(request); - logger.info(EELFLoggerDelegate.securityLogger, - "AAFPermission of the requested MechId for all the namespaces: " + aafPermsList); - logger.debug(EELFLoggerDelegate.securityLogger, "Requested nameSpace: " + nameSpace); - - List aafPermsFinalList = filterNameSpacesAAFPermissions(nameSpace, aafPermsList); - - logger.debug(EELFLoggerDelegate.securityLogger, - "AuthUtil list of AAFPermission for the specific namespace :::" - + aafPermsFinalList); - - HttpServletRequest httpRequest = (HttpServletRequest) request; - String requestUri = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length() + 1); - - logger.debug(EELFLoggerDelegate.securityLogger, - "AuthUtil requestUri :::" + requestUri); - - for (Iterator iterator = aafPermsFinalList.iterator(); iterator.hasNext();) { - AAFPermission aafPermission = iterator.next(); - if(!isauthorized) { - isauthorized = isMatchPattern(aafPermission, requestUri, httpRequest.getMethod()); - } - } - - logger.debug(EELFLoggerDelegate.securityLogger, - "isAccessAllowed for the request uri: " + requestUri + "is :" + isauthorized); - return isauthorized; - } - - /** - * - * This method will check, if the requested URI matches any of the instance - * found with the AAF permission list. - * i;e if the request URI is; /v2/keyspaces/tomtest/tables/emp15 and in the - * AAF permission table, we have an instance - * defined as "tomtest" mapped the logged in user, it will allow else error. - * - * User trying to create or aquire a lock - * Here is the requested URI /v2/locks/create/tomtest.MyTable.Field1 - * Here the keyspace name i;e tomtest will be test throught out the URL if it - * matches, it will allow the user to create a lock. - * "tomtest" here is the key, which is mapped as an instance in permission object. - * Instance can be delimited with ":" i;e ":music-cassandra-1908-dev:admin". In this case, - * each delimited - * token will be matched with that of request URI. - * - * Example Permission: - * org.onap.music.api.user.access|tomtest|* or ALL - * org.onap.music.api.user.access|tomtest|GET - * In case of the action field is ALL and *, user will be allowed else it will - * be matched with the requested http method type. - * - * - * - * @param aafPermission - AAfpermission obtained by cadi. - * @param requestUri - Rest URL client is calling. - * @param method - REST Method being used (GET,POST,PUT,DELETE) - * @return returns a boolean - * @throws Exception - throws an exception - */ - private static boolean isMatchPattern( - AAFPermission aafPermission, - String requestUri, - String method) throws MusicAuthenticationException { - if (null == aafPermission || null == requestUri || null == method) { - return false; - } - - String permKey = aafPermission.getKey(); - - logger.debug(EELFLoggerDelegate.securityLogger, "isMatchPattern permKey: " - + permKey + ", requestUri " + requestUri + " ," + method); - - String[] keyArray = permKey.split("\\|"); - String[] subPath = null; - String instance = keyArray[1]; - String action = keyArray[2]; - - //if the instance & action both are * , then allow - if ("*".equalsIgnoreCase(instance) && "*".equalsIgnoreCase(action)) { - return true; - } - //Decode string like %2f, %2d and %2a - if (!"*".equals(instance)) { - instance = decodeFunctionCode(instance); - } - if (!"*".equals(action)) { - action = decodeFunctionCode(action); - } - //Instance: :music-cassandra-1908-dev:admin - List instanceList = Arrays.asList(instance.split(":")); - - String[] path = requestUri.split("/"); - - for (int i = 0; i < path.length; i++) { - // Sometimes the value will begin with "$", so we need to remove it - if (path[i].startsWith("$")) { - path[i] = path[i].replace("$",""); - } - // Each path element can again delemited by ".";i;e - // tomtest.tables.emp. We have scenarios like lock aquire URL - subPath = path[i].split("\\."); - for (int j = 0; j < subPath.length; j++) { - if (instanceList.contains(subPath[j])) { - return checkAction(method,action); - } else { - continue; - } - } - } - return false; - } - - private static boolean checkAction(String method, String action) { - if ("*".equals(action) || "ALL".equalsIgnoreCase(action)) { - return true; - } else { - return (method.equalsIgnoreCase(action)); - } - } - - - -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/authentication/AuthorizationError.java b/src/main/java/org/onap/music/authentication/AuthorizationError.java deleted file mode 100644 index 7015b550..00000000 --- a/src/main/java/org/onap/music/authentication/AuthorizationError.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.authentication; - - -/** - * Authorization error class used while setting error code and description back to client. - * - * - * @author sp931a - * - */ -public class AuthorizationError { - - private int responseCode; - - private String responseMessage; - - public int getResponseCode() { - return responseCode; - } - - public void setResponseCode(int responseCode) { - this.responseCode = responseCode; - } - - public String getResponseMessage() { - return responseMessage; - } - - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } - -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/authentication/CadiAuthFilter.java b/src/main/java/org/onap/music/authentication/CadiAuthFilter.java deleted file mode 100644 index d043e6d6..00000000 --- a/src/main/java/org/onap/music/authentication/CadiAuthFilter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.authentication; - - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.annotation.WebFilter; - -import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.filter.CadiFilter; -import org.onap.music.eelf.logging.EELFLoggerDelegate; - -@WebFilter(urlPatterns = { "/*" }) -public class CadiAuthFilter extends CadiFilter { - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CadiAuthFilter.class); - - public CadiAuthFilter(PropAccess access) throws ServletException { - super(true, access); - } - - public CadiAuthFilter() throws ServletException { - super(); - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - super.init(filterConfig); - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - logger.info(EELFLoggerDelegate.securityLogger, "Request is entering cadifilter"); - long startTime = System.currentTimeMillis(); - request.setAttribute("startTime", startTime); - super.doFilter(request, response, chain); - } -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java b/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java deleted file mode 100644 index bde3e205..00000000 --- a/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.authentication; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; - -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.exceptions.MusicAuthenticationException; -import org.onap.music.main.MusicUtil; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * This filter class does authorization from AAF - * - * @author sp931a - * - */ -//@PropertySource(value = {"file:/opt/app/music/etc/music.properties"}) -public class MusicAuthorizationFilter implements Filter { - - private String musicNS = MusicUtil.getMusicAafNs(); - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthorizationFilter.class); - - public MusicAuthorizationFilter() throws ServletException { - super(); - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - // Do Nothing - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { - HttpServletResponse httpResponse = null; - - boolean isAuthAllowed = false; - - if (null != servletRequest && null != servletResponse) { - httpResponse = (HttpServletResponse) servletResponse; - long startTime = 0; - if( null != servletRequest.getAttribute("startTime")) { - startTime = ((Long)servletRequest.getAttribute("startTime")).longValue(); - } else { - startTime = System.currentTimeMillis(); // this will set only incase the request attribute not found - } - - try { - isAuthAllowed = AuthUtil.isAccessAllowed(servletRequest, musicNS); - } catch (MusicAuthenticationException e) { - logger.error(EELFLoggerDelegate.securityLogger, - "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage(),e); - } catch ( Exception e) { - logger.error(EELFLoggerDelegate.securityLogger, - "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage(),e); - } - - long endTime = System.currentTimeMillis(); - - //startTime set in CadiAuthFilter doFilter - logger.debug(EELFLoggerDelegate.securityLogger, - "Time took for authentication & authorization : " - + (endTime - startTime) + " milliseconds"); - - if (!isAuthAllowed) { - logger.info(EELFLoggerDelegate.securityLogger, - "Unauthorized Access"); - AuthorizationError authError = new AuthorizationError(); - authError.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); - authError.setResponseMessage("Unauthorized Access - Please make sure you are " - + "onboarded and have proper access to MUSIC. "); - - byte[] responseToSend = restResponseBytes(authError); - httpResponse.setHeader("Content-Type", "application/json"); - - httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - servletResponse.getOutputStream().write(responseToSend); - return; - } else { - filterChain.doFilter(servletRequest, servletResponse); - } - } - } - - private byte[] restResponseBytes(AuthorizationError eErrorResponse) throws IOException { - String serialized = new ObjectMapper().writeValueAsString(eErrorResponse); - return serialized.getBytes(); - } -} - diff --git a/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java b/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java deleted file mode 100644 index 4efcabea..00000000 --- a/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.conductor.conditionals; - -import java.io.Serializable; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; - -@ApiModel(value = "JsonConditional", description = "Json model for insert or update into table based on some conditions") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonConditional implements Serializable { - - private String primaryKey; - private String primaryKeyValue; - private String casscadeColumnName; - private Map tableValues; - private Map casscadeColumnData; - private Map> conditions; - - public Map getTableValues() { - return tableValues; - } - public void setTableValues(Map tableValues) { - this.tableValues = tableValues; - } - - public String getPrimaryKey() { - return primaryKey; - } - public String getPrimaryKeyValue() { - return primaryKeyValue; - } - public String getCasscadeColumnName() { - return casscadeColumnName; - } - - public Map getCasscadeColumnData() { - return casscadeColumnData; - } - - - - public void setPrimaryKey(String primaryKey) { - this.primaryKey = primaryKey; - } - public void setPrimaryKeyValue(String primaryKeyValue) { - this.primaryKeyValue = primaryKeyValue; - } - public Map> getConditions() { - return conditions; - } - public void setConditions(Map> conditions) { - this.conditions = conditions; - } - public void setCasscadeColumnName(String casscadeColumnName) { - this.casscadeColumnName = casscadeColumnName; - } - - public void setCasscadeColumnData(Map casscadeColumnData) { - this.casscadeColumnData = casscadeColumnData; - } - - - - - -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java b/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java deleted file mode 100644 index 18fa8a18..00000000 --- a/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (C) 2019 IBM. - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.conductor.conditionals; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; - -import org.codehaus.jettison.json.JSONObject; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.rest.RestMusicDataAPI; - -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.TableMetadata; - -public class MusicConditional { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); - - public static ReturnType conditionalInsert(String keyspace, String tablename, String casscadeColumnName, - Map casscadeColumnData, String primaryKey, Map valuesMap, - Map status) throws Exception { - - Map queryBank = new HashMap<>(); - TableMetadata tableInfo = null; - tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); - DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); - String primaryId = tableInfo.getPrimaryKey().get(0).getName(); - DataType casscadeColumnType = tableInfo.getColumn(casscadeColumnName).getType(); - String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - - PreparedQueryObject select = new PreparedQueryObject(); - select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?"); - select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey)); - queryBank.put(MusicUtil.SELECT, select); - - PreparedQueryObject update = new PreparedQueryObject(); - //casscade column values - Map updateColumnvalues = getValues(true, casscadeColumnData, status); - Object formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, updateColumnvalues); - update.appendQueryString("UPDATE " + keyspace + "." + tablename + " SET " + casscadeColumnName + " =" - + casscadeColumnName + " + ? , vector_ts = ?" + " WHERE " + primaryId + " = ? "); - update.addValue(formatedValues); - update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector)); - update.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey)); - queryBank.put(MusicUtil.UPDATE, update); - - - //casscade column values - Map insertColumnvalues = getValues(false, casscadeColumnData, status); - formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, insertColumnvalues); - PreparedQueryObject insert = extractQuery(valuesMap, tableInfo, tablename, keyspace, primaryId, primaryKey,casscadeColumnName,formatedValues); - queryBank.put(MusicUtil.INSERT, insert); - - - String key = keyspace + "." + tablename + "." + primaryKey; - String lockId; - try { - lockId = MusicCore.createLockReference(key); - } catch (MusicLockingException e) { - return new ReturnType(ResultType.FAILURE, e.getMessage()); - } - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod); - - try { - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - ReturnType criticalPutResult = conditionalInsertAtomic(lockId, keyspace, tablename, primaryKey, - queryBank); - MusicCore.destroyLockRef(lockId); - if (criticalPutResult.getMessage().contains("insert")) - criticalPutResult - .setMessage("Insert values: "); - else if (criticalPutResult.getMessage().contains("update")) - criticalPutResult - .setMessage("Update values: " + updateColumnvalues); - return criticalPutResult; - - } else { - MusicCore.destroyLockRef(lockId); - return lockAcqResult; - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.applicationLogger, e); - MusicCore.destroyLockRef(lockId); - return new ReturnType(ResultType.FAILURE, e.getMessage()); - } - - } - - public static ReturnType conditionalInsertAtomic(String lockId, String keyspace, String tableName, - String primaryKey, Map queryBank) { - - ResultSet results = null; - - try { - String fullyQualifiedKey = keyspace + "." + tableName + "." + primaryKey; - ReturnType lockAcqResult = MusicCore.acquireLock(fullyQualifiedKey, lockId); - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - try { - results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryBank.get(MusicUtil.SELECT)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.applicationLogger, e); - return new ReturnType(ResultType.FAILURE, e.getMessage()); - } - if (results.all().isEmpty()) { - MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), "critical"); - return new ReturnType(ResultType.SUCCESS, "insert"); - } else { - MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.UPDATE), "critical"); - return new ReturnType(ResultType.SUCCESS, "update"); - } - } else { - return new ReturnType(ResultType.FAILURE, - "Cannot perform operation since you are the not the lock holder"); - } - - } catch (Exception e) { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - String exceptionAsString = sw.toString(); - logger.error(EELFLoggerDelegate.applicationLogger, e); - return new ReturnType(ResultType.FAILURE, - "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" - + exceptionAsString); - } - - } - - public static ReturnType update(UpdateDataObject dataObj) - throws MusicLockingException, MusicQueryException, MusicServiceException { - - String key = dataObj.getKeyspace() + "." + dataObj.getTableName() + "." + dataObj.getPrimaryKeyValue(); - String lockId = MusicCore.createLockReference(key); - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod); - - try { - - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - ReturnType criticalPutResult = updateAtomic(new UpdateDataObject().setLockId(lockId) - .setKeyspace(dataObj.getKeyspace()) - .setTableName( dataObj.getTableName()) - .setPrimaryKey(dataObj.getPrimaryKey()) - .setPrimaryKeyValue(dataObj.getPrimaryKeyValue()) - .setQueryBank(dataObj.getQueryBank()) - .setPlanId(dataObj.getPlanId()) - .setCascadeColumnValues(dataObj.getCascadeColumnValues()) - .setCascadeColumnName(dataObj.getCascadeColumnName())); - - MusicCore.destroyLockRef(lockId); - return criticalPutResult; - } else { - MusicCore.destroyLockRef(lockId); - return lockAcqResult; - } - - } catch (Exception e) { - MusicCore.destroyLockRef(lockId); - logger.error(EELFLoggerDelegate.applicationLogger, e); - return new ReturnType(ResultType.FAILURE, e.getMessage()); - - } - } - - public static ReturnType updateAtomic(UpdateDataObject dataObj) { - try { - String fullyQualifiedKey = dataObj.getKeyspace() + "." + dataObj.getTableName() + "." + dataObj.getPrimaryKeyValue(); - ReturnType lockAcqResult = MusicCore.acquireLock(fullyQualifiedKey, dataObj.getLockId()); - - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - Row row = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(dataObj.getQueryBank().get(MusicUtil.SELECT)).one(); - - if(row != null) { - Map updatedValues = cascadeColumnUpdateSpecific(row, dataObj.getCascadeColumnValues(), dataObj.getCascadeColumnName(), dataObj.getPlanId()); - JSONObject json = new JSONObject(updatedValues); - PreparedQueryObject update = new PreparedQueryObject(); - String vector_ts = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - update.appendQueryString("UPDATE " + dataObj.getKeyspace() + "." + dataObj.getTableName() + " SET " + dataObj.getCascadeColumnName() + "['" + dataObj.getPlanId() - + "'] = ?, vector_ts = ? WHERE " + dataObj.getPrimaryKey() + " = ?"); - update.addValue(MusicUtil.convertToActualDataType(DataType.text(), json.toString())); - update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector_ts)); - update.addValue(MusicUtil.convertToActualDataType(DataType.text(), dataObj.getPrimaryKeyValue())); - try { - MusicDataStoreHandle.getDSHandle().executePut(update, "critical"); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.applicationLogger, ex); - return new ReturnType(ResultType.FAILURE, ex.getMessage()); - } - }else { - return new ReturnType(ResultType.FAILURE,"Cannot find data related to key: "+dataObj.getPrimaryKey()); - } - MusicDataStoreHandle.getDSHandle().executePut(dataObj.getQueryBank().get(MusicUtil.UPSERT), "critical"); - return new ReturnType(ResultType.SUCCESS, "update success"); - - } else { - return new ReturnType(ResultType.FAILURE, - "Cannot perform operation since you are the not the lock holder"); - } - - } catch (Exception e) { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - String exceptionAsString = sw.toString(); - logger.error(EELFLoggerDelegate.applicationLogger, e); - return new ReturnType(ResultType.FAILURE, - "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" - + exceptionAsString); - } - - } - - @SuppressWarnings("unchecked") - public static Map getValues(boolean isExists, Map casscadeColumnData, - Map status) { - - Map returnMap = new HashMap<>(); - Object key = casscadeColumnData.get("key"); - String setStatus = ""; - Map value = (Map) casscadeColumnData.get("value"); - - if (isExists) - setStatus = status.get("exists"); - else - setStatus = status.get("nonexists"); - - value.put("status", setStatus); - JSONObject valueJson = new JSONObject(value); - returnMap.put(key.toString(), valueJson.toString()); - return returnMap; - - } - - public static PreparedQueryObject extractQuery(Map valuesMap, TableMetadata tableInfo, String tableName, - String keySpaceName,String primaryKeyName,String primaryKey,String casscadeColumn,Object casscadeColumnValues) throws Exception { - - PreparedQueryObject queryObject = new PreparedQueryObject(); - StringBuilder fieldsString = new StringBuilder("(vector_ts"+","); - StringBuilder valueString = new StringBuilder("(" + "?" + ","); - String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - String localPrimaryKey; - queryObject.addValue(vector); - if(casscadeColumn!=null && casscadeColumnValues!=null) { - fieldsString.append(casscadeColumn).append(" ,"); - valueString.append("?,"); - queryObject.addValue(casscadeColumnValues); - } - - int counter = 0; - for (Map.Entry entry : valuesMap.entrySet()) { - - fieldsString.append(entry.getKey()); - Object valueObj = entry.getValue(); - if (primaryKeyName.equals(entry.getKey())) { - localPrimaryKey = entry.getValue() + ""; - localPrimaryKey = localPrimaryKey.replace("'", "''"); - } - DataType colType = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - } catch(NullPointerException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey(), - AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR, ex); - } - - Object formattedValue = null; - try { - formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e); - } - - valueString.append("?"); - queryObject.addValue(formattedValue); - - - if (counter == valuesMap.size() - 1) { - fieldsString.append(")"); - valueString.append(")"); - } else { - fieldsString.append(","); - valueString.append(","); - } - counter = counter + 1; - } - queryObject.appendQueryString("INSERT INTO " + keySpaceName + "." + tableName + " " - + fieldsString + " VALUES " + valueString); - return queryObject; - } - - public static Object getColValue(Row row, String colName, DataType colType) { - switch (colType.getName()) { - case VARCHAR: - return row.getString(colName); - case UUID: - return row.getUUID(colName); - case VARINT: - return row.getVarint(colName); - case BIGINT: - return row.getLong(colName); - case INT: - return row.getInt(colName); - case FLOAT: - return row.getFloat(colName); - case DOUBLE: - return row.getDouble(colName); - case BOOLEAN: - return row.getBool(colName); - case MAP: - return row.getMap(colName, String.class, String.class); - default: - return null; - } - } - - @SuppressWarnings("unchecked") - public static Map cascadeColumnUpdateSpecific(Row row, Map changeOfStatus, - String cascadeColumnName, String planId) { - - ColumnDefinitions colInfo = row.getColumnDefinitions(); - DataType colType = colInfo.getType(cascadeColumnName); - Object columnValue = getColValue(row, cascadeColumnName, colType); - - Map finalValues = new HashMap<>(); - Map values = (Map) columnValue; - if (values != null && values.keySet().contains(planId)) { - String valueString = values.get(planId); - String tempValueString = valueString.replaceAll("\\{", "").replaceAll("\"", "").replaceAll("\\}", ""); - String[] elements = tempValueString.split(","); - for (String str : elements) { - String[] keyValue = str.split(":"); - if ((changeOfStatus.keySet().contains(keyValue[0].replaceAll("\\s", "")))) - keyValue[1] = changeOfStatus.get(keyValue[0].replaceAll("\\s", "")); - finalValues.put(keyValue[0], keyValue[1]); - } - } - return finalValues; - - } - -} diff --git a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java b/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java deleted file mode 100644 index 584a9e47..00000000 --- a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2018 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.conductor.conditionals; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -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.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; - -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.response.jsonobjects.JsonResponse; -import org.onap.music.conductor.*; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TableMetadata; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiParam; - -@Path("/v2/conditional") -@Api(value = "Conditional Api", hidden = true) -public class RestMusicConditionalAPI { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicConditionalAPI.class); - private static final String XMINORVERSION = "X-minorVersion"; - private static final String XPATCHVERSION = "X-patchVersion"; - private static final String NS = "ns"; - private static final String VERSION = "v2"; - - @POST - @Path("/insert/keyspaces/{keyspace}/tables/{tablename}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response insertConditional( - @ApiParam(value = "Major Version", required = true) - @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) - @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version", required = false) - @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) - @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) - @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) - @HeaderParam("Authorization") String authorization, - @ApiParam(value = "Keyspace Name", required = true) - @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) - @PathParam("tablename") String tablename, - JsonConditional jsonObj) throws Exception { - ResponseBuilder response = - MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - String primaryKey = jsonObj.getPrimaryKey(); - String primaryKeyValue = jsonObj.getPrimaryKeyValue(); - String casscadeColumnName = jsonObj.getCasscadeColumnName(); - Map tableValues = jsonObj.getTableValues(); - Map casscadeColumnData = jsonObj.getCasscadeColumnData(); - Map> conditions = jsonObj.getConditions(); - - if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null - || tableValues.isEmpty() || casscadeColumnData.isEmpty() || conditions.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE) - .setError(String.valueOf("One or more input values missing")).toMap()).build(); - } - Map authMap = null; - Map valuesMap = new LinkedHashMap<>(); - for (Map.Entry entry : tableValues.entrySet()) { - valuesMap.put(entry.getKey(), entry.getValue()); - } - - Map status = new HashMap<>(); - status.put("exists", conditions.get("exists").get("status")); - status.put("nonexists", conditions.get("nonexists").get("status")); - ReturnType out = null; - - out = MusicConditional.conditionalInsert(keyspace, tablename, - casscadeColumnName, casscadeColumnData,primaryKeyValue, valuesMap, status); - return response.status(Status.OK).entity(new JsonResponse( - out.getResult()).setMessage(out.getMessage()).toMap()) - .build(); - - } - - @SuppressWarnings("unchecked") - @PUT - @Path("/update/keyspaces/{keyspace}/tables/{tablename}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response updateConditional( - @ApiParam(value = "Major Version", required = true) - @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) - @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version", required = false) - @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) - @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) - @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) - @HeaderParam("Authorization") String authorization, - @ApiParam(value = "Major Version", required = true) - @PathParam("keyspace") String keyspace, - @ApiParam(value = "Major Version", required = true) - @PathParam("tablename") String tablename, - JsonConditional upObj) throws Exception { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - String primaryKey = upObj.getPrimaryKey(); - String primaryKeyValue = upObj.getPrimaryKeyValue(); - String casscadeColumnName = upObj.getCasscadeColumnName(); - Map casscadeColumnData = upObj.getCasscadeColumnData(); - Map tableValues = upObj.getTableValues(); - - if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null - || casscadeColumnData.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE) - .setError(String.valueOf("One or more input values missing")).toMap()).build(); - - } - - Map casscadeColumnValueMap = - (Map) casscadeColumnData.get("value"); - TableMetadata tableInfo = null; - tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); - DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); - String primaryId = tableInfo.getPrimaryKey().get(0).getName(); - - PreparedQueryObject select = new PreparedQueryObject(); - select.appendQueryString("SELECT * FROM " + keyspace + "." - + tablename + " where " + primaryId + " = ?"); - select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue)); - - PreparedQueryObject upsert = - MusicConditional.extractQuery(tableValues, tableInfo, tablename, - keyspace, primaryKey, primaryKeyValue, null, null); - Map queryBank = new HashMap<>(); - queryBank.put(MusicUtil.SELECT, select); - queryBank.put(MusicUtil.UPSERT, upsert); - String planId = casscadeColumnData.get("key").toString(); - ReturnType result = MusicConditional.update(new UpdateDataObject().setQueryBank(queryBank) - .setKeyspace(keyspace) - .setTableName(tablename) - .setPrimaryKey(primaryKey) - .setPrimaryKeyValue(primaryKeyValue) - .setPlanId(planId) - .setCascadeColumnName(casscadeColumnName) - .setCascadeColumnValues(casscadeColumnValueMap)); - if (result.getResult() == ResultType.SUCCESS) { - return response.status(Status.OK) - .entity(new JsonResponse(result.getResult()) - .setMessage(result.getMessage()).toMap()).build(); - } - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(result.getResult()) - .setMessage(result.getMessage()).toMap()).build(); - - } - -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java b/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java deleted file mode 100644 index 1ea8994e..00000000 --- a/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Samsung Electronics Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.music.conductor.conditionals; - -import java.util.Map; -import org.onap.music.datastore.PreparedQueryObject; - -public class UpdateDataObject { - - Map queryBank; - String keyspace; - String tableName; - String primaryKey; - String primaryKeyValue; - String planId; - String cascadeColumnName; - Map cascadeColumnValues; - String lockId; - - public Map getQueryBank() { - return queryBank; - } - - public UpdateDataObject setQueryBank(Map queryBank) { - this.queryBank = queryBank; - return this; - } - - public String getKeyspace() { - return keyspace; - } - - public UpdateDataObject setKeyspace(String keyspace) { - this.keyspace = keyspace; - return this; - } - - public String getTableName() { - return tableName; - } - - public UpdateDataObject setTableName(String tableName) { - this.tableName = tableName; - return this; - } - - public String getPrimaryKey() { - return primaryKey; - } - - public UpdateDataObject setPrimaryKey(String primaryKey) { - this.primaryKey = primaryKey; - return this; - } - - public String getPrimaryKeyValue() { - return primaryKeyValue; - } - - public UpdateDataObject setPrimaryKeyValue(String primaryKeyValue) { - this.primaryKeyValue = primaryKeyValue; - return this; - } - - public String getPlanId() { - return planId; - } - - public UpdateDataObject setPlanId(String planId) { - this.planId = planId; - return this; - } - - public String getCascadeColumnName() { - return cascadeColumnName; - } - - public UpdateDataObject setCascadeColumnName(String cascadeColumnName) { - this.cascadeColumnName = cascadeColumnName; - return this; - } - - public Map getCascadeColumnValues() { - return cascadeColumnValues; - } - - public UpdateDataObject setLockId(String lockId) { - this.lockId=lockId; - return this; - } - - public String getLockId() { - return lockId; - } - - public UpdateDataObject setCascadeColumnValues(Map cascadeColumnValues) { - this.cascadeColumnValues = cascadeColumnValues; - return this; - } - - -} diff --git a/src/main/java/org/onap/music/datastore/Condition.java b/src/main/java/org/onap/music/datastore/Condition.java deleted file mode 100644 index 6587748e..00000000 --- a/src/main/java/org/onap/music/datastore/Condition.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.datastore; - -import java.util.Map; - -import org.onap.music.main.MusicCore; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; - -public class Condition { - private Map conditions; - private PreparedQueryObject selectQueryForTheRow; - - public Condition(Map conditions, PreparedQueryObject selectQueryForTheRow) { - this.conditions = conditions; - this.selectQueryForTheRow = selectQueryForTheRow; - } - - public boolean testCondition() throws Exception { - // first generate the row - ResultSet results = MusicCore.quorumGet(selectQueryForTheRow); - Row row = null; - if(results != null) { - row = results.one(); - } - if(row == null) { - throw new Exception(" No data found to update"); - } - return MusicDataStoreHandle.getDSHandle().doesRowSatisfyCondition(row, conditions); - } - } \ No newline at end of file diff --git a/src/main/java/org/onap/music/datastore/MusicDataStore.java b/src/main/java/org/onap/music/datastore/MusicDataStore.java deleted file mode 100755 index 5a658688..00000000 --- a/src/main/java/org/onap/music/datastore/MusicDataStore.java +++ /dev/null @@ -1,523 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2018-2019 IBM - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.datastore; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.lockingservice.cassandra.LockType; -import org.onap.music.main.CipherUtil; -import org.onap.music.main.MusicUtil; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ColumnDefinitions.Definition; -import com.datastax.driver.core.ConsistencyLevel; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.HostDistance; -import com.datastax.driver.core.KeyspaceMetadata; -import com.datastax.driver.core.Metadata; -import com.datastax.driver.core.PoolingOptions; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.TableMetadata; -import com.datastax.driver.core.TypeCodec; -import com.datastax.driver.core.exceptions.AlreadyExistsException; -import com.datastax.driver.core.exceptions.InvalidQueryException; -import com.datastax.driver.core.exceptions.NoHostAvailableException; -import com.datastax.driver.extras.codecs.enums.EnumNameCodec; -import com.datastax.driver.extras.codecs.enums.EnumOrdinalCodec; - -/** - * @author nelson24 - * - */ -public class MusicDataStore { - - public static final String CONSISTENCY_LEVEL_ONE = "ONE"; - public static final String CONSISTENCY_LEVEL_QUORUM = "QUORUM"; - private Session session; - private Cluster cluster; - - - /** - * @param session - */ - public void setSession(Session session) { - this.session = session; - } - - /** - * @param session - */ - public Session getSession() { - return session; - } - - /** - * @param cluster - */ - public void setCluster(Cluster cluster) { - this.cluster = cluster; - } - - public Cluster getCluster() { - return this.cluster; - } - - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class); - - /** - * Connect to default Cassandra address - */ - public MusicDataStore() { - try { - connectToCassaCluster(MusicUtil.getMyCassaHost()); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); - } - } - - - /** - * @param cluster - * @param session - */ - public MusicDataStore(Cluster cluster, Session session) { - this.session = session; - this.cluster = cluster; - } - - /** - * - * @param remoteIp - * @throws MusicServiceException - */ - public MusicDataStore(String remoteIp) { - try { - connectToCassaCluster(remoteIp); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); - } - } - - /** - * - */ - public void close() { - session.close(); - } - - /** - * This method connects to cassandra cluster on specific address. - * - * @param address - */ - private void connectToCassaCluster(String address) throws MusicServiceException { - String[] addresses = null; - addresses = address.split(","); - PoolingOptions poolingOptions = new PoolingOptions(); - poolingOptions - .setConnectionsPerHost(HostDistance.LOCAL, 4, 10) - .setConnectionsPerHost(HostDistance.REMOTE, 2, 4); - - if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) { - String cassPwd = CipherUtil.decryptPKC(MusicUtil.getCassPwd()); - logger.info(EELFLoggerDelegate.applicationLogger, - "Building with credentials "+MusicUtil.getCassName()+" & "+ MusicUtil.getCassPwd()); - cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort()) - .withCredentials(MusicUtil.getCassName(), cassPwd) - //.withLoadBalancingPolicy(new RoundRobinPolicy()) - .withoutJMXReporting() - .withPoolingOptions(poolingOptions) - .addContactPoints(addresses).build(); - } else { - cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort()) - .withoutJMXReporting() - .withPoolingOptions(poolingOptions) - .addContactPoints(addresses) - .build(); - } - - - Metadata metadata = cluster.getMetadata(); - logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster " - + metadata.getClusterName() + " at " + address); - - EnumNameCodec lockTypeCodec = new EnumNameCodec(LockType.class); - cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec); - - try { - session = cluster.connect(); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY, - ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE, ex); - throw new MusicServiceException( - "Error while connecting to Cassandra cluster.. " + ex.getMessage()); - } - } - - /** - * - * @param keyspace - * @param tableName - * @param columnName - * @return DataType - */ - public DataType returnColumnDataType(String keyspace, String tableName, String columnName) { - KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace); - TableMetadata table = ks.getTable(tableName); - return table.getColumn(columnName).getType(); - - } - - /** - * - * @param keyspace - * @param tableName - * @return TableMetadata - */ - public TableMetadata returnColumnMetadata(String keyspace, String tableName) { - KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace); - return ks.getTable(tableName); - } - - /** - * - * @param keyspace - * @param tableName - * @return TableMetadata - */ - public KeyspaceMetadata returnKeyspaceMetadata(String keyspace) { - return cluster.getMetadata().getKeyspace(keyspace); - } - - - /** - * Utility function to return the Java specific object type. - * - * @param row - * @param colName - * @param colType - * @return - */ - public Object getColValue(Row row, String colName, DataType colType) { - - switch (colType.getName()) { - case VARCHAR: - return row.getString(colName); - case UUID: - return row.getUUID(colName); - case VARINT: - return row.getVarint(colName); - case BIGINT: - return row.getLong(colName); - case INT: - return row.getInt(colName); - case FLOAT: - return row.getFloat(colName); - case DOUBLE: - return row.getDouble(colName); - case BOOLEAN: - return row.getBool(colName); - case MAP: - return row.getMap(colName, String.class, String.class); - case LIST: - return row.getList(colName, String.class); - default: - return null; - } - } - - public byte[] getBlobValue(Row row, String colName, DataType colType) { - ByteBuffer bb = row.getBytes(colName); - return bb.array(); - } - - public boolean doesRowSatisfyCondition(Row row, Map condition) throws Exception { - ColumnDefinitions colInfo = row.getColumnDefinitions(); - - for (Map.Entry entry : condition.entrySet()) { - String colName = entry.getKey(); - DataType colType = colInfo.getType(colName); - Object columnValue = getColValue(row, colName, colType); - Object conditionValue = MusicUtil.convertToActualDataType(colType, entry.getValue()); - if (columnValue.equals(conditionValue) == false) - return false; - } - return true; - } - - /** - * Utility function to store ResultSet values in to a MAP for output. - * - * @param results - * @return MAP - */ - public Map> marshalData(ResultSet results) { - Map> resultMap = - new HashMap<>(); - int counter = 0; - for (Row row : results) { - ColumnDefinitions colInfo = row.getColumnDefinitions(); - HashMap resultOutput = new HashMap<>(); - for (Definition definition : colInfo) { - if (!(("vector_ts").equals(definition.getName()))) { - if(definition.getType().toString().toLowerCase().contains("blob")) { - resultOutput.put(definition.getName(), - getBlobValue(row, definition.getName(), definition.getType())); - } else { - resultOutput.put(definition.getName(), - getColValue(row, definition.getName(), definition.getType())); - } - } - } - resultMap.put("row " + counter, resultOutput); - counter++; - } - return resultMap; - } - - - // Prepared Statements 1802 additions - - public boolean executePut(PreparedQueryObject queryObject, String consistency) - throws MusicServiceException, MusicQueryException { - return executePut(queryObject, consistency, 0); - } - /** - * This Method performs DDL and DML operations on Cassandra using specified consistency level - * - * @param queryObject Object containing cassandra prepared query and values. - * @param consistency Specify consistency level for data synchronization across cassandra - * replicas - * @return Boolean Indicates operation success or failure - * @throws MusicServiceException - * @throws MusicQueryException - */ - public boolean executePut(PreparedQueryObject queryObject, String consistency,long timeSlot) - throws MusicServiceException, MusicQueryException { - - boolean result = false; - long timeOfWrite = System.currentTimeMillis(); - if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { - logger.error(EELFLoggerDelegate.errorLogger, queryObject.getQuery(),AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicQueryException("Ill formed queryObject for the request = " + "[" - + queryObject.getQuery() + "]"); - } - logger.debug(EELFLoggerDelegate.applicationLogger, - "In preprared Execute Put: the actual insert query:" - + queryObject.getQuery() + "; the values" - + queryObject.getValues()); - SimpleStatement preparedInsert = null; - - try { - preparedInsert = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray()); - if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - logger.info(EELFLoggerDelegate.applicationLogger, "Executing critical put query"); - preparedInsert.setConsistencyLevel(ConsistencyLevel.QUORUM); - } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { - logger.info(EELFLoggerDelegate.applicationLogger, "Executing simple put query"); - if(queryObject.getConsistency() == null) - preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE); - else - preparedInsert.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency())); - } else if (consistency.equalsIgnoreCase(MusicUtil.ONE)) { - preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE); - } else if (consistency.equalsIgnoreCase(MusicUtil.QUORUM)) { - preparedInsert.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); - } else if (consistency.equalsIgnoreCase(MusicUtil.ALL)) { - preparedInsert.setConsistencyLevel(ConsistencyLevel.ALL); - } - long timestamp = MusicUtil.v2sTimeStampInMicroseconds(timeSlot, timeOfWrite); - preparedInsert.setDefaultTimestamp(timestamp); - - ResultSet rs = session.execute(preparedInsert); - result = rs.wasApplied(); - - } - catch (AlreadyExistsException ae) { - // logger.error(EELFLoggerDelegate.errorLogger,"AlreadExistsException: " + ae.getMessage(),AppMessages.QUERYERROR, - // ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicQueryException("AlreadyExistsException: " + ae.getMessage(),ae); - } catch ( InvalidQueryException e ) { - // logger.error(EELFLoggerDelegate.errorLogger,"InvalidQueryException: " + e.getMessage(),AppMessages.SESSIONFAILED + " [" - // + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicQueryException("InvalidQueryException: " + e.getMessage(),e); - } catch (Exception e) { - // logger.error(EELFLoggerDelegate.errorLogger,e.getClass().toString() + ":" + e.getMessage(),AppMessages.SESSIONFAILED + " [" - // + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR, e); - throw new MusicServiceException("Executing Session Failure for Request = " + "[" - + queryObject.getQuery() + "]" + " Reason = " + e.getMessage(),e); - } - return result; - } - - /* *//** - * This method performs DDL operations on Cassandra using consistency level ONE. - * - * @param queryObject Object containing cassandra prepared query and values. - * @return ResultSet - * @throws MusicServiceException - * @throws MusicQueryException - *//* - public ResultSet executeEventualGet(PreparedQueryObject queryObject) - throws MusicServiceException, MusicQueryException { - CacheAccess queryBank = CachingUtil.getStatementBank(); - PreparedStatement preparedEventualGet = null; - if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { - logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicQueryException("Ill formed queryObject for the request = " + "[" - + queryObject.getQuery() + "]"); - } - logger.info(EELFLoggerDelegate.applicationLogger, - "Executing Eventual get query:" + queryObject.getQuery()); - - ResultSet results = null; - try { - if(queryBank.get(queryObject.getQuery()) != null ) - preparedEventualGet=queryBank.get(queryObject.getQuery()); - else { - preparedEventualGet = session.prepare(queryObject.getQuery()); - CachingUtil.updateStatementBank(queryObject.getQuery(), preparedEventualGet); - } - if(queryObject.getConsistency() == null) { - preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE); - } else { - preparedEventualGet.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency())); - } - results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray())); - - } catch (Exception ex) { - logger.error("Exception", ex); - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicServiceException(ex.getMessage()); - } - return results; - } - - *//** - * - * This method performs DDL operation on Cassandra using consistency level QUORUM. - * - * @param queryObject Object containing cassandra prepared query and values. - * @return ResultSet - * @throws MusicServiceException - * @throws MusicQueryException - *//* - public ResultSet executeCriticalGet(PreparedQueryObject queryObject) - throws MusicServiceException, MusicQueryException { - if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { - logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "[" - + queryObject.getQuery() + "]"); - } - logger.info(EELFLoggerDelegate.applicationLogger, - "Executing Critical get query:" + queryObject.getQuery()); - PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery()); - preparedEventualGet.setConsistencyLevel(ConsistencyLevel.QUORUM); - ResultSet results = null; - try { - results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray())); - } catch (Exception ex) { - logger.error("Exception", ex); - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicServiceException(ex.getMessage()); - } - return results; - - } - */ - public ResultSet executeGet(PreparedQueryObject queryObject,String consistencyLevel) throws MusicQueryException, MusicServiceException { - if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { - logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "[" - + queryObject.getQuery() + "]"); - } - ResultSet results = null; - try { - SimpleStatement statement = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray()); - - if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_ONE)) { - if(queryObject.getConsistency() == null) { - statement.setConsistencyLevel(ConsistencyLevel.ONE); - } else { - statement.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency())); - } - } - else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_QUORUM)) { - statement.setConsistencyLevel(ConsistencyLevel.QUORUM); - } - - results = session.execute(statement); - - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Execute Get Error" + ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject - .getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR, ex); - throw new MusicServiceException("Execute Get Error" + ex.getMessage()); - } - - return results; - - } - - /** - * This method performs DDL operations on Cassandra using consistency level ONE. - * - * @param queryObject Object containing cassandra prepared query and values. - */ - public ResultSet executeOneConsistencyGet(PreparedQueryObject queryObject) - throws MusicServiceException, MusicQueryException { - return executeGet(queryObject, CONSISTENCY_LEVEL_ONE); - } - - /** - * - * This method performs DDL operation on Cassandra using consistency level QUORUM. - * - * @param queryObject Object containing cassandra prepared query and values. - */ - public ResultSet executeQuorumConsistencyGet(PreparedQueryObject queryObject) - throws MusicServiceException, MusicQueryException { - return executeGet(queryObject, CONSISTENCY_LEVEL_QUORUM); - } - -} diff --git a/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java b/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java deleted file mode 100644 index 92457d07..00000000 --- a/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.datastore; - -import java.util.HashMap; -import java.util.Map; - -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicUtil; - -import com.datastax.driver.core.KeyspaceMetadata; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.TableMetadata; - -public class MusicDataStoreHandle { - - private static MusicDataStore mDstoreHandle = null; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStoreHandle.class); - - private MusicDataStoreHandle(){ - throw new IllegalStateException("Utility class"); - } - - /** - * - * @param remoteIp - * @return - */ - public static MusicDataStore getDSHandle(String remoteIp) { - logger.info(EELFLoggerDelegate.metricsLogger,"Acquiring data store handle"); - long start = System.currentTimeMillis(); - if (mDstoreHandle == null) { - mDstoreHandle = new MusicDataStore(remoteIp); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.metricsLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); - return mDstoreHandle; - } - - /** - * - * @return - * @throws MusicServiceException - */ - public static MusicDataStore getDSHandle() throws MusicServiceException { - logger.info(EELFLoggerDelegate.metricsLogger,"Acquiring data store handle"); - long start = System.currentTimeMillis(); - if (mDstoreHandle == null) { - // Quick Fix - Best to put this into every call to getDSHandle? - if (!"localhost".equals(MusicUtil.getMyCassaHost())) { - mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost()); - } else { - mDstoreHandle = new MusicDataStore(); - } - } - if(mDstoreHandle.getSession() == null) { - String message = "Connection to Cassandra has not been enstablished." - + " Please check connection properites and reboot."; - logger.info(EELFLoggerDelegate.applicationLogger, message); - throw new MusicServiceException(message); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.metricsLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); - return mDstoreHandle; - } - - - /** - * - * @param keyspace - * @param tablename - * @return - * @throws MusicServiceException - */ - public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException { - return getDSHandle().returnColumnMetadata(keyspace, tablename); - } - - /** - * - * @param keyspace - * @param tablename - * @return - * @throws MusicServiceException - */ - public static KeyspaceMetadata returnkeyspaceMetadata(String keyspace) throws MusicServiceException { - return getDSHandle().returnKeyspaceMetadata(keyspace); - } - - /** - * - * @param results - * @return - * @throws MusicServiceException - */ - public static Map> marshallResults(ResultSet results) throws MusicServiceException { - return getDSHandle().marshalData(results); - } - -} diff --git a/src/main/java/org/onap/music/datastore/PreparedQueryObject.java b/src/main/java/org/onap/music/datastore/PreparedQueryObject.java deleted file mode 100644 index fdac50be..00000000 --- a/src/main/java/org/onap/music/datastore/PreparedQueryObject.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017-2019 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.datastore; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author srupane - * - */ -public class PreparedQueryObject { - - - private List values; - private StringBuilder query; - private String consistency; - private String keyspaceName; - private String tableName; - private String operation; - private String primaryKeyValue; - - - /** - * Create PreparedQueryObject - */ - public PreparedQueryObject() { - this.values = new ArrayList<>(); - this.query = new StringBuilder(); - } - - /** - * Create PreparedQueryObject - * @param query query portion of the prepared query - */ - public PreparedQueryObject(String query) { - this.values = new ArrayList<>(); - this.query = new StringBuilder(query); - } - - /** - * Create PreparedQueryObject - * @param query query portion of the prepared query - * @param values to be added to the query string as prepared query - */ - public PreparedQueryObject(String query, Object...values) { - this.query = new StringBuilder(query); - this.values = new ArrayList<>(); - for (Object value: values) { - this.values.add(value); - } - } - - public String getKeyspaceName() { - return keyspaceName; - } - - public void setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - } - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - public String getOperation() { - if (operation!=null) return operation; - if (query.length()==0) return null; - String queryStr = query.toString().toLowerCase(); - String firstOp = null; - int firstOpChar = query.length(); - if (queryStr.indexOf("insert")>-1 && queryStr.indexOf("insert")-1 && queryStr.indexOf("update")-1 && queryStr.indexOf("delete")-1 && queryStr.indexOf("select") getValues() { - return values; - } - - /** - * @param o object to be added as a value to the prepared query, in order - */ - public void addValue(Object o) { - this.values.add(o); - } - - /** - * Add values to the preparedQuery - * @param objs ordered list of objects to be added as values to the prepared query - */ - public void addValues(Object... objs) { - for (Object obj: objs) { - this.values.add(obj); - } - } - - /** - * @param s - */ - public void appendQueryString(String s) { - this.query.append(s); - } - public void replaceQueryString(String s) { - this.query.replace(0, query.length(), s); - } - - /** - * @return the query - */ - public String getQuery() { - return this.query.toString(); - } -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java b/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java deleted file mode 100644 index a1524cc6..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.onap.music.datastore.jsonobjects; -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - - -public class JSONObject { - - private String data; - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java deleted file mode 100644 index 988ba3a8..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.datastore.jsonobjects; - -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response.Status; - -import org.onap.music.datastore.Condition; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicUtil; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TableMetadata; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "JsonTable", description = "Json model for delete") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonDelete { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonDelete.class); - - private List columns = null; - private Map consistencyInfo; - private Map conditions; - private String ttl; - private String timestamp; - private String keyspaceName; - private String tableName; - private StringBuilder rowIdString; - private String primarKeyValue; - - - @ApiModelProperty(value = "Conditions") - public Map getConditions() { - return conditions; - } - - public void setConditions(Map conditions) { - this.conditions = conditions; - } - - @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") - public Map getConsistencyInfo() { - return consistencyInfo; - } - - public void setConsistencyInfo(Map consistencyInfo) { - this.consistencyInfo = consistencyInfo; - } - - @ApiModelProperty(value = "Column values") - public List getColumns() { - return columns; - } - - public void setColumns(List columns) { - this.columns = columns; - } - - - @ApiModelProperty(value = "Time to live information") - public String getTtl() { - return ttl; - } - - public void setTtl(String ttl) { - this.ttl = ttl; - } - - @ApiModelProperty(value = "Time stamp") - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public String getKeyspaceName() { - return keyspaceName; - } - - public void setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - } - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - public StringBuilder getRowIdString() { - return rowIdString; - } - - public void setRowIdString(StringBuilder rowIdString) { - this.rowIdString = rowIdString; - } - - public String getPrimarKeyValue() { - return primarKeyValue; - } - - public void setPrimarKeyValue(String primarKeyValue) { - this.primarKeyValue = primarKeyValue; - } - - - public PreparedQueryObject genDeletePreparedQueryObj(MultivaluedMap rowParams) throws MusicQueryException { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getKeyspaceName()); - logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getTableName()); - } - - PreparedQueryObject queryObject = new PreparedQueryObject(); - - if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) - || (this.getTableName() == null || this.getTableName().isEmpty())){ - - - throw new MusicQueryException("one or more path parameters are not set, please check and try again", - Status.BAD_REQUEST.getStatusCode()); - } - - EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) "); - - if(this == null) { - logger.error(EELFLoggerDelegate.errorLogger,"Required HTTP Request body is missing.", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); - - throw new MusicQueryException("Required HTTP Request body is missing.", - Status.BAD_REQUEST.getStatusCode()); - } - StringBuilder columnString = new StringBuilder(); - - int counter = 0; - List columnList = this.getColumns(); - if (columnList != null) { - for (String column : columnList) { - columnString.append(column); - if (counter != columnList.size() - 1) - columnString.append(","); - counter = counter + 1; - } - } - - // get the row specifier - RowIdentifier rowId = null; - try { - rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject); - this.setRowIdString(rowId.rowIdString); - this.setPrimarKeyValue(rowId.primarKeyValue); - if(rowId == null || rowId.primarKeyValue.isEmpty()) { - - throw new MusicQueryException("Mandatory WHERE clause is missing. Please check the input request.", - Status.BAD_REQUEST.getStatusCode()); - } - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes - .GENERALSERVICEERROR, ex); - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();*/ - throw new MusicQueryException(AppMessages.UNKNOWNERROR.toString(), Status.BAD_REQUEST.getStatusCode()); - } - String rowSpec = rowId.rowIdString.toString(); - - if ((columnList != null) && (!rowSpec.isEmpty())) { - queryObject.appendQueryString("DELETE " + columnString + " FROM " + this.getKeyspaceName() + "." - + this.getTableName() + " WHERE " + rowSpec + ";"); - } - - if ((columnList == null) && (!rowSpec.isEmpty())) { - queryObject.appendQueryString("DELETE FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " - + rowSpec + ";"); - } - - if ((columnList != null) && (rowSpec.isEmpty())) { - queryObject.appendQueryString( - "DELETE " + columnString + " FROM " + this.getKeyspaceName() + "." + rowSpec + ";"); - } - // get the conditional, if any - Condition conditionInfo; - if (this.getConditions() == null) { - conditionInfo = null; - } else { - // to avoid parsing repeatedly, just send the select query to - // obtain row - PreparedQueryObject selectQuery = new PreparedQueryObject(); - selectQuery.appendQueryString("SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " - + rowId.rowIdString + ";"); - selectQuery.addValue(rowId.primarKeyValue); - conditionInfo = new Condition(this.getConditions(), selectQuery); - } - - String consistency = this.getConsistencyInfo().get("type"); - - - if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency")!=null) { - if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { - queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); - } else { - throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode()); - } - } - - queryObject.setOperation("delete"); - - return queryObject; - } - - - /** - * - * @param keyspace - * @param tablename - * @param rowParams - * @param queryObject - * @return - * @throws MusicServiceException - */ - private RowIdentifier getRowIdentifier(String keyspace, String tablename, - MultivaluedMap rowParams, PreparedQueryObject queryObject) - throws MusicServiceException { - StringBuilder rowSpec = new StringBuilder(); - int counter = 0; - TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); - if (tableInfo == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - throw new MusicServiceException( - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - } - StringBuilder primaryKey = new StringBuilder(); - for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { - String keyName = entry.getKey(); - List valueList = entry.getValue(); - String indValue = valueList.get(0); - DataType colType = null; - Object formattedValue = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - formattedValue = MusicUtil.convertToActualDataType(colType, indValue); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); - } - if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { - primaryKey.append(indValue); - } - rowSpec.append(keyName + "= ?"); - queryObject.addValue(formattedValue); - if (counter != rowParams.size() - 1) { - rowSpec.append(" AND "); - } - counter = counter + 1; - } - return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); - } - - private class RowIdentifier { - private String primarKeyValue; - private StringBuilder rowIdString; - @SuppressWarnings("unused") - public PreparedQueryObject queryObject; // the string with all the row - // identifiers separated by AND - - public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, - PreparedQueryObject queryObject) { - this.primarKeyValue = primaryKeyValue; - this.rowIdString = rowIdString; - this.queryObject = queryObject; - } - } -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java deleted file mode 100644 index a06e8ea9..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ -package org.onap.music.datastore.jsonobjects; - -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ApiModel(value = "JsonIndex", description = "Index Object") -public class JsonIndex { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonIndex.class); - - private String indexName; - private String keyspaceName; - private String tableName; - private String fieldName; - - public JsonIndex(String indexName,String keyspaceName,String tableName,String fieldName) { - this.indexName = indexName; - this.keyspaceName= keyspaceName; - this.tableName = tableName; - this.fieldName = fieldName; - } - - @ApiModelProperty(value = "Index Name") - public String getIndexName() { - return indexName; - } - - public JsonIndex setIndexName(String indexName) { - this.indexName = indexName; - return this; - } - - @ApiModelProperty(value = "Keyspace name") - public String getKeyspaceName() { - return keyspaceName; - } - - public JsonIndex setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - return this; - } - - public JsonIndex setTableName(String tableName) { - this.tableName = tableName; - return this; - } - - @ApiModelProperty(value = "Table name") - public String getTableName() { - return tableName; - } - - public JsonIndex setFieldName(String fieldName) { - this.fieldName = fieldName; - return this; - } - - @ApiModelProperty(value = "Field name") - public String getFieldName() { - return fieldName; - } - - public PreparedQueryObject genCreateIndexQuery() { - - if (logger.isDebugEnabled()) { - logger.debug("Came inside genCreateIndexQuery method"); - } - - logger.info("genCreateIndexQuery indexName ::" + indexName); - logger.info("genCreateIndexQuery keyspaceName ::" + keyspaceName); - logger.info("genCreateIndexQuery tableName ::" + tableName); - logger.info("genCreateIndexQuery fieldName ::" + fieldName); - - long start = System.currentTimeMillis(); - - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString("Create index if not exists " + this.getIndexName() + " on " + this.getKeyspaceName() + "." - + this.getTableName() + " (" + this.getFieldName() + ");"); - - long end = System.currentTimeMillis(); - - logger.info(EELFLoggerDelegate.applicationLogger, - "Time taken for setting up query in create index:" + (end - start)); - - logger.info(EELFLoggerDelegate.applicationLogger, - " create index query :" + query.getQuery()); - - return query; - } - -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java deleted file mode 100644 index 57ff245a..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.datastore.jsonobjects; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response.Status; - -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicUtil; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TableMetadata; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "InsertTable", description = "Json model for table vlaues insert") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonInsert implements Serializable { - private static final long serialVersionUID = 1L; - private String keyspaceName; - private String tableName; - private transient Map values; - private String ttl; - private String timestamp; - private transient Map rowSpecification; - private Map consistencyInfo; - private Map objectMap; - private String primaryKeyVal; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonInsert.class); - - @ApiModelProperty(value = "objectMap",hidden = true) - public Map getObjectMap() { - return objectMap; - } - - public void setObjectMap(Map objectMap) { - this.objectMap = objectMap; - } - - @ApiModelProperty(value = "keyspace") - public String getKeyspaceName() { - return keyspaceName; - } - - public void setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - } - - @ApiModelProperty(value = "Table name") - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") - public Map getConsistencyInfo() { - return consistencyInfo; - } - - public void setConsistencyInfo(Map consistencyInfo) { - this.consistencyInfo = consistencyInfo; - } - - @ApiModelProperty(value = "Columns and tables support an optional " - + "expiration period called TTL (time-to-live) in seconds.", - notes="TTL precision is one second, which is calculated by the coordinator " - + "node. When using TTL, ensure that all nodes in the cluster have synchronized clocks.",allowEmptyValue = true) - public String getTtl() { - return ttl; - } - - public void setTtl(String ttl) { - this.ttl = ttl; - } - - @ApiModelProperty(value = "Time stamp (epoch_in_microseconds)", - notes = "Marks inserted data (write time) with TIMESTAMP. " - + "Enter the time since epoch (January 1, 1970) in microseconds." - + "By default, the actual time of write is used.", allowEmptyValue = true) - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - @ApiModelProperty(value = "Json Object of key/values", notes="Where key is the column name and value is the data value for that column.", - example = "{'emp_id': 'df98a3d40cd6','emp_name': 'john'," - + "'emp_salary': 50,'address':{'street' : '1 Some way','city' : 'New York'}}") - public Map getValues() { - return values; - } - - public void setValues(Map values) { - this.values = values; - } - - @ApiModelProperty(value = "Information for selecting specific rows for insert",hidden = true) - public Map getRowSpecification() { - return rowSpecification; - } - - public void setRowSpecification(Map rowSpecification) { - this.rowSpecification = rowSpecification; - } - - public String getPrimaryKeyVal() { - return primaryKeyVal; - } - - public void setPrimaryKeyVal(String primaryKeyVal) { - this.primaryKeyVal = primaryKeyVal; - } - - public byte[] serialize() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutput out = null; - try { - out = new ObjectOutputStream(bos); - out.writeObject(this); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.DATAERROR); - } - return bos.toByteArray(); - } - - /** - * Generate TableInsertQuery - * @return - * @throws MusicQueryException - */ - public PreparedQueryObject genInsertPreparedQueryObj() throws MusicQueryException { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genTableInsertQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genTableInsertQuery method " + this.getTableName()); - } - - PreparedQueryObject queryObject = new PreparedQueryObject(); - TableMetadata tableInfo = null; - try { - tableInfo = MusicDataStoreHandle.returnColumnMetadata(this.getKeyspaceName(), this.getTableName()); - if(tableInfo == null) { - throw new MusicQueryException("Table name doesn't exists. Please check the table name.", - Status.BAD_REQUEST.getStatusCode()); - } - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - throw new MusicQueryException(e.getMessage(),Status.BAD_REQUEST.getStatusCode()); - - } - String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); - StringBuilder fieldsString = new StringBuilder("(vector_ts,"); - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - StringBuilder valueString = new StringBuilder("(" + "?" + ","); - queryObject.addValue(vectorTs); - - Map valuesMap = this.getValues(); - if (valuesMap==null) { - throw new MusicQueryException("Nothing to insert. No values provided in request.", - Status.BAD_REQUEST.getStatusCode()); - } - int counter = 0; - String primaryKey = ""; - for (Map.Entry entry : valuesMap.entrySet()) { - fieldsString.append("" + entry.getKey()); - Object valueObj = entry.getValue(); - if (primaryKeyName.equals(entry.getKey())) { - primaryKey = entry.getValue() + ""; - primaryKey = primaryKey.replace("'", "''"); - } - DataType colType = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - } catch(NullPointerException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey - (), AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR, ex); - throw new MusicQueryException("Invalid column name : " + entry.getKey(), - Status.BAD_REQUEST.getStatusCode()); - } - - Object formattedValue = null; - try { - formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); - } - valueString.append("?"); - - queryObject.addValue(formattedValue); - - if (counter == valuesMap.size() - 1) { - fieldsString.append(")"); - valueString.append(")"); - } else { - fieldsString.append(","); - valueString.append(","); - } - counter = counter + 1; - } - - //blobs.. - Map objectMap = this.getObjectMap(); - if(objectMap != null) { - for (Map.Entry entry : objectMap.entrySet()) { - if(counter > 0) { - fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ","); - valueString.replace(valueString.length()-1, valueString.length(), ","); - } - fieldsString.append("" + entry.getKey()); - byte[] valueObj = entry.getValue(); - if (primaryKeyName.equals(entry.getKey())) { - primaryKey = entry.getValue() + ""; - primaryKey = primaryKey.replace("'", "''"); - } - DataType colType = tableInfo.getColumn(entry.getKey()).getType(); - ByteBuffer formattedValue = null; - if(colType.toString().toLowerCase().contains("blob")) { - formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); - } - valueString.append("?"); - queryObject.addValue(formattedValue); - counter = counter + 1; - fieldsString.append(","); - valueString.append(","); - } - } - this.setPrimaryKeyVal(primaryKey); - if(primaryKey == null || primaryKey.length() <= 0) { - logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName ); - throw new MusicQueryException("Some required partition key parts are missing: " + primaryKeyName, - Status.BAD_REQUEST.getStatusCode()); - } - - fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")"); - valueString.replace(valueString.length()-1, valueString.length(), ")"); - - queryObject.appendQueryString("INSERT INTO " + this.getKeyspaceName() + "." + this.getTableName() + " " - + fieldsString + " VALUES " + valueString); - - String ttl = this.getTtl(); - String timestamp = this.getTimestamp(); - - if ((ttl != null) && (timestamp != null)) { - logger.info(EELFLoggerDelegate.applicationLogger, "both there"); - queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); - queryObject.addValue(Integer.parseInt(ttl)); - queryObject.addValue(Long.parseLong(timestamp)); - } - - if ((ttl != null) && (timestamp == null)) { - logger.info(EELFLoggerDelegate.applicationLogger, "ONLY TTL there"); - queryObject.appendQueryString(" USING TTL ?"); - queryObject.addValue(Integer.parseInt(ttl)); - } - - if ((ttl == null) && (timestamp != null)) { - logger.info(EELFLoggerDelegate.applicationLogger, "ONLY timestamp there"); - queryObject.appendQueryString(" USING TIMESTAMP ?"); - queryObject.addValue(Long.parseLong(timestamp)); - } - - queryObject.appendQueryString(";"); - - String consistency = this.getConsistencyInfo().get("type"); - if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency") != null) { - if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { - queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); - } else { - throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode()); - } - } - queryObject.setOperation("insert"); - - logger.info("Data insert Query ::::: " + queryObject.getQuery()); - - return queryObject; - } - - /** - * - * @param rowParams - * @return - * @throws MusicQueryException - */ - public PreparedQueryObject genSelectCriticalPreparedQueryObj(MultivaluedMap rowParams) throws MusicQueryException { - - PreparedQueryObject queryObject = new PreparedQueryObject(); - - if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) - || (this.getTableName() == null || this.getTableName().isEmpty())){ - throw new MusicQueryException("one or more path parameters are not set, please check and try again", - Status.BAD_REQUEST.getStatusCode()); - } - EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) "); - RowIdentifier rowId = null; - try { - rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject); - this.setPrimaryKeyVal(rowId.primarKeyValue); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes - .GENERALSERVICEERROR, ex); - throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode()); - } - - queryObject.appendQueryString( - "SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " + rowId.rowIdString + ";"); - - return queryObject; - } - - private class RowIdentifier { - public String primarKeyValue; - public StringBuilder rowIdString; - @SuppressWarnings("unused") - public PreparedQueryObject queryObject; // the string with all the row - // identifiers separated by AND - - public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, - PreparedQueryObject queryObject) { - this.primarKeyValue = primaryKeyValue; - this.rowIdString = rowIdString; - this.queryObject = queryObject; - } - } - - /** - * - * @param keyspace - * @param tablename - * @param rowParams - * @param queryObject - * @return - * @throws MusicServiceException - */ - private RowIdentifier getRowIdentifier(String keyspace, String tablename, - MultivaluedMap rowParams, PreparedQueryObject queryObject) - throws MusicServiceException { - StringBuilder rowSpec = new StringBuilder(); - int counter = 0; - TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); - if (tableInfo == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - throw new MusicServiceException( - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - } - StringBuilder primaryKey = new StringBuilder(); - for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { - String keyName = entry.getKey(); - List valueList = entry.getValue(); - String indValue = valueList.get(0); - DataType colType = null; - Object formattedValue = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - formattedValue = MusicUtil.convertToActualDataType(colType, indValue); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); - } - if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { - primaryKey.append(indValue); - } - rowSpec.append(keyName + "= ?"); - queryObject.addValue(formattedValue); - if (counter != rowParams.size() - 1) { - rowSpec.append(" AND "); - } - counter = counter + 1; - } - return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); - } - - -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java deleted file mode 100644 index cada1c00..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.datastore.jsonobjects; - -import java.util.Map; - -import javax.ws.rs.core.Response.Status; - -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.main.MusicUtil; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "JsonTable", description = "Json model creating new keyspace") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonKeySpace { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonKeySpace.class); - private String keyspaceName; - private Map replicationInfo; - private String durabilityOfWrites; - private Map consistencyInfo; - - @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") - public Map getConsistencyInfo() { - return consistencyInfo; - } - - public void setConsistencyInfo(Map consistencyInfo) { - this.consistencyInfo = consistencyInfo; - } - - @ApiModelProperty(value = "Replication information") - public Map getReplicationInfo() { - return replicationInfo; - } - - public void setReplicationInfo(Map replicationInfo) { - this.replicationInfo = replicationInfo; - } - - @ApiModelProperty(value = "Durability", allowableValues = "true,false") - public String getDurabilityOfWrites() { - return durabilityOfWrites; - } - - public void setDurabilityOfWrites(String durabilityOfWrites) { - this.durabilityOfWrites = durabilityOfWrites; - } - - @ApiModelProperty(value = "Keyspace name") - public String getKeyspaceName() { - return keyspaceName; - } - - public void setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - } - - /** - * Will generate query to create Keyspacce. - * - * @throws MusicQueryException - */ - @SuppressWarnings("deprecation") - public PreparedQueryObject genCreateKeyspaceQuery() throws MusicQueryException { - - if (logger.isDebugEnabled()) { - logger.debug("Came inside createKeyspace method"); - } - - String keyspaceName = this.getKeyspaceName(); - String durabilityOfWrites = this.getDurabilityOfWrites(); - String consistency = MusicUtil.EVENTUAL; - - logger.info("genCreateKeyspaceQuery keyspaceName ::" + keyspaceName); - logger.info("genCreateKeyspaceQuery class :: " + this.getReplicationInfo().get("class")); - logger.info("genCreateKeyspaceQuery replication_factor :: " + this.getReplicationInfo().get("replication_factor")); - logger.info("genCreateKeyspaceQuery durabilityOfWrites :: " + durabilityOfWrites); - - PreparedQueryObject queryObject = new PreparedQueryObject(); - - if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency") != null) { - if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { - queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); - }else { - throw new MusicQueryException("Invalid Consistency type",Status.BAD_REQUEST.getStatusCode()); - } - } - - long start = System.currentTimeMillis(); - Map replicationInfo = this.getReplicationInfo(); - String repString = null; - try { - repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}"; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - } - queryObject.appendQueryString("CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString); - if (this.getDurabilityOfWrites() != null) { - queryObject.appendQueryString(" AND durable_writes = " + this.getDurabilityOfWrites()); - } - queryObject.appendQueryString(";"); - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger, - "Time taken for setting up query in create keyspace:" + (end - start)); - - return queryObject; - } - - /** - * Will generate Query to drop a keyspace. - * - * @return - */ - public PreparedQueryObject genDropKeyspaceQuery() { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genDropKeyspaceQuery method "+this.getKeyspaceName()); - } - - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("DROP KEYSPACE " + this.getKeyspaceName() + ";"); - - return queryObject; - } - - @Override - public String toString() { - return "CassaKeyspaceObject [keyspaceName=" + keyspaceName + ", replicationInfo=" + replicationInfo - + "durabilityOfWrites=" + durabilityOfWrites + "]"; - } - -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java deleted file mode 100644 index 86bbe3dc..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.datastore.jsonobjects; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "Json Leasesd Lock", description = "model for leased lock") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonLeasedLock { - private long leasePeriod; - - @ApiModelProperty(value = "Lease period") - public long getLeasePeriod() { - return leasePeriod; - } - - public void setLeasePeriod(long leasePeriod) { - this.leasePeriod = leasePeriod; - } - -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java deleted file mode 100644 index f353c018..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.datastore.jsonobjects; - -import org.onap.music.lockingservice.cassandra.LockType; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "Json Lock Type", description = "Model for Lock Type") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonLock { - private LockType locktype; - - @ApiModelProperty( - value = "Type of music lock", - name = "lockType", - allowEmptyValue = false, - allowableValues = "READ|WRITE") - public LockType getLocktype() { - return this.locktype; - } - - public void setLockType(LockType locktype) { - this.locktype = locktype; - } -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java deleted file mode 100644 index e354b4b0..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.datastore.jsonobjects; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response.Status; - -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicUtil; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TableMetadata; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonSelect implements Serializable { - private Map consistencyInfo; - private String keyspaceName; - private String tableName; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonSelect.class); - - - - public Map getConsistencyInfo() { - return consistencyInfo; - } - - public void setConsistencyInfo(Map consistencyInfo) { - this.consistencyInfo = consistencyInfo; - } - - public String getKeyspaceName() { - return keyspaceName; - } - - public void setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - } - - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - public byte[] serialize() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutput out = null; - try { - out = new ObjectOutputStream(bos); - out.writeObject(this); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); - } - return bos.toByteArray(); - } - - /** - * genSelectQuery - * - * @return - * @throws MusicQueryException - */ - public PreparedQueryObject genSelectQuery(MultivaluedMap rowParams) throws MusicQueryException { - - if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) - || (this.getTableName() == null || this.getTableName().isEmpty())){ - throw new MusicQueryException("one or more path parameters are not set, please check and try again", - Status.BAD_REQUEST.getStatusCode()); - } - EELFLoggerDelegate.mdcPut("keyspace", "( " + this.getKeyspaceName() + " ) "); - PreparedQueryObject queryObject = new PreparedQueryObject(); - - if (rowParams.isEmpty()) { // select all - queryObject.appendQueryString("SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + ";"); - } else { - int limit = -1; // do not limit the number of results - try { - queryObject = selectSpecificQuery(this.getKeyspaceName(), this.getTableName(), rowParams, limit); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, - ErrorTypes.GENERALSERVICEERROR, ex); - - throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode()); - } - } - - return queryObject; - } - - public PreparedQueryObject selectSpecificQuery(String keyspace, - String tablename, MultivaluedMap rowParams, int limit) - throws MusicServiceException { - PreparedQueryObject queryObject = new PreparedQueryObject(); - StringBuilder rowIdString = getRowIdentifier(keyspace, - tablename,rowParams,queryObject).rowIdString; - queryObject.appendQueryString( - "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowIdString); - if (limit != -1) { - queryObject.appendQueryString(" LIMIT " + limit); - } - queryObject.appendQueryString(";"); - return queryObject; - } - - private class RowIdentifier { - public String primarKeyValue; - public StringBuilder rowIdString; - @SuppressWarnings("unused") - public PreparedQueryObject queryObject; // the string with all the row - // identifiers separated by AND - - public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, - PreparedQueryObject queryObject) { - this.primarKeyValue = primaryKeyValue; - this.rowIdString = rowIdString; - this.queryObject = queryObject; - } - } - - /** - * - * @param keyspace - * @param tablename - * @param rowParams - * @param queryObject - * @return - * @throws MusicServiceException - */ - private RowIdentifier getRowIdentifier(String keyspace, String tablename, - MultivaluedMap rowParams, PreparedQueryObject queryObject) - throws MusicServiceException { - StringBuilder rowSpec = new StringBuilder(); - int counter = 0; - TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); - if (tableInfo == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - throw new MusicServiceException( - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - } - StringBuilder primaryKey = new StringBuilder(); - for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { - String keyName = entry.getKey(); - List valueList = entry.getValue(); - String indValue = valueList.get(0); - DataType colType = null; - Object formattedValue = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - formattedValue = MusicUtil.convertToActualDataType(colType, indValue); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); - } - if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { - primaryKey.append(indValue); - } - rowSpec.append(keyName + "= ?"); - queryObject.addValue(formattedValue); - if (counter != rowParams.size() - 1) { - rowSpec.append(" AND "); - } - counter = counter + 1; - } - return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); - } - -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java deleted file mode 100644 index ef560144..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.datastore.jsonobjects; - -import java.util.Map; - -import javax.ws.rs.core.Response.Status; - -import org.apache.commons.lang3.StringUtils; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.main.MusicUtil; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "JsonTable", description = "Defines the Json for Creating a new Table.") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonTable { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonTable.class); - - private String keyspaceName; - private String tableName; - - private Map fields; - private Map properties; - private String primaryKey; - private String partitionKey; - private String clusteringKey; - private String filteringKey; - private String clusteringOrder; - private Map consistencyInfo; - - @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") - public Map getConsistencyInfo() { - return consistencyInfo; - } - - public void setConsistencyInfo(Map consistencyInfo) { - this.consistencyInfo = consistencyInfo; - } - - @ApiModelProperty(value = "Properties") - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } - - @ApiModelProperty(value = "Fields") - public Map getFields() { - return fields; - } - - public void setFields(Map fields) { - this.fields = fields; - } - - @ApiModelProperty(value = "KeySpace Name") - public String getKeyspaceName() { - return keyspaceName; - } - - public void setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - } - - @ApiModelProperty(value = "Table Name") - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - @ApiModelProperty(value = "Clustering Order", notes = "") - public String getClusteringOrder() { - return clusteringOrder; - } - - public void setClusteringOrder(String clusteringOrder) { - this.clusteringOrder = clusteringOrder; - } - - @ApiModelProperty(value = "Primary Key") - public String getPrimaryKey() { - return primaryKey; - } - - public void setPrimaryKey(String primaryKey) { - this.primaryKey = primaryKey; - } - - public String getClusteringKey() { - return clusteringKey; - } - - public void setClusteringKey(String clusteringKey) { - this.clusteringKey = clusteringKey; - } - - public String getFilteringKey() { - return filteringKey; - } - - public void setFilteringKey(String filteringKey) { - this.filteringKey = filteringKey; - } - - public String getPartitionKey() { - return partitionKey; - } - - public void setPartitionKey(String partitionKey) { - this.partitionKey = partitionKey; - } - - public PreparedQueryObject genCreateTableQuery() throws MusicQueryException { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genCreateTableQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genCreateTableQuery method " + this.getTableName()); - } - - String primaryKey = null; - String partitionKey = this.getPartitionKey(); - String clusterKey = this.getClusteringKey(); - String filteringKey = this.getFilteringKey(); - if (filteringKey != null) { - clusterKey = clusterKey + "," + filteringKey; - } - primaryKey = this.getPrimaryKey(); // get primaryKey if available - - PreparedQueryObject queryObject = new PreparedQueryObject(); - // first read the information about the table fields - Map fields = this.getFields(); - if (fields == null) { - throw new MusicQueryException( - "Create Table Error: No fields in request", Status.BAD_REQUEST.getStatusCode()); - } - StringBuilder fieldsString = new StringBuilder("(vector_ts text,"); - int counter = 0; - for (Map.Entry entry : fields.entrySet()) { - if (entry.getKey().equals("PRIMARY KEY")) { - primaryKey = entry.getValue(); // replaces primaryKey - primaryKey = primaryKey.trim(); - } else { - if (counter == 0 ) fieldsString.append("" + entry.getKey() + " " + entry.getValue() + ""); - else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + ""); - } - - if (counter != (fields.size() - 1) ) { - counter = counter + 1; - } else { - - if((primaryKey != null) && (partitionKey == null)) { - primaryKey = primaryKey.trim(); - int count1 = StringUtils.countMatches(primaryKey, ')'); - int count2 = StringUtils.countMatches(primaryKey, '('); - if (count1 != count2) { - throw new MusicQueryException( - "Create Table Error: primary key '(' and ')' do not match, primary key=" + primaryKey, - Status.BAD_REQUEST.getStatusCode()); - } - - if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) ) { - if (primaryKey.contains(",") ) { - partitionKey= primaryKey.substring(0,primaryKey.indexOf(',')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - clusterKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index - clusterKey=clusterKey.replaceAll("[)]+", ""); - } else { - partitionKey=primaryKey; - partitionKey=partitionKey.replaceAll("[\\)]+",""); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - clusterKey=""; - } - } else { // not null and has ) before the last char - partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - partitionKey = partitionKey.trim(); - clusterKey= primaryKey.substring(primaryKey.indexOf(')')); - clusterKey=clusterKey.replaceAll("[\\(]+",""); - clusterKey=clusterKey.replaceAll("[\\)]+",""); - clusterKey = clusterKey.trim(); - if (clusterKey.indexOf(',') == 0) { - clusterKey=clusterKey.substring(1); - } - clusterKey = clusterKey.trim(); - if (clusterKey.equals(",") ) clusterKey=""; // print error if needed ( ... ),) - } - - if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) - && (partitionKey.equalsIgnoreCase(clusterKey) || - clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) { - logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey + " and primary key=" + primaryKey ); - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( - "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ") of" - + " primary key=" + primaryKey) - .toMap()).build();*/ - throw new MusicQueryException("Create Table primary key error: clusterKey(" + clusterKey - + ") equals/contains/overlaps partitionKey(" + partitionKey + ") of" + " primary key=" - + primaryKey, Status.BAD_REQUEST.getStatusCode()); - - } - - if (partitionKey.isEmpty() ) primaryKey=""; - else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; - else primaryKey=" (" + partitionKey + ")," + clusterKey; - - - if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); - - } else { // end of length > 0 - - if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) - && (partitionKey.equalsIgnoreCase(clusterKey) || - clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) { - logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey); - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( - "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ")") - .toMap()).build();*/ - throw new MusicQueryException( - "Create Table primary key error: clusterKey(" + clusterKey - + ") equals/contains/overlaps partitionKey(" + partitionKey + ")", - Status.BAD_REQUEST.getStatusCode()); - } - - if (partitionKey.isEmpty() ) primaryKey=""; - else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; - else primaryKey=" (" + partitionKey + ")," + clusterKey; - - if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); - } - fieldsString.append(")"); - - } // end of last field check - - } // end of for each - // information about the name-value style properties - Map propertiesMap = this.getProperties(); - StringBuilder propertiesString = new StringBuilder(); - if (propertiesMap != null) { - counter = 0; - for (Map.Entry entry : propertiesMap.entrySet()) { - Object ot = entry.getValue(); - String value = ot + ""; - if (ot instanceof String) { - value = "'" + value + "'"; - } else if (ot instanceof Map) { - @SuppressWarnings("unchecked") - Map otMap = (Map) ot; - try { - value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}"; - } catch (Exception e) { - throw new MusicQueryException(e.getMessage(), - Status.BAD_REQUEST.getStatusCode()); - } - } - - propertiesString.append(entry.getKey() + "=" + value + ""); - if (counter != propertiesMap.size() - 1) - propertiesString.append(" AND "); - - counter = counter + 1; - } - } - - String clusteringOrder = this.getClusteringOrder(); - - if (clusteringOrder != null && !(clusteringOrder.isEmpty())) { - String[] arrayClusterOrder = clusteringOrder.split("[,]+"); - - for (int i = 0; i < arrayClusterOrder.length; i++) { - String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+"); - if ( (clusterS.length ==2) && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) { - continue; - } else { - /*return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:"+ clusteringOrder+".") - .toMap()).build();*/ - - throw new MusicQueryException( - "createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:" - + clusteringOrder + ".", - Status.BAD_REQUEST.getStatusCode()); - } - // add validation for column names in cluster key - } - - if (!(clusterKey.isEmpty())) { - clusteringOrder = "CLUSTERING ORDER BY (" +clusteringOrder +")"; - //cjc check if propertiesString.length() >0 instead propertiesMap - if (propertiesMap != null) { - propertiesString.append(" AND "+ clusteringOrder); - } else { - propertiesString.append(clusteringOrder); - } - } else { - logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty "); - } - } //if non empty - - queryObject.appendQueryString( - "CREATE TABLE " + this.getKeyspaceName() + "." + this.getTableName() + " " + fieldsString); - - - if (propertiesString != null && propertiesString.length()>0 ) - queryObject.appendQueryString(" WITH " + propertiesString); - queryObject.appendQueryString(";"); - - return queryObject; - } - - /** - * - * @return - */ - public PreparedQueryObject genCreateShadowLockingTableQuery() { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genCreateShadowLockingTableQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genCreateShadowLockingTableQuery method " + this.getTableName()); - } - - String tableName = "unsyncedKeys_" + this.getTableName(); - String tabQuery = "CREATE TABLE IF NOT EXISTS " + this.getKeyspaceName() + "." + tableName - + " ( key text,PRIMARY KEY (key) );"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(tabQuery); - - return queryObject; - } - - /** - * genDropTableQuery - * - * @return PreparedQueryObject - */ - public PreparedQueryObject genDropTableQuery() { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genDropTableQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genDropTableQuery method " + this.getTableName()); - } - - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString("DROP TABLE " + this.getKeyspaceName() + "." + this.getTableName() + ";"); - logger.info("Delete Query ::::: " + query.getQuery()); - - return query; - } - - -} diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java deleted file mode 100644 index 12508de0..00000000 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.datastore.jsonobjects; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response.Status; - -import org.onap.music.datastore.Condition; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ReturnType; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TableMetadata; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "JsonTable", description = "Json model for table update") -@JsonIgnoreProperties(ignoreUnknown = true) -public class JsonUpdate implements Serializable { - private String keyspaceName; - private String tableName; - private transient Map values; - private String ttl; - private String timestamp; - private Map consistencyInfo; - private transient Map conditions; - private transient Map rowSpecification; - private StringBuilder rowIdString; - private String primarKeyValue; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonUpdate.class); - - @ApiModelProperty(value = "Conditions") - public Map getConditions() { - return conditions; - } - - public void setConditions(Map conditions) { - this.conditions = conditions; - } - - @ApiModelProperty(value = "Information for selecting sepcific rows") - public Map getRow_specification() { - return rowSpecification; - } - - public void setRow_specification(Map rowSpecification) { - this.rowSpecification = rowSpecification; - } - - - @ApiModelProperty(value = "Keyspace name") - public String getKeyspaceName() { - return keyspaceName; - } - - public void setKeyspaceName(String keyspaceName) { - this.keyspaceName = keyspaceName; - } - - @ApiModelProperty(value = "Table name") - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic") - public Map getConsistencyInfo() { - return consistencyInfo; - } - - public void setConsistencyInfo(Map consistencyInfo) { - this.consistencyInfo = consistencyInfo; - } - - @ApiModelProperty(value = "Time to live value") - public String getTtl() { - return ttl; - } - - public void setTtl(String ttl) { - this.ttl = ttl; - } - - @ApiModelProperty(value = "Time stamp") - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - @ApiModelProperty(value = "Column values") - public Map getValues() { - return values; - } - - public void setValues(Map values) { - this.values = values; - } - - public StringBuilder getRowIdString() { - return rowIdString; - } - - public void setRowIdString(StringBuilder rowIdString) { - this.rowIdString = rowIdString; - } - - public String getPrimarKeyValue() { - return primarKeyValue; - } - - public void setPrimarKeyValue(String primarKeyValue) { - this.primarKeyValue = primarKeyValue; - } - - public byte[] serialize() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutput out = null; - try { - out = new ObjectOutputStream(bos); - out.writeObject(this); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.DATAERROR); - } - return bos.toByteArray(); - } - - /** - * Generate TableInsertQuery - * @return - * @throws MusicQueryException - */ - public PreparedQueryObject genUpdatePreparedQueryObj(MultivaluedMap rowParams) throws MusicQueryException { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getKeyspaceName()); - logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getTableName()); - } - - PreparedQueryObject queryObject = new PreparedQueryObject(); - - if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) || - (this.getTableName() == null || this.getTableName().isEmpty())){ - - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build();*/ - - throw new MusicQueryException("one or more path parameters are not set, please check and try again", - Status.BAD_REQUEST.getStatusCode()); - } - - EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) "); - long startTime = System.currentTimeMillis(); - String operationId = UUID.randomUUID().toString(); // just for infoging purposes. - String consistency = this.getConsistencyInfo().get("type"); - - logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency - + " update-" + operationId + "-------------------------"); - // obtain the field value pairs of the update - - Map valuesMap = this.getValues(); - - TableMetadata tableInfo; - - try { - tableInfo = MusicDataStoreHandle.returnColumnMetadata(this.getKeyspaceName(), this.getTableName()); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes - .GENERALSERVICEERROR, e); - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();*/ - throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); - }catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR, ErrorSeverity.CRITICAL, - ErrorTypes.GENERALSERVICEERROR); - throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); - } - - if (tableInfo == null) { - logger.error(EELFLoggerDelegate.errorLogger,"Table information not found. Please check input for table name= "+this.getTableName(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("Table information not found. Please check input for table name= " - + this.getKeyspaceName() + "." + this.getTableName()).toMap()).build();*/ - - throw new MusicQueryException("Table information not found. Please check input for table name= " - + this.getKeyspaceName() + "." + this.getTableName(), Status.BAD_REQUEST.getStatusCode()); - } - - String vectorTs = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - StringBuilder fieldValueString = new StringBuilder("vector_ts=?,"); - queryObject.addValue(vectorTs); - int counter = 0; - for (Map.Entry entry : valuesMap.entrySet()) { - Object valueObj = entry.getValue(); - DataType colType = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - } catch(NullPointerException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex, "Invalid column name : "+entry.getKey(), ex); - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE). - * setError("Invalid column name : "+entry.getKey()).toMap()).build();*/ - - throw new MusicQueryException("Invalid column name : " + entry.getKey(),Status.BAD_REQUEST.getStatusCode()); - } - Object valueString = null; - try { - valueString = MusicUtil.convertToActualDataType(colType, valueObj); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); - } - fieldValueString.append(entry.getKey() + "= ?"); - queryObject.addValue(valueString); - if (counter != valuesMap.size() - 1) { - fieldValueString.append(","); - } - counter = counter + 1; - } - String ttl = this.getTtl(); - String timestamp = this.getTimestamp(); - - queryObject.appendQueryString("UPDATE " + this.getKeyspaceName() + "." + this.getTableName() + " "); - if ((ttl != null) && (timestamp != null)) { - logger.info("both there"); - queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); - queryObject.addValue(Integer.parseInt(ttl)); - queryObject.addValue(Long.parseLong(timestamp)); - } - - if ((ttl != null) && (timestamp == null)) { - logger.info("ONLY TTL there"); - queryObject.appendQueryString(" USING TTL ?"); - queryObject.addValue(Integer.parseInt(ttl)); - } - - if ((ttl == null) && (timestamp != null)) { - logger.info("ONLY timestamp there"); - queryObject.appendQueryString(" USING TIMESTAMP ?"); - queryObject.addValue(Long.parseLong(timestamp)); - } - - // get the row specifier - RowIdentifier rowId = null; - try { - rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject); - this.setRowIdString(rowId.rowIdString); - this.setPrimarKeyValue(rowId.primarKeyValue); - if(rowId == null || rowId.primarKeyValue.isEmpty()) { - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap()).build();*/ - - throw new MusicQueryException("Mandatory WHERE clause is missing. Please check the input request.", - Status.BAD_REQUEST.getStatusCode()); - } - } catch (MusicQueryException ex) { - throw new MusicQueryException("Mandatory WHERE clause is missing. Please check the input request.", - Status.BAD_REQUEST.getStatusCode()); - - }catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes - .GENERALSERVICEERROR, ex); - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();*/ - - throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode()); - - } - - - - queryObject.appendQueryString( - " SET " + fieldValueString + " WHERE " + rowId.rowIdString + ";"); - - - - // get the conditional, if any - Condition conditionInfo; - if (this.getConditions() == null) { - conditionInfo = null; - } else { - // to avoid parsing repeatedly, just send the select query to obtain row - PreparedQueryObject selectQuery = new PreparedQueryObject(); - selectQuery.appendQueryString("SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " - + rowId.rowIdString + ";"); - selectQuery.addValue(rowId.primarKeyValue); - conditionInfo = new Condition(this.getConditions(), selectQuery); - } - - ReturnType operationResult = null; - long jsonParseCompletionTime = System.currentTimeMillis(); - - if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency") != null) { - if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) { - queryObject.setConsistency(this.getConsistencyInfo().get("consistency")); - } else { - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR) - .setError("Invalid Consistency type").toMap()).build();*/ - - logger.error("Invalid Consistency type"); - throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode()); - } - } - - queryObject.setOperation("update"); - - return queryObject; - } - - private class RowIdentifier { - public String primarKeyValue; - public StringBuilder rowIdString; - @SuppressWarnings("unused") - public PreparedQueryObject queryObject; // the string with all the row - // identifiers separated by AND - - public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, - PreparedQueryObject queryObject) { - this.primarKeyValue = primaryKeyValue; - this.rowIdString = rowIdString; - this.queryObject = queryObject; - } - } - - /** - * - * @param keyspace - * @param tablename - * @param rowParams - * @param queryObject - * @return - * @throws MusicServiceException - */ - private RowIdentifier getRowIdentifier(String keyspace, String tablename, - MultivaluedMap rowParams, PreparedQueryObject queryObject) - throws MusicServiceException { - StringBuilder rowSpec = new StringBuilder(); - int counter = 0; - TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); - if (tableInfo == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - throw new MusicServiceException( - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - } - StringBuilder primaryKey = new StringBuilder(); - for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { - String keyName = entry.getKey(); - List valueList = entry.getValue(); - String indValue = valueList.get(0); - DataType colType = null; - Object formattedValue = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - formattedValue = MusicUtil.convertToActualDataType(colType, indValue); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); - } - if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { - primaryKey.append(indValue); - } - rowSpec.append(keyName + "= ?"); - queryObject.addValue(formattedValue); - if (counter != rowParams.size() - 1) { - rowSpec.append(" AND "); - } - counter = counter + 1; - } - return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); - } - -} diff --git a/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java b/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java deleted file mode 100644 index fbfc0de6..00000000 --- a/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.eelf.healthcheck; - -import java.util.UUID; - -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.MusicCore; - -import com.datastax.driver.core.ConsistencyLevel; - -/** - * @author inam - * - */ -public class MusicHealthCheck { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); - - private String cassandrHost; - - public String getCassandraStatus(String consistency) { - logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra"); - - boolean result = false; - UUID randomUUID = UUID.randomUUID(); - try { - result = getAdminKeySpace(consistency, randomUUID); - } catch( Exception e) { - if(e.getMessage().toLowerCase().contains("unconfigured table healthcheck")) { - logger.error("Error", e); - logger.debug("Creating table...."); - try { - boolean ksresult = createKeyspace(); - if(ksresult) { - result = getAdminKeySpace(consistency, randomUUID); - } - } catch (MusicServiceException e1) { - logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN, e1); - } catch (MusicQueryException e1) { - logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN,e1); - } - } else { - logger.error("Error", e); - return "One or more nodes are down or not responding."; - } - } - try { - cleanHealthCheckId(randomUUID); - } catch (MusicServiceException | MusicQueryException e) { - logger.error("Error while cleaning healthcheck record id...", e); - } - if (result) { - return "ACTIVE"; - } else { - logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra Service is not responding"); - return "INACTIVE"; - } - } - - private Boolean getAdminKeySpace(String consistency, UUID randomUUID) throws MusicServiceException,MusicQueryException { - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("insert into admin.healthcheck (id) values (?)"); - pQuery.addValue(randomUUID); - ResultType rs = null; - rs = MusicCore.nonKeyRelatedPut(pQuery, consistency); - logger.info(rs.toString()); - return null != rs; - - } - - private void cleanHealthCheckId(UUID randomUUID) throws MusicServiceException, MusicQueryException { - String cleanQuery = "delete from admin.healthcheck where id = ?"; - PreparedQueryObject deleteQueryObject = new PreparedQueryObject(); - deleteQueryObject.appendQueryString(cleanQuery); - deleteQueryObject.addValue(randomUUID); - MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "eventual"); - logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra healthcheck responded and cleaned up."); - } - - - - private boolean createKeyspace() throws MusicServiceException,MusicQueryException { - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("CREATE TABLE admin.healthcheck (id uuid PRIMARY KEY)"); - ResultType rs = null ; - rs = MusicCore.nonKeyRelatedPut(pQuery, ConsistencyLevel.ONE.toString()); - return rs != null && rs.getResult().toLowerCase().contains("success"); - } - - public String getCassandrHost() { - return cassandrHost; - } - - public void setCassandrHost(String cassandrHost) { - this.cassandrHost = cassandrHost; - } - -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java b/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java deleted file mode 100644 index a8012c82..00000000 --- a/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.eelf.logging; - -import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; -import java.net.InetAddress; -import java.text.MessageFormat; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import javax.servlet.http.HttpServletRequest; -import org.slf4j.MDC; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.configuration.SLF4jWrapper; - -public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { - - public static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - public static final EELFLogger applicationLogger = - EELFManager.getInstance().getApplicationLogger(); - public static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - public static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - public static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); - public static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); - - private String className; - private static ConcurrentMap classMap = new ConcurrentHashMap<>(); - - public EELFLoggerDelegate(final String className) { - super(className); - this.className = className; - } - - /** - * Convenience method that gets a logger for the specified class. - * - * @see #getLogger(String) - * - * @param clazz - * @return Instance of EELFLoggerDelegate - */ - public static EELFLoggerDelegate getLogger(Class clazz) { - return getLogger(clazz.getName()); - } - - /** - * Gets a logger for the specified class name. If the logger does not already exist in the map, - * this creates a new logger. - * - * @param className If null or empty, uses EELFLoggerDelegate as the class name. - * @return Instance of EELFLoggerDelegate - */ - public static EELFLoggerDelegate getLogger(final String className) { - String classNameNeverNull = className == null || "".equals(className) - ? EELFLoggerDelegate.class.getName() - : className; - EELFLoggerDelegate delegate = classMap.get(classNameNeverNull); - if (delegate == null) { - delegate = new EELFLoggerDelegate(className); - classMap.put(className, delegate); - } - return delegate; - } - - /** - * Logs a message at the lowest level: trace. - * - * @param logger - * @param msg - */ - public void trace(EELFLogger logger, String msg) { - if (logger.isTraceEnabled()) { - logger.trace(msg); - } - } - - /** - * Logs a message with parameters at the lowest level: trace. - * - * @param logger - * @param msg - * @param arguments - */ - public void trace(EELFLogger logger, String msg, Object... arguments) { - if (logger.isTraceEnabled()) { - logger.trace(msg, arguments); - } - } - - /** - * Logs a message and throwable at the lowest level: trace. - * - * @param logger - * @param msg - * @param th - */ - public void trace(EELFLogger logger, String msg, Throwable th) { - if (logger.isTraceEnabled()) { - logger.trace(msg, th); - } - } - - /** - * Logs a message at the second-lowest level: debug. - * - * @param logger - * @param msg - */ - public void debug(EELFLogger logger, String msg) { - if (logger.isDebugEnabled()) { - logger.debug(msg); - } - } - - /** - * Logs a message with parameters at the second-lowest level: debug. - * - * @param logger - * @param msg - * @param arguments - */ - public void debug(EELFLogger logger, String msg, Object... arguments) { - if (logger.isDebugEnabled()) { - logger.debug(msg, arguments); - } - } - - /** - * Logs a message and throwable at the second-lowest level: debug. - * - * @param logger - * @param msg - * @param th - */ - public void debug(EELFLogger logger, String msg, Throwable th) { - if (logger.isDebugEnabled()) { - logger.debug(msg, th); - } - } - - /** - * Logs a message at info level. - * - * @param logger - * @param msg - */ - public void info(EELFLogger logger, String msg) { - logger.info(className + " - "+msg); - } - - /** - * Logs a message with parameters at info level. - * - * @param logger - * @param msg - * @param arguments - */ - public void info(EELFLogger logger, String msg, Object... arguments) { - logger.info(msg, arguments); - } - - /** - * Logs a message and throwable at info level. - * - * @param logger - * @param msg - * @param th - */ - public void info(EELFLogger logger, String msg, Throwable th) { - logger.info(msg, th); - } - - /** - * Logs a message at warn level. - * - * @param logger - * @param msg - */ - public void warn(EELFLogger logger, String msg) { - logger.warn(msg); - } - - /** - * Logs a message with parameters at warn level. - * - * @param logger - * @param msg - * @param arguments - */ - public void warn(EELFLogger logger, String msg, Object... arguments) { - logger.warn(msg, arguments); - } - - /** - * Logs a message and throwable at warn level. - * - * @param logger - * @param msg - * @param th - */ - public void warn(EELFLogger logger, String msg, Throwable th) { - logger.warn(msg, th); - } - - /** - * Logs a message at error level. - * - * @param logger - * @param msg - * - */ - public void error(EELFLogger logger, String msg) { - logger.error(className+ " - " + msg); - } - - /** - * Logs a message at error level. - * - * @param logger - * @param msg - */ - public void error(EELFLogger logger, Exception e) { - logger.error(className+ " - ", e); - } - - /** - * Logs a message with parameters at error level. - * - * @param logger - * @param msg - * @param arguments - * - */ - public void error(EELFLogger logger, String msg, Object... arguments) { - logger.error(msg, arguments); - } - - /** - * Logs a message with parameters at error level. - * - * @param logger - * @param msg - * @param arguments - */ - public void error(EELFLogger logger, Exception e, Object... arguments) { - logger.error("Exception", e, arguments); - } - - /** - * Logs a message and throwable at error level. - * - * @param logger - * @param msg - * @param th - */ - public void error(EELFLogger logger, String msg, Throwable th) { - logger.error(msg, th); - } - - /** - * Logs a message with the associated alarm severity at error level. - * - * @param logger - * @param msg - * @param severtiy - */ - public void error(EELFLogger logger, String msg, Object /* AlarmSeverityEnum */ severtiy) { - logger.error(msg); - } - - /** - * Initializes the logger context. - */ - public void init() { - setGlobalLoggingContext(); - final String msg = - "############################ Logging is started. ############################"; - // These loggers emit the current date-time without being told. - info(applicationLogger, msg); - error(errorLogger, msg); - debug(debugLogger, msg); - info(auditLogger, msg); - info(metricsLogger, msg); - info(securityLogger, msg); - - } - - /** - * Builds a message using a template string and the arguments. - * - * @param message - * @param args - * @return - */ - private String formatMessage(String message, Object... args) { - StringBuilder sbFormattedMessage = new StringBuilder(); - if (args != null && args.length > 0 && message != null && message != "") { - MessageFormat mf = new MessageFormat(message); - sbFormattedMessage.append(mf.format(args)); - } else { - sbFormattedMessage.append(message); - } - - return sbFormattedMessage.toString(); - } - - /** - * Loads all the default logging fields into the MDC context. - */ - private void setGlobalLoggingContext() { - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - errorLogger.error("setGlobalLoggingContext failed", e); - } - } - - public static void mdcPut(String key, String value) { - MDC.put(key, value); - } - - public static String mdcGet(String key) { - return MDC.get(key); - } - - public static void mdcRemove(String key) { - MDC.remove(key); - } - - /** - * Loads the RequestId/TransactionId into the MDC which it should be receiving with an each - * incoming REST API request. Also, configures few other request based logging fields into the - * MDC context. - * - * @param req - * @param appName - */ - public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req, - String appName) { - // Load the default fields - setGlobalLoggingContext(); - - // Load the request based fields - if (req != null) { - // Rest Path - MDC.put(MDC_SERVICE_NAME, req.getServletPath()); - - // Client IPAddress i.e. IPAddress of the remote host who is making - // this request. - String clientIPAddress = req.getHeader("X-FORWARDED-FOR"); - if (clientIPAddress == null) { - clientIPAddress = req.getRemoteAddr(); - } - } - } -} diff --git a/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java b/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java deleted file mode 100644 index bac02afa..00000000 --- a/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.eelf.logging; - -import java.io.IOException; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; - -import org.springframework.stereotype.Component; - - -/** - * This filter filter/modifies outbound http responses just before sending back to client. - * - * @author sp931a - * - */ -@Component -public class MusicContainerFilter implements ContainerResponseFilter { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicContainerFilter.class); - - public MusicContainerFilter() { - - } - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) - throws IOException { - if (null != EELFLoggerDelegate.mdcGet("transactionId")) { - EELFLoggerDelegate.mdcRemove("transactionId"); - } - - if (null != EELFLoggerDelegate.mdcGet("conversationId")) { - EELFLoggerDelegate.mdcRemove("conversationId"); - } - - if (null != EELFLoggerDelegate.mdcGet("clientId")) { - EELFLoggerDelegate.mdcRemove("clientId"); - } - - if (null != EELFLoggerDelegate.mdcGet("messageId")) { - EELFLoggerDelegate.mdcRemove("messageId"); - } - } - -} diff --git a/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java b/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java deleted file mode 100644 index c8c6ba65..00000000 --- a/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ -package org.onap.music.eelf.logging; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.music.authentication.AuthorizationError; -import org.onap.music.main.MusicUtil; - -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * This is the first filter in the chain to be executed before cadi - * authentication. The priority has been set in MusicApplication - * through filter registration bean - * - * The responsibility of this filter is to validate header values as per - * contract and write it to MDC and http response header back. - * - * - * @author sp931a - * - */ - -public class MusicLoggingServletFilter implements Filter { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicLoggingServletFilter.class); - // client transaction id, specific to client system, set in properties - public static final String CONVERSATION_ID = MusicUtil.getConversationIdPrefix() + "ConversationId"; - - // can be used as correlation-id in case of callback, also this can be passed to - // other services for tracking. - public static final String MESSAGE_ID = MusicUtil.getMessageIdPrefix() + "MessageId"; - - // client id would be the unique client source-system-id, i;e VALET or CONDUCTOR - // etc - public static final String CLIENT_ID = MusicUtil.getClientIdPrefix() + "ClientId"; - - // unique transaction of the source system - private static final String TRANSACTION_ID = MusicUtil.getTransIdPrefix() + "Transaction-Id"; - - public MusicLoggingServletFilter() throws ServletException { - super(); - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - - logger.info(EELFLoggerDelegate.securityLogger, - "In MusicLogginServletFilter doFilter start() :: [\"+MusicUtil.getTransIdRequired()+\",\"+MusicUtil.getConversationIdRequired()+\",\"+MusicUtil.getClientIdRequired()+\",\"+MusicUtil.getMessageIdRequired()"); - - HttpServletRequest httpRequest = null; - HttpServletResponse httpResponse = null; - Map headerMap = null; - Map upperCaseHeaderMap = null; - - if (null != request && null != response) { - httpRequest = (HttpServletRequest) request; - httpResponse = (HttpServletResponse) response; - - headerMap = getHeadersInfo(httpRequest); - - // The custom header values automatically converted into lower case, not sure - // why ? So i had to covert all keys to upper case - // The response header back to client will have all custom header values as - // upper case. - upperCaseHeaderMap = headerMap.entrySet().stream() - .collect(Collectors.toMap(entry -> entry.getKey().toUpperCase(), entry -> entry.getValue())); - // Enable/disable keys are present in /opt/app/music/etc/music.properties - - if (MusicUtil.getTransIdRequired() - && !upperCaseHeaderMap.containsKey(TRANSACTION_ID.toUpperCase())) { - populateError(httpResponse, "Transaction id '" + TRANSACTION_ID - + "' required on http header"); - return; - } else { - populateMDCAndResponseHeader(upperCaseHeaderMap, TRANSACTION_ID, "transactionId", - MusicUtil.getTransIdRequired(), httpResponse); - } - - if (MusicUtil.getConversationIdRequired() - && !upperCaseHeaderMap.containsKey(CONVERSATION_ID.toUpperCase())) { - populateError(httpResponse, "Conversation Id '" + CONVERSATION_ID - + "' required on http header"); - return; - } else { - populateMDCAndResponseHeader(upperCaseHeaderMap, CONVERSATION_ID, "conversationId", - MusicUtil.getConversationIdRequired(), httpResponse); - } - - if (MusicUtil.getMessageIdRequired() - && !upperCaseHeaderMap.containsKey(MESSAGE_ID.toUpperCase())) { - populateError(httpResponse, "Message Id '" + MESSAGE_ID - + "' required on http header"); - return; - } else { - populateMDCAndResponseHeader(upperCaseHeaderMap, MESSAGE_ID, "messageId", - MusicUtil.getMessageIdRequired(), httpResponse); - } - - if (MusicUtil.getClientIdRequired() - && !upperCaseHeaderMap.containsKey(CLIENT_ID.toUpperCase())) { - populateError(httpResponse, "Client Id '" + CLIENT_ID - + "' required on http header"); - return; - } else { - populateMDCAndResponseHeader(upperCaseHeaderMap, CLIENT_ID, "clientId", - MusicUtil.getClientIdRequired(), httpResponse); - } - - } - - logger.info(EELFLoggerDelegate.securityLogger, - "In MusicLogginServletFilter doFilter. Header values validated sucessfully"); - - chain.doFilter(request, response); - } - - private void populateError(HttpServletResponse httpResponse, String errMsg) throws IOException { - AuthorizationError authError = new AuthorizationError(); - authError.setResponseCode(HttpServletResponse.SC_BAD_REQUEST); - authError.setResponseMessage(errMsg); - - byte[] responseToSend = restResponseBytes(authError); - httpResponse.setHeader("Content-Type", "application/json"); - - // ideally the http response code should be 200, as this is a biz validation - // failure. For now, keeping it consistent with other places. - httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); - httpResponse.getOutputStream().write(responseToSend); - } - - private void populateMDCAndResponseHeader(Map headerMap, String idKey, String mdcKey, - boolean isRequired, HttpServletResponse httpResponse) { - - idKey = idKey.trim().toUpperCase(); - - // 1. setting the keys & value in MDC for future use 2.setting the values in - // http response header back to client. - if (isRequired && (headerMap.containsKey(idKey))) { - EELFLoggerDelegate.mdcPut(mdcKey, headerMap.get(idKey)); - httpResponse.addHeader(idKey, headerMap.get(idKey)); - } else { - // do nothing - } - } - - private Map getHeadersInfo(HttpServletRequest request) { - - Map map = new HashMap(); - - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String key = (String) headerNames.nextElement(); - String value = request.getHeader(key); - map.put(key, value); - } - - return map; - } - - private byte[] restResponseBytes(AuthorizationError eErrorResponse) throws IOException { - String serialized = new ObjectMapper().writeValueAsString(eErrorResponse); - return serialized.getBytes(); - } -} diff --git a/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java b/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java deleted file mode 100644 index 5af3661c..00000000 --- a/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Copyright (c) 2019 IBM Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; - -/** - * @author inam - * - */ -public enum AppMessages { - - - - /* - * 100-199 Security/Permission Related - Authentication problems - * [ERR100E] Missing Information - * [ERR101E] Authentication error occured - * - * 200-299 Availability/Timeout Related/IO - connectivity error - connection timeout - * [ERR200E] Connectivity - * [ERR201E] Host not available - * [ERR202E] Error while connecting to Cassandra cluster - * [ERR203E] IO Error has occured - * [ERR204E] Execution Interrupted - * [ERR205E] Session Expired - * [ERR206E] Cache not authenticated - * - * - * 300-399 Data Access/Integrity Related - * [ERR300E] Incorrect data - * - * 400-499 - Cassandra Query Related - * [ERR400E] Error while processing prepared query object - * [ERR401E] Executing Session Failure for Request - * [ERR402E] Ill formed queryObject for the request - * [ERR403E] Error processing Prepared Query Object - * - * 500-599 - Locking Related - * [ERR500E] Invalid lock - * [ERR501E] Locking Error has occured - * [ERR502E] Deprecated - * [ERR503E] Failed to aquire lock store handle - * [ERR504E] Failed to create Lock Reference - * [ERR505E] Lock does not exist - * [ERR506E] Failed to aquire lock - * [ERR507E] Lock not aquired - * [ERR508E] Lock state not set - * [ERR509E] Lock not destroyed - * [ERR510E] Lock not released - * [ERR511E] Lock not deleted - * [ERR512E] Deprecated - * - * - * 600 - 699 - Music Service Errors - * [ERR600E] Error initializing the cache - * - * 700-799 Schema Interface Type/Validation - received Pay-load checksum is - * invalid - received JSON is not valid - * - * 800-899 Business/Flow Processing Related - check out to service is not - * allowed - Roll-back is done - failed to generate heat file - * - * - * 900-999 Unknown Errors - Unexpected exception - * [ERR900E] Unexpected error occured - * [ERR901E] Number format exception - * - * - * 1000-1099 Reserved - do not use - * - */ - - - - - MISSINGINFO("[ERR100E]", "Missing Information ","Details: NA", "Please check application credentials and/or headers"), - AUTHENTICATIONERROR("[ERR101E]", "Authentication error occured ","Details: NA", "Please verify application credentials"), - CONNCECTIVITYERROR("[ERR200E]"," Connectivity error","Details: NA ","Please check connectivity to external resources"), - HOSTUNAVAILABLE("[ERR201E]","Host not available","Details: NA","Please verify the host details"), - CASSANDRACONNECTIVITY("[ERR202E]","Error while connecting to Cassandra cluster",""," Please check cassandra cluster details"), - IOERROR("[ERR203E]","IO Error has occured","","Please check IO"), - EXECUTIONINTERRUPTED("[ERR204E]"," Execution Interrupted","",""), - SESSIONEXPIRED("[ERR205E]"," Session Expired","","Session has expired."), - CACHEAUTHENTICATION("[ERR206E]","Cache not authenticated",""," Cache not authenticated"), - - INCORRECTDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"), - MULTIPLERECORDS("[ERR301E]"," Multiple records found",""," Please verify the request payload and try again"), - ALREADYEXIST("[ERR302E]"," Record already exist",""," Please verify the request payload and try again"), - MISSINGDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"), - - QUERYERROR("[ERR400E]","Error while processing prepared query object",""," Please verify the query"), - SESSIONFAILED("[ERR401E]","Executing Session Failure for Request","","Please verify the session and request"), - - INVALIDLOCK("[ERR500E]"," Invalid lock or acquire failed",""," Lock is not valid to aquire"), - LOCKINGERROR("[ERR501E]"," Locking Error has occured",""," Locking Error has occured"), - LOCKHANDLE("[ERR503E]","Failed to aquire lock store handle",""," Failed to aquire lock store handle"), - CREATELOCK("[ERR504E]","Failed to aquire lock store handle ","","Failed to aquire lock store handle "), - LOCKSTATE("[ERR508E]"," Lock state not set",""," Lock state not set"), - DESTROYLOCK("[ERR509E]"," Lock not destroyed",""," Lock not destroyed"), - RELEASELOCK("[ERR510E]"," Lock not released",""," Lock not released"), - DELTELOCK("[ERR511E]",""," Lock not deleted "," Lock not deleted "), - CACHEERROR("[ERR600E]"," Error initializing the cache",""," Error initializing the cache"), - - UNKNOWNERROR("[ERR900E]"," Unexpected error occured",""," Please check logs for details"); - - - - - private ErrorTypes eType; - private ErrorSeverity alarmSeverity; - private ErrorSeverity errorSeverity; - private String errorCode; - private String errorDescription; - private String details; - private String resolution; - - - AppMessages(String errorCode, String errorDescription, String details,String resolution) { - - this.errorCode = errorCode; - this.errorDescription = errorDescription; - this.details = details; - this.resolution = resolution; - } - - - public ErrorTypes getEType() { - return eType; - } - - public ErrorSeverity getAlarmSeverity() { - return alarmSeverity; - } - public ErrorSeverity getErrorSeverity() { - return errorSeverity; - } - - public void setDetails(String details){ this.details=details; } - - public String getDetails() { - return this.details; - } - - public void setResolution(String resolution){ this.resolution=resolution; } - - public String getResolution() { - return this.resolution; - } - - public void setErrorCode(String errorCode){ this.errorCode=errorCode; } - - public String getErrorCode() { - return this.errorCode; - } - - public void setErrorDescription(String errorDescription){ this.errorDescription=errorDescription; } - - public String getErrorDescription() { - return this.errorDescription; - } - - - - - - - -} diff --git a/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java b/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java deleted file mode 100644 index 91ee3473..00000000 --- a/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; - - - -/** - * @author inam - * - */ -public enum ErrorCodes { - - - /* - * 100-199 Security/Permission Related - Authentication problems - * [ERR100E] Missing Information - * [ERR101E] Authentication error occured - * - * 200-299 Availability/Timeout Related/IO - connectivity error - connection timeout - * [ERR200E] Connectivity - * [ERR201E] Host not available - * [ERR202E] Error while connecting to Cassandra cluster - * [ERR203E] IO Error has occured - * [ERR204E] Execution Interrupted - * [ERR205E] Session Expired - * [ERR206E] Cache not authenticated - * - * - * 300-399 Data Access/Integrity Related - * - * 400-499 - Cassandra Query Related - * [ERR400E] Error while processing prepared query object - * [ERR401E] Executing Session Failure for Request - * [ERR402E] Ill formed queryObject for the request - * [ERR403E] Error processing Prepared Query Object - * - * 500-599 - Zookeepr/Locking Related - * [ERR500E] Invalid lock - * [ERR501E] Locking Error has occured - * [ERR502E] Zookeeper error has occured - * [ERR503E] Failed to aquire lock store handle - * [ERR504E] Failed to create Lock Reference - * [ERR505E] Lock does not exist - * [ERR506E] Failed to aquire lock - * [ERR507E] Lock not aquired - * [ERR508E] Lock state not set - * [ERR509E] Lock not destroyed - * [ERR510E] Lock not released - * [ERR511E] Lock not deleted - * [ERR512E] Failed to get Lock Handle - * - * - * 600 - 699 - Music Service Errors - * [ERR600E] Error initializing the cache - * - * 700-799 Schema Interface Type/Validation - received Pay-load checksum is - * invalid - received JSON is not valid - * - * 800-899 Business/Flow Processing Related - check out to service is not - * allowed - Roll-back is done - failed to generate heat file - * - * - * 900-999 Unknown Errors - Unexpected exception - * [ERR900E] Unexpected error occured - * [ERR901E] Number format exception - * - * - * 1000-1099 Reserved - do not use - * - */ - - /*SUCCESS("Success"), FAILURE("Failure"); - - private String result; - - ResultType(String result) { - this.result = result; - } - - public String getResult() { - return result; - } -*/ - - - -} diff --git a/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java b/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java deleted file mode 100644 index 4e798239..00000000 --- a/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; - -/** - * @author inam - * - */ -public enum ErrorSeverity { - INFO, - WARN, - ERROR, - FATAL, - CRITICAL, - MAJOR, - MINOR, - NONE, -} diff --git a/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java b/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java deleted file mode 100644 index 9bdbf20f..00000000 --- a/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; - -import com.att.eelf.i18n.EELFResolvableErrorEnum; - -/** - * @author inam - * - */ -public enum ErrorTypes implements EELFResolvableErrorEnum { - - - CONNECTIONERROR, - SESSIONEXPIRED, - AUTHENTICATIONERROR, - CACHEERROR, - SERVICEUNAVAILABLE, - QUERYERROR, - DATAERROR, - GENERALSERVICEERROR, - MUSICSERVICEERROR, - LOCKINGERROR, - UNKNOWN, - -} diff --git a/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java b/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java deleted file mode 100644 index ab44fd6e..00000000 --- a/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -/** - * @author inam - * - */ -public class MusicAuthenticationException extends Exception { - - /** - * - */ - public MusicAuthenticationException() { - - } - - /** - * @param message - */ - public MusicAuthenticationException(String message) { - super(message); - - } - - /** - * @param cause - */ - public MusicAuthenticationException(Throwable cause) { - super(cause); - - } - - /** - * @param message - * @param cause - */ - public MusicAuthenticationException(String message, Throwable cause) { - super(message, cause); - - } - - /** - * @param message - * @param cause - * @param enableSuppression - * @param writableStackTrace - */ - public MusicAuthenticationException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - - } - -} diff --git a/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java b/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java deleted file mode 100644 index f5478e78..00000000 --- a/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -public class MusicDeadlockException extends MusicLockingException { - - public String owner = null; - public String keyspace = null; - public String table = null; - public String key = null; - - public MusicDeadlockException() { - super(); - } - - public MusicDeadlockException(String message) { - super(message); - } - - public MusicDeadlockException(Throwable cause) { - super(cause); - } - - public MusicDeadlockException(String message, Throwable cause) { - super(message, cause); - } - - public MusicDeadlockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - - public void setValues(String owner, String keyspace, String table, String key) { - this.owner = owner; - this.keyspace = keyspace; - this.table = table; - this.key = key; - } - - public String getOwner() { - return owner; - } - - public String getKeyspace() { - return keyspace; - } - - public String getTable() { - return table; - } - - public String getKey() { - return key; - } - - -} diff --git a/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java b/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java deleted file mode 100644 index c31fcf73..00000000 --- a/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -import java.io.EOFException; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -import org.codehaus.jackson.map.exc.UnrecognizedPropertyException; -import org.onap.music.main.ResultType; -import org.onap.music.response.jsonobjects.JsonResponse; - -@Provider -public class MusicExceptionMapper implements ExceptionMapper { - @Override - public Response toResponse(Exception exception) { - if(exception instanceof UnrecognizedPropertyException) { - return Response.status(Response.Status.BAD_REQUEST). - entity(new JsonResponse(ResultType.FAILURE).setError("Unknown field :"+((UnrecognizedPropertyException) exception).getUnrecognizedPropertyName()).toMap()). - build(); - } else if(exception instanceof EOFException) { - return Response.status(Response.Status.BAD_REQUEST). - entity(new JsonResponse(ResultType.FAILURE).setError("Request body cannot be empty").toMap()). - build(); - } else if(exception instanceof NullPointerException) { - return Response.status(Response.Status.BAD_REQUEST). - entity(new JsonResponse(ResultType.FAILURE).setError("NullPointerException - Please check to make sure all inputs are valid.").toMap()). - build(); - } else { - return Response.status(Response.Status.BAD_REQUEST). - entity(new JsonResponse(ResultType.FAILURE).setError(exception.getMessage()).toMap()). - build(); - } - } -} diff --git a/src/main/java/org/onap/music/exceptions/MusicLockingException.java b/src/main/java/org/onap/music/exceptions/MusicLockingException.java deleted file mode 100644 index ab70c54c..00000000 --- a/src/main/java/org/onap/music/exceptions/MusicLockingException.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -/** - * @author inam - * - */ -public class MusicLockingException extends Exception { - - /** - * - */ - public MusicLockingException() { - - } - - /** - * @param message - */ - public MusicLockingException(String message) { - super(message); - - } - - /** - * @param cause - */ - public MusicLockingException(Throwable cause) { - super(cause); - - } - - /** - * @param message - * @param cause - */ - public MusicLockingException(String message, Throwable cause) { - super(message, cause); - - } - - /** - * @param message - * @param cause - * @param enableSuppression - * @param writableStackTrace - */ - public MusicLockingException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - - } - -} diff --git a/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java b/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java deleted file mode 100644 index f489cd45..00000000 --- a/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2018 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.exceptions; - -/** - * @author inam - * - */ -public class MusicPolicyVoilationException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * - */ - public MusicPolicyVoilationException() { - - } - - /** - * @param message - */ - public MusicPolicyVoilationException(String message) { - super(message); - - } - - /** - * @param cause - */ - public MusicPolicyVoilationException(Throwable cause) { - super(cause); - - } - - /** - * @param message - * @param cause - */ - public MusicPolicyVoilationException(String message, Throwable cause) { - super(message, cause); - - } - - /** - * @param message - * @param cause - * @param enableSuppression - * @param writableStackTrace - */ - public MusicPolicyVoilationException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - - } - -} diff --git a/src/main/java/org/onap/music/exceptions/MusicQueryException.java b/src/main/java/org/onap/music/exceptions/MusicQueryException.java deleted file mode 100644 index 803f993f..00000000 --- a/src/main/java/org/onap/music/exceptions/MusicQueryException.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - - - -/** - * @author inam - * - */ -public class MusicQueryException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - private int errorCode; - - - /** - * - */ - public MusicQueryException() { - super(); - } - - /** - * @param message - */ - public MusicQueryException(String message) { - super(message); - } - - - - /** - * @param message - */ - public MusicQueryException(String message, int errorCode) { - super(message); - this.errorCode = errorCode; - } - - /** - * @param cause - */ - public MusicQueryException(Throwable cause) { - super(cause); - } - - /** - * @param message - * @param cause - */ - public MusicQueryException(String message, Throwable cause) { - super(message, cause); - } - - /** - * @param message - * @param cause - * @param enableSuppression - * @param writableStackTrace - */ - public MusicQueryException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/src/main/java/org/onap/music/exceptions/MusicServiceException.java b/src/main/java/org/onap/music/exceptions/MusicServiceException.java deleted file mode 100644 index 76e1f948..00000000 --- a/src/main/java/org/onap/music/exceptions/MusicServiceException.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (C) 2018 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.exceptions; - -/** - * @author inam - * - */ -public class MusicServiceException extends Exception { - - - private int errorCode; - private String errorMessage; - - public MusicServiceException() { - super(); - } - - - public MusicServiceException(String message) { - super(message); - - } - - public MusicServiceException(String message, int errorCode) { - super(message); - this.errorCode=errorCode; - } - - public MusicServiceException(String message, int errorCode, String errorMessage) { - super(message); - this.errorCode=errorCode; - this.errorMessage=errorMessage; - } - - public MusicServiceException(Throwable cause) { - super(cause); - - } - - - public MusicServiceException(String message, Throwable cause) { - super(message, cause); - - } - - - public MusicServiceException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - - } - public void setErrorCode(int errorCode) { - this.errorCode=errorCode; - } - - public int getErrorCode() { - return errorCode; - } - public void setErrorMessage(String errorMessage) { - this.errorMessage=errorMessage; - } - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java b/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java deleted file mode 100644 index 10898476..00000000 --- a/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java +++ /dev/null @@ -1,604 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.lockingservice.cassandra; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.DeadlockDetectionUtil; -import org.onap.music.main.DeadlockDetectionUtil.OwnershipType; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.extras.codecs.enums.EnumNameCodec; - -/* - * This is the lock store that is built on top of Cassandra that is used by MUSIC to maintain lock state. - */ - -public class CassaLockStore { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CassaLockStore.class); - private static String table_prepend_name = "lockQ_"; - private MusicDataStore dsHandle; - - public CassaLockStore() { - dsHandle = new MusicDataStore(); - } - - public CassaLockStore(MusicDataStore dsHandle) { - this.dsHandle=dsHandle; - } - public class LockObject{ - private boolean isLockOwner; - private String lockRef; - private String createTime; - private String acquireTime; - private LockType locktype; - // Owner is the self-declared client which "owns" this row. It is used for deadlock detection. It is not (directly) related to isLockOwner. - private String owner; - public LockObject(boolean isLockOwner, String lockRef, String createTime, String acquireTime, LockType locktype, String owner) { - this.setIsLockOwner(isLockOwner); - this.setLockRef(lockRef); - this.setAcquireTime(acquireTime); - this.setCreateTime(createTime); - this.setLocktype(locktype); - this.setOwner(owner); - } - public boolean getIsLockOwner() { - return isLockOwner; - } - public void setIsLockOwner(boolean isLockOwner) { - this.isLockOwner = isLockOwner; - } - public String getAcquireTime() { - return acquireTime; - } - public void setAcquireTime(String acquireTime) { - this.acquireTime = acquireTime; - } - public String getCreateTime() { - return createTime; - } - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - public String getLockRef() { - return lockRef; - } - public void setLockRef(String lockRef) { - this.lockRef = lockRef; - } - public LockType getLocktype() { - return locktype; - } - public void setLocktype(LockType locktype) { - this.locktype = locktype; - } - public String getOwner() { - return owner; - } - public void setOwner(String owner) { - this.owner = owner; - } - } - - /** - * - * This method creates a shadow locking table for every main table in Cassandra. This table tracks all information regarding locks. - * @param keyspace of the application. - * @param table of the application. - * @return true if the operation was successful. - * @throws MusicServiceException - * @throws MusicQueryException - */ - public boolean createLockQueue(String keyspace, String table) throws MusicServiceException, MusicQueryException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Create lock queue/table for " + keyspace+"."+table); - table = table_prepend_name+table; - String tabQuery = "CREATE TABLE IF NOT EXISTS "+keyspace+"."+table - + " ( key text, lockReference bigint, createTime text, acquireTime text, guard bigint static, " - + "lockType text, owner text, PRIMARY KEY ((key), lockReference) ) " - + "WITH CLUSTERING ORDER BY (lockReference ASC);"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - - queryObject.appendQueryString(tabQuery); - boolean result; - result = dsHandle.executePut(queryObject, "eventual"); - return result; - } - - /** - * This method creates a lock reference for each invocation. The lock references are monotonically increasing timestamps. - * @param keyspace of the locks. - * @param table of the locks. - * @param lockName is the primary key of the lock table - * @param lockType is the type of lock (read/write) - * @param owner is the owner of the lock (optional, for deadlock detection) - * @return the UUID lock reference. - * @throws MusicServiceException - * @throws MusicQueryException - */ - public String genLockRefandEnQueue(String keyspace, String table, String lockName, LockType locktype, String owner) throws MusicServiceException, MusicQueryException, MusicLockingException { - return genLockRefandEnQueue(keyspace, table, lockName, locktype, owner, 0); - } - - private String genLockRefandEnQueue(String keyspace, String table, String lockName, LockType locktype, String owner, int count) throws MusicServiceException, MusicQueryException, MusicLockingException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Create " + locktype + " lock reference for " + keyspace + "." + table + "." + lockName); - String lockTable =""; - lockTable = table_prepend_name+table; - - PreparedQueryObject queryObject = new PreparedQueryObject(); - String selectQuery = "SELECT guard FROM " + keyspace + "." + lockTable + " WHERE key=?;"; - - queryObject.addValue(lockName); - queryObject.appendQueryString(selectQuery); - ResultSet gqResult = dsHandle.executeOneConsistencyGet(queryObject); - List latestGuardRow = gqResult.all(); - - long prevGuard = 0; - long lockRef = 1; - if (!latestGuardRow.isEmpty()) { - prevGuard = latestGuardRow.get(0).getLong(0); - lockRef = prevGuard + 1; - } - - long lockEpochMillis = System.currentTimeMillis(); - - logger.info(EELFLoggerDelegate.applicationLogger, - "Created lock reference for " + keyspace + "." + lockTable + "." + lockName + ":" + lockRef); - - queryObject = new PreparedQueryObject(); - - String insQuery = "BEGIN BATCH" + - " UPDATE " + keyspace + "." + lockTable + - " SET guard=? WHERE key=? IF guard = " + (prevGuard == 0 ? "NULL" : "?") +";" + - " INSERT INTO " + keyspace + "." + lockTable + - "(key, lockReference, createTime, acquireTime, lockType, owner) VALUES (?,?,?,?,?,?) IF NOT EXISTS; APPLY BATCH;"; - - queryObject.addValue(lockRef); - queryObject.addValue(lockName); - if (prevGuard != 0) - queryObject.addValue(prevGuard); - - queryObject.addValue(lockName); - queryObject.addValue(lockRef); - queryObject.addValue(String.valueOf(lockEpochMillis)); - queryObject.addValue("0"); - queryObject.addValue(locktype); - queryObject.addValue(owner); - queryObject.appendQueryString(insQuery); - boolean pResult = dsHandle.executePut(queryObject, "critical"); - if (!pResult) {// couldn't create lock ref, retry - count++; - if (count > MusicUtil.getRetryCount()) { - logger.warn(EELFLoggerDelegate.applicationLogger, "Unable to create lock reference"); - throw new MusicLockingException("Unable to create lock reference"); - } - return genLockRefandEnQueue(keyspace, table, lockName, locktype, owner, count); - } - return "$" + keyspace + "." + table + "." + lockName + "$" + String.valueOf(lockRef); - } - - /** - * Returns a result set containing the list of clients waiting for a particular lock - * - * @param keyspace - * @param table - * @param key - * @return list of lockrefs in the queue - * @throws MusicServiceException - * @throws MusicQueryException - */ - public List getLockQueue(String keyspace, String table, String key) - throws MusicServiceException, MusicQueryException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Getting the queue for " + keyspace + "." + table + "." + key); - table = table_prepend_name + table; - String selectQuery = "select * from " + keyspace + "." + table + " where key='" + key + "';"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(selectQuery); - ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); - ArrayList lockQueue = new ArrayList<>(); - for (Row row : rs) { - lockQueue.add(Long.toString(row.getLong("lockReference"))); - } - return lockQueue; - } - - - /** - * Returns a result set containing the list of clients waiting for a particular lock - * - * @param keyspace - * @param table - * @param key - * @return size of lockrefs queue - * @throws MusicServiceException - * @throws MusicQueryException - */ - public long getLockQueueSize(String keyspace, String table, String key) - throws MusicServiceException, MusicQueryException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Getting the queue size for " + keyspace + "." + table + "." + key); - table = table_prepend_name + table; - String selectQuery = "select count(*) from " + keyspace + "." + table + " where key='" + key + "';"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(selectQuery); - ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); - return rs.one().getLong("count"); - } - - - /** - * This method returns the top of lock table/queue for the key. - * - * @param keyspace of the application. - * @param table of the application. - * @param key is the primary key of the application table - * @return the UUID lock reference. Returns LockObject.isLockOwner=false if there is no owner or the - * lock doesn't exist - * @throws MusicServiceException - * @throws MusicQueryException - */ - public LockObject peekLockQueue(String keyspace, String table, String key) - throws MusicServiceException, MusicQueryException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Peek in lock table for " + keyspace + "." + table + "." + key); - table = table_prepend_name + table; - String selectQuery = "select * from " + keyspace + "." + table + " where key='" + key + "' LIMIT 1;"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(selectQuery); - ResultSet results = dsHandle.executeOneConsistencyGet(queryObject); - Row row = results.one(); - if (row == null || row.isNull("lockReference")) { - return new LockObject(false, null, null, null, null, null); - } - String lockReference = "" + row.getLong("lockReference"); - String createTime = row.getString("createTime"); - String acquireTime = row.getString("acquireTime"); - LockType locktype = row.get("lockType", LockType.class); - String owner = row.getString("owner"); - - return new LockObject(true, lockReference, createTime, acquireTime, locktype, owner); - } - - public List getCurrentLockHolders(String keyspace, String table, String key) - throws MusicServiceException, MusicQueryException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Getting lockholders in lock table for " + keyspace + "." + table + "." + key); - String origTable = table; - table = table_prepend_name + table; - String selectQuery = "select * from " + keyspace + "." + table + " where key=?;"; - List lockHolders = new ArrayList<>(); - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(selectQuery); - queryObject.addValue(key); - ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); - boolean topOfQueue = true; - StringBuilder lock = new StringBuilder(). - append("$").append(keyspace).append(".").append(origTable). - append(".").append(key).append("$"); - StringBuilder lockReference = new StringBuilder(); - for (Row row : rs) { - if ( row.isNull("lockReference") ) { - return lockHolders; - } - lockReference.append(lock).append(row.getLong("lockReference")); - if (row.get("lockType", LockType.class)!=LockType.WRITE) { - if (topOfQueue) { - lockHolders.add(lockReference.toString()); - break; - } else { - break; - } - } - // read lock - lockHolders.add(lockReference.toString()); - - topOfQueue = false; - lockReference.delete(0,lockReference.length()); - } - return lockHolders; - } - - /** - * Determine if the lock is a valid current lock holder. - * - * @param keyspace - * @param table - * @param key - * @param lockRef - * @return true if lockRef is a lock owner of key - * @throws MusicServiceException - * @throws MusicQueryException - */ - public boolean isLockOwner(String keyspace, String table, String key, String lockRef) - throws MusicServiceException, MusicQueryException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Checking in lock table for " + keyspace + "." + table + "." + key); - table = table_prepend_name + table; - String selectQuery = - "select * from " + keyspace + "." + table + " where key=?;"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(selectQuery); - queryObject.addValue(key); - ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); - - boolean topOfQueue = true; - for (Row row : rs) { - String lockReference = "" + row.getLong("lockReference"); - if (row.get("lockType", LockType.class)==LockType.WRITE) { - if (topOfQueue && lockRef.equals(lockReference)) { - return true; - } else { - return false; - } - } - if (lockRef.equals(lockReference)) { - return true; - } - topOfQueue = false; - } - logger.info(EELFLoggerDelegate.applicationLogger, "Could not find " + lockRef - + " in the lock queue. It has expired and no longer exists."); - return false; - } - - /** - * Determine if the lock is a valid current lock holder. - * - * @param keyspace - * @param table - * @param key - * @param lockRef - * @return true if lockRef is a lock owner of key - * @throws MusicServiceException - * @throws MusicQueryException - */ - public LockObject getLockInfo(String keyspace, String table, String key, String lockRef) - throws MusicServiceException, MusicQueryException { - logger.info(EELFLoggerDelegate.applicationLogger, - "Checking in lock table for " + keyspace + "." + table + "." + key); - String lockQ_table = table_prepend_name + table; - String selectQuery = - "select * from " + keyspace + "." + lockQ_table + " where key=? and lockReference=?;"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(selectQuery); - queryObject.addValue(key); - queryObject.addValue(Long.parseLong(lockRef)); - ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); - Row row = rs.one(); - if (row == null || row.isNull("lockReference")) { - return null; - } - - String lockReference = "" + row.getLong("lockReference"); - String createTime = row.getString("createTime"); - String acquireTime = row.getString("acquireTime"); - LockType locktype = row.get("lockType", LockType.class); - boolean isLockOwner = isLockOwner(keyspace, table, key, lockRef); - String owner = row.getString("owner"); - - return new LockObject(isLockOwner, lockReference, createTime, acquireTime, locktype, owner); - } - - - - /** - * This method removes the lock ref from the lock table/queue for the key. - * - * @param keyspace of the application. - * @param table of the application. - * @param key is the primary key of the application table - * @param lockReference the lock reference that needs to be dequeued. - * @throws MusicServiceException - * @throws MusicQueryException - * @throws MusicLockingException - */ - public void deQueueLockRef(String keyspace, String table, String key, String lockReference, int n) - throws MusicServiceException, MusicQueryException, MusicLockingException { - String prependTable = table_prepend_name + table; - PreparedQueryObject queryObject = new PreparedQueryObject(); - Long lockReferenceL = Long.parseLong(lockReference.substring(lockReference.lastIndexOf("$") + 1)); - String deleteQuery = "delete from " + keyspace + "." + prependTable + " where key='" + key - + "' AND lockReference =" + lockReferenceL + " IF EXISTS;"; - queryObject.appendQueryString(deleteQuery); - logger.info(EELFLoggerDelegate.applicationLogger, "Removing lock for key: "+key+ " and reference: "+lockReference); - try { - dsHandle.executePut(queryObject, "critical"); - logger.info(EELFLoggerDelegate.applicationLogger, - "Lock removed for key: " + key + " and reference: " + lockReference); - } catch (MusicServiceException ex) { - logger.error(logger, ex.getMessage(), ex); - logger.error(EELFLoggerDelegate.applicationLogger, - "Exception while deQueueLockRef for lockname: " + key + " reference:" + lockReference); - if (n > 1) { - logger.info(EELFLoggerDelegate.applicationLogger, "Trying again..."); - deQueueLockRef(keyspace, table, key, lockReference, n - 1); - } else { - logger.error(EELFLoggerDelegate.applicationLogger, - "deQueueLockRef failed for lockname: " + key + " reference:" + lockReference); - logger.error(logger, ex.getMessage(), ex); - throw new MusicLockingException("Error while deQueueLockRef: " + ex.getMessage()); - } - } - } - - - public void updateLockAcquireTime(String keyspace, String table, String key, String lockReference) { - table = table_prepend_name + table; - Long lockReferenceL = Long.parseLong(lockReference); - String updateQuery = "update " + keyspace + "." + table + " set acquireTime='" + System.currentTimeMillis() - + "' where key='" + key + "' AND lockReference = " + lockReferenceL + " IF EXISTS;"; - - //cannot use executePut because we need to ignore music timestamp adjustments for lock store - dsHandle.getSession().execute(updateQuery); - } - - public boolean checkForDeadlock(String keyspace, String table, String lockName, LockType locktype, String owner, boolean forAcquire) throws MusicServiceException, MusicQueryException { - if (locktype.equals(LockType.READ)) return false; - if (owner==null || owner.length()==0) return false; - - String lockTable = table_prepend_name + table; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("SELECT key, acquiretime, owner FROM " + keyspace + "." + lockTable); - queryObject.appendQueryString(" WHERE lockType = ? ALLOW FILTERING"); - queryObject.addValue(LockType.WRITE); - - DeadlockDetectionUtil ddu = new DeadlockDetectionUtil(); - - ResultSet rs = dsHandle.executeQuorumConsistencyGet(queryObject); - logger.debug("rs has " + rs.getAvailableWithoutFetching() + (rs.isFullyFetched()?"":" (or more!)") ); - Iterator it = rs.iterator(); - while (it.hasNext()) { - Row row = it.next(); - logger.debug("key = " + row.getString("key") + ", time = " + row.getString("acquiretime") + ", owner = " + row.getString("owner") ); - ddu.setExisting(row.getString("key"), row.getString("owner"), ("0".equals(row.getString("acquiretime")))?OwnershipType.CREATED:OwnershipType.ACQUIRED); - } - boolean deadlock = ddu.checkForDeadlock(lockName, owner, forAcquire?OwnershipType.ACQUIRED:OwnershipType.CREATED); - if (deadlock) logger.warn("Deadlock detected when " + owner + " tried to create lock on " + keyspace + "." + lockTable + "." + lockName); - return deadlock; - } - - public List getAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicServiceException, MusicQueryException { - List toRet = new ArrayList(); - String lockTable = table_prepend_name + table; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("SELECT key, lockreference FROM " + keyspace + "." + lockTable); - queryObject.appendQueryString(" WHERE owner = '" + ownerId + "' ALLOW FILTERING"); - - ResultSet rs = dsHandle.executeQuorumConsistencyGet(queryObject); - Iterator it = rs.iterator(); - while (it.hasNext()) { - Row row = it.next(); - toRet.add(row.getString("key") + "$" + row.getLong("lockreference")); - } - return toRet; - } - - public ReturnType promoteLock(String keyspace, String table, String key, String lockRef) - throws MusicLockingException, MusicServiceException, MusicQueryException { - String lockqtable = table_prepend_name + table; - String selectQuery = "select * from " + keyspace + "." + lockqtable + " where key=?;"; - - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(selectQuery); - queryObject.addValue(key); - ResultSet rs = dsHandle.executeOneConsistencyGet(queryObject); - - long refToPromote = Long.parseLong(lockRef); - - boolean topOfQueue = true; - boolean readBlock = false; - boolean seenLockToPromote = false; - boolean promotionOngoing = false; - long readBlockStart = 0; - long readBlockEnd = 0; - - - for (Row row : rs) { - long ref = row.getLong("lockreference"); - LockType lockType = row.get("lockType", LockType.class); - - if (refToPromote==ref) { - if (promotionOngoing) { - return new ReturnType(ResultType.FAILURE, "Can't promote, already promoting another lockref."); - } - seenLockToPromote = true; - if (!topOfQueue) { - readBlockStart = ref; - readBlockEnd = ref; - break; - } - } else if (!seenLockToPromote && refToPromote nodeList = null; - public enum OwnershipType {NONE, CREATED, ACQUIRED}; - - private class Node implements Comparable { - private String id; - private List links; - private boolean visited = false; - private boolean onStack = false; - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - for (Node link : links) sb.append(link.id); - return "Node [id=" + id + ", links=" + sb.toString() + ", visited=" + visited + ", onStack=" + onStack + "]"; - } - - public Node(String id) { - super(); - this.id = id; - this.links = new ArrayList(); - } - - public List getLinks() { - return links; - } - - public void addLink(Node link) { - this.links.add(link); - } - - public void removeLink(Node link) { - this.links.remove(link); - } - - public boolean isVisited() { - return visited; - } - - public boolean isOnStack() { - return onStack; - } - - public void setVisited(boolean visited) { - this.visited = visited; - } - - public void setOnStack(boolean onStack) { - this.onStack = onStack; - } - - @Override - public int compareTo(Node arg0) { - return id.compareTo(arg0.id); - } - } - - public DeadlockDetectionUtil() { - this.nodeList = new HashMap(); - } - - public void listAllNodes() { - System.out.println("In DeadlockDetectionUtil: "); - for (String key : nodeList.keySet()) { - System.out.println(" " + key + " : " + nodeList.get(key)); - } - } - - public boolean checkForDeadlock(String resource, String owner, OwnershipType operation) { - setExisting(resource, owner, operation); - - Node currentNode = null; - if (operation.equals(OwnershipType.ACQUIRED)) { - currentNode = nodeList.get("r" + resource); - } else if (operation.equals(OwnershipType.CREATED)) { - currentNode = nodeList.get("o" + owner); - } - - boolean cycle = findCycle(currentNode); - return cycle; - } - - private boolean findCycle(Node currentNode) { - if (currentNode==null) return false; - if (currentNode.isOnStack()) return true; - if (currentNode.isVisited()) return false; - currentNode.setOnStack(true); - currentNode.setVisited(true); - for (Node childNode : currentNode.getLinks()) { - if (findCycle(childNode)) return true; - } - currentNode.setOnStack(false); - return false; - } - - public void setExisting(String resource, String owner, OwnershipType operation) { - String resourceKey = "r" + resource; - Node resourceNode = nodeList.get(resourceKey); - if (resourceNode==null) { - resourceNode = new Node(resourceKey); - nodeList.put(resourceKey, resourceNode); - } - - String ownerKey = "o" + owner; - Node ownerNode = nodeList.get(ownerKey); - if (ownerNode==null) { - ownerNode = new Node(ownerKey); - nodeList.put(ownerKey, ownerNode); - } - - if (operation.equals(OwnershipType.ACQUIRED)) { - resourceNode.addLink(ownerNode); - ownerNode.removeLink(resourceNode); - } else if (operation.equals(OwnershipType.CREATED)) { - ownerNode.addLink(resourceNode); - resourceNode.removeLink(ownerNode); - } - } - -} diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/main/MusicCore.java deleted file mode 100644 index 658f2124..00000000 --- a/src/main/java/org/onap/music/main/MusicCore.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.main; - -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; - -import org.onap.music.datastore.Condition; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonIndex; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonSelect; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.lockingservice.cassandra.CassaLockStore; -import org.onap.music.lockingservice.cassandra.LockType; -import org.onap.music.lockingservice.cassandra.MusicLockState; -import org.onap.music.service.MusicCoreService; - -import com.datastax.driver.core.ResultSet; - -public class MusicCore { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class); - private static MusicCoreService musicCore = MusicUtil.getMusicCoreService(); - private static CassaLockStore mLockHandle; - - public static CassaLockStore getmLockHandle() { - return mLockHandle; - } - - public static void setmLockHandle(CassaLockStore mLockHandleIn) { - mLockHandle = mLockHandleIn; - } - - /** - * Acquire lock - * - * @param fullyQualifiedKey DO NOT RELY ON THIS KEY WORKING. INCLUDE THE KEY IN THE LOCKID. - * @param lockId - the full lock id (key + lockRef) - * @return - * @throws MusicLockingException - * @throws MusicQueryException - * @throws MusicServiceException - */ - public static ReturnType acquireLock(String fullyQualifiedKey, String lockId) - throws MusicLockingException, MusicQueryException, MusicServiceException { - return musicCore.acquireLock(fullyQualifiedKey, lockId); - } - - public static ReturnType acquireLockWithLease(String key, String lockId, long leasePeriod) - throws MusicLockingException, MusicQueryException, MusicServiceException { - return musicCore.acquireLockWithLease(key, lockId, leasePeriod); - } - - public static String createLockReference(String fullyQualifiedKey) throws MusicLockingException { - return musicCore.createLockReference(fullyQualifiedKey); - } - - public static String createLockReference(String fullyQualifiedKey, LockType locktype) throws MusicLockingException { - return musicCore.createLockReference(fullyQualifiedKey, locktype); - } - - public static String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException { - return musicCore.createLockReference(fullyQualifiedKey, locktype, owner); - } - - public static ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, - String consistency) throws MusicServiceException { - return musicCore.createTable(keyspace, table, tableQueryObject, consistency); - } - - public static ResultSet quorumGet(PreparedQueryObject query) { - return musicCore.quorumGet(query); - } - - /** - * Gets the top of queue for fullyQualifiedKey - * - * @param fullyQualifiedKey - * @return - */ - public static String whoseTurnIsIt(String fullyQualifiedKey) { - return musicCore.whoseTurnIsIt(fullyQualifiedKey); - } - - /** - * Gets the current lockholder(s) for fullyQualifiedKey - * - * @param fullyQualifiedKey - * @return - */ - public static List getCurrentLockHolders(String fullyQualifiedKey) { - return musicCore.getCurrentLockHolders(fullyQualifiedKey); - } - - public static ReturnType promoteLock(String lockIdToPromote) throws MusicLockingException { - return musicCore.promoteLock(lockIdToPromote); - } - - public static void destroyLockRef(String lockId) throws MusicLockingException { - musicCore.destroyLockRef(lockId); - } - - public static ReturnType eventualPut(PreparedQueryObject queryObject) { - return musicCore.eventualPut(queryObject); - } - - public static ReturnType eventualPut_nb(PreparedQueryObject queryObject, String keyspace, String tablename, - String primaryKey) { - return musicCore.eventualPut_nb(queryObject, keyspace, tablename, primaryKey); - } - - public static ReturnType criticalPut(String keyspace, String table, String primaryKeyValue, - PreparedQueryObject queryObject, String lockReference, Condition conditionInfo) { - return musicCore.criticalPut(keyspace, table, primaryKeyValue, queryObject, lockReference, conditionInfo); - } - - public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) - throws MusicServiceException,MusicQueryException { - return musicCore.nonKeyRelatedPut(queryObject, consistency); - } - - public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { - return musicCore.get(queryObject); - } - - public static ResultSet criticalGet(String keyspace, String table, String primaryKeyValue, - PreparedQueryObject queryObject, String lockReference) throws MusicServiceException { - return musicCore.criticalGet(keyspace, table, primaryKeyValue, queryObject, lockReference); - } - - public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, Condition conditionInfo) - throws MusicLockingException, MusicQueryException, MusicServiceException { - return musicCore.atomicPut(keyspaceName, tableName, primaryKey, queryObject, conditionInfo); - } - - public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException { - return musicCore.atomicGet(keyspaceName, tableName, primaryKey, queryObject); - } - - public static List getLockQueue(String fullyQualifiedKey) - throws MusicServiceException, MusicQueryException, MusicLockingException { - return musicCore.getLockQueue(fullyQualifiedKey); - } - - public static long getLockQueueSize(String fullyQualifiedKey) - throws MusicServiceException, MusicQueryException, MusicLockingException { - return musicCore.getLockQueueSize(fullyQualifiedKey); - } - - public static void deleteLock(String lockName) throws MusicLockingException { - musicCore.deleteLock(lockName); - } - - public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { - return musicCore.atomicPutWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject, conditionInfo); - } - - public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException { - return musicCore.atomicGetWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject); - } - - public static Map validateLock(String lockName) { - return musicCore.validateLock(lockName); - } - - public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException { - return musicCore.releaseLock(lockId, voluntaryRelease); - } - - public static List releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException { - return musicCore.releaseAllLocksForOwner(ownerId, keyspace, table); - } - - //Added changes for orm implementation. - - public static ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo) - throws MusicServiceException, MusicQueryException { - return musicCore.createKeyspace(jsonKeySpaceObject,consistencyInfo); - } - - public static ResultType dropKeyspace(JsonKeySpace josnKeyspaceObject, String consistencyInfo) - throws MusicServiceException,MusicQueryException { - return musicCore.dropKeyspace(josnKeyspaceObject, consistencyInfo); - } - - public static ResultType createTable(JsonTable jsonTableObject,String consistencyInfo) - throws MusicServiceException,MusicQueryException { - return musicCore.createTable(jsonTableObject, consistencyInfo); - } - - public static ResultType dropTable(JsonTable jsonTableObject, String consistencyInfo) - throws MusicServiceException, MusicQueryException { - return musicCore.dropTable(jsonTableObject, consistencyInfo); - } - - public static ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo) - throws MusicServiceException,MusicQueryException { - return musicCore.createIndex(jsonIndexObject, consistencyInfo); - } - - public static ResultSet select(JsonSelect jsonSelect, MultivaluedMap rowParams) - throws MusicServiceException, MusicQueryException{ - return musicCore.select(jsonSelect, rowParams); - } - - public static ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException{ - return musicCore.selectCritical(jsonInsertObj, rowParams); - } - - - public static ReturnType insertIntoTable(JsonInsert jsonInsert) throws MusicLockingException, MusicQueryException, MusicServiceException{ - return musicCore.insertIntoTable(jsonInsert); - } - - public static ReturnType updateTable(JsonUpdate jsonUpdateObj,MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException{ - return musicCore.updateTable(jsonUpdateObj, rowParams); - } - - public static ReturnType deleteFromTable(JsonDelete jsonDeleteObj,MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException{ - return musicCore.deleteFromTable(jsonDeleteObj,rowParams); - } - -} diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java deleted file mode 100755 index d46e770e..00000000 --- a/src/main/java/org/onap/music/main/MusicUtil.java +++ /dev/null @@ -1,820 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 IBM. - * Modifications Copyright (c) 2019 Samsung. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.main; - -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ColumnDefinitions.Definition; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import java.io.File; -import java.io.FileNotFoundException; -import java.math.BigInteger; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Scanner; -import java.util.UUID; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.service.MusicCoreService; -import org.onap.music.service.impl.MusicCassaCore; - -import com.datastax.driver.core.ConsistencyLevel; -import com.datastax.driver.core.DataType; - -/** - * @author nelson24 - * - * Properties This will take Properties and load them into MusicUtil. - * This is a hack for now. Eventually it would bebest to do this in - * another way. - * - */ -public class MusicUtil { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); - - // Consistancy Constants - public static final String ATOMIC = "atomic"; - public static final String EVENTUAL = "eventual"; - public static final String CRITICAL = "critical"; - public static final String EVENTUAL_NB = "eventual_nb"; - public static final String ALL = "all"; - public static final String QUORUM = "quorum"; - public static final String ONE = "one"; - public static final String ATOMICDELETELOCK = "atomic_delete_lock"; - - // Header Constants - private static final String XLATESTVERSION = "X-latestVersion"; - private static final String XMINORVERSION = "X-minorVersion"; - private static final String XPATCHVERSION = "X-patchVersion"; - public static final String AUTHORIZATION = "Authorization"; - - // CQL Constants - public static final String SELECT = "select"; - public static final String INSERT = "insert"; - public static final String UPDATE = "update"; - public static final String UPSERT = "upsert"; - public static final String USERID = "userId"; - public static final String PASSWORD = ""; - public static final String CASSANDRA = "cassandra"; - - private static final String LOCALHOST = "localhost"; - private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties"; - public static final String DEFAULTKEYSPACENAME = "TBD"; - - private static long defaultLockLeasePeriod = 6000; - // Amount of times to retry to delete a lock in atomic. - private static int retryCount = 3; - private static String lockUsing = MusicUtil.CASSANDRA; - // Cadi OnOff - private static boolean isCadi = false; - // Keyspace Creation on/off - private static boolean isKeyspaceActive = false; - private static boolean debug = true; - private static String version = "0.0.0"; - private static String build = ""; - - private static String musicPropertiesFilePath = PROPERTIES_FILE; - // private static final String[] propKeys = new String[] { MusicUtil.class.getDeclaredMethod(arg0, )"build","cassandra.host", "debug", - // "version", "music.properties", "lock.lease.period", "cassandra.user", - // "cassandra.password", "aaf.endpoint.url","admin.username","admin.password", - // "music.namespace","admin.aaf.role","cassandra.port","lock.using","retry.count", - // "transId.header.required","conversation.header.required","clientId.header.required", - // "messageId.header.required","transId.header.prefix","conversation.header.prefix", - // "clientId.header.prefix","messageId.header.prefix"}; - // Consistency Constants and variables. - private static final String[] cosistencyLevel = new String[] { - "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO", - "THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"}; - private static final Map consistencyName = new HashMap<>(); - static { - consistencyName.put("ONE",ConsistencyLevel.ONE); - consistencyName.put("TWO",ConsistencyLevel.TWO); - consistencyName.put("THREE",ConsistencyLevel.THREE); - consistencyName.put("SERIAL",ConsistencyLevel.SERIAL); - consistencyName.put("ALL",ConsistencyLevel.ALL); - consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM); - consistencyName.put("QUORUM",ConsistencyLevel.QUORUM); - consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM); - consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE); - consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL); - } - - // Cassandra Values - private static String cassName = "cassandra"; - private static String cassPwd; - private static String myCassaHost = LOCALHOST; - private static int cassandraPort = 9042; - - // AAF - private static String musicAafNs = "org.onap.music.cadi"; - - // Locking - public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM - public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050) - public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day - - // Response/Request tracking headers - private static String transIdPrefix = "false"; - private static String conversationIdPrefix = "false"; - private static String clientIdPrefix = "false"; - private static String messageIdPrefix = "false"; - private static Boolean transIdRequired = false; - private static Boolean conversationIdRequired = false; - private static Boolean clientIdRequired = false; - private static Boolean messageIdRequired = false; - private static String cipherEncKey = ""; - - public MusicUtil() { - throw new IllegalStateException("Utility Class"); - } - - public static String getLockUsing() { - return lockUsing; - } - - public static void setLockUsing(String lockUsing) { - MusicUtil.lockUsing = lockUsing; - } - - /** - * - * @return cassandra port - */ - public static int getCassandraPort() { - return cassandraPort; - } - - /** - * set cassandra port - * @param cassandraPort - */ - public static void setCassandraPort(int cassandraPort) { - MusicUtil.cassandraPort = cassandraPort; - } - /** - * @return the cassName - */ - public static String getCassName() { - return cassName; - } - - /** - * @return the cassPwd - */ - public static String getCassPwd() { - return cassPwd; - } - - /** - * Returns An array of property names that should be in the Properties - * files. - * -// * @return -// */ -// public static String[] getPropkeys() { -// return propKeys.clone(); -// } - - /** - * Get MusicPropertiesFilePath - Default = /opt/music/music.properties - * property file value - music.properties - * - * @return - */ - public static String getMusicPropertiesFilePath() { - return musicPropertiesFilePath; - } - - /** - * Set MusicPropertiesFilePath - * - * @param musicPropertiesFilePath - */ - public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) { - MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath; - } - - /** - * Get DefaultLockLeasePeriod - Default = 6000 property file value - - * lock.lease.period - * - * @return - */ - public static long getDefaultLockLeasePeriod() { - return defaultLockLeasePeriod; - } - - /** - * Set DefaultLockLeasePeriod - * - * @param defaultLockLeasePeriod - */ - public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) { - MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod; - } - - /** - * Set Debug - * - * @param debug - */ - public static void setDebug(boolean debug) { - MusicUtil.debug = debug; - } - - /** - * Is Debug - Default = true property file value - debug - * - * @return - */ - public static boolean isDebug() { - return debug; - } - - /** - * Set Version - * - * @param version - */ - public static void setVersion(String version) { - MusicUtil.version = version; - } - - /** - * Return the version property file value - version. - * - * @return - */ - public static String getVersion() { - return version; - } - - /** - * Set the build of project which is a combination of the - * version and the date. - * - * @param build - version-date. - */ - public static void setBuild(String build) { - MusicUtil.build = build; - } - - /** - * Return the build version-date. - */ - public static String getBuild() { - return build; - } - - /** - * Get MyCassHost - Cassandra Hostname - Default = localhost property file - * value - cassandra.host - * - * @return - */ - public static String getMyCassaHost() { - return myCassaHost; - } - - /** - * Set MyCassHost - Cassandra Hostname - * - * @param myCassaHost . - */ - public static void setMyCassaHost(String myCassaHost) { - MusicUtil.myCassaHost = myCassaHost; - } - - /** - * Gey default retry count - * @return - */ - public static int getRetryCount() { - return retryCount; - } - - /** - * Set retry count - * @param retryCount . - */ - public static void setRetryCount(int retryCount) { - MusicUtil.retryCount = retryCount; - } - - - /** - * This is used to turn keyspace creation api on/off. - * - */ - public static void setKeyspaceActive(Boolean keyspaceActive) { - MusicUtil.isKeyspaceActive = keyspaceActive; - } - - /** - * This is used to turn keyspace creation api on/off. - * @return boolean isKeyspaceActive - */ - public static boolean isKeyspaceActive() { - return isKeyspaceActive; - } - - /** - * This method depricated as its not used or needed. - * - * @return String - */ - @Deprecated - public static String getTestType() { - String testType = ""; - try { - Scanner fileScanner = new Scanner(new File("")); - testType = fileScanner.next();// ignore the my id line - @SuppressWarnings("unused") - String batchSize = fileScanner.next();// ignore the my public ip line - fileScanner.close(); - } catch (FileNotFoundException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); - } - return testType; - - } - - /** - * Method to do a Thread Sleep. - * Used for adding a delay. - * - * @param time - */ - public static void sleep(long time) { - try { - Thread.sleep(time); - } catch (InterruptedException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); - Thread.currentThread().interrupt(); - } - } - - /** - * Utility function to check if the query object is valid. - * - * @param withparams - * @param queryObject - * @return - */ - public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) { - if (withparams) { - int noOfValues = queryObject.getValues().size(); - int noOfParams = 0; - char[] temp = queryObject.getQuery().toCharArray(); - for (int i = 0; i < temp.length; i++) { - if (temp[i] == '?') - noOfParams++; - } - return (noOfValues == noOfParams); - } else { - return !queryObject.getQuery().isEmpty(); - } - - } - - public static void setCassName(String cassName) { - MusicUtil.cassName = cassName; - } - - public static void setCassPwd(String cassPwd) { - MusicUtil.cassPwd = cassPwd; - } - - @SuppressWarnings("unchecked") - public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception { - - String value = ""; - switch (type.getName()) { - case UUID: - value = valueObj + ""; - break; - case TEXT: - case VARCHAR: - String valueString = valueObj + ""; - valueString = valueString.replace("'", "''"); - value = "'" + valueString + "'"; - break; - case MAP: { - Map otMap = (Map) valueObj; - value = "{" + jsonMaptoSqlString(otMap, ",") + "}"; - break; - } - default: - value = valueObj + ""; - break; - } - return value; - } - - /** - * - * @param colType - * @param valueObj - * @return - * @throws MusicTypeConversionException - * @throws Exception - */ - @SuppressWarnings("unchecked") - public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception { - String valueObjString = valueObj + ""; - switch (colType.getName()) { - case UUID: - return UUID.fromString(valueObjString); - case VARINT: - return BigInteger.valueOf(Long.parseLong(valueObjString)); - case BIGINT: - return Long.parseLong(valueObjString); - case INT: - return Integer.parseInt(valueObjString); - case FLOAT: - return Float.parseFloat(valueObjString); - case DOUBLE: - return Double.parseDouble(valueObjString); - case BOOLEAN: - return Boolean.parseBoolean(valueObjString); - case MAP: - return (Map) valueObj; - case LIST: - return (List)valueObj; - case BLOB: - - default: - return valueObjString; - } - } - - public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) { - ByteBuffer buffer = ByteBuffer.wrap(valueObj); - return buffer; - } - - /** - * - * Utility function to parse json map into sql like string - * - * @param jMap - * @param lineDelimiter - * @return - */ - - public static String jsonMaptoSqlString(Map jMap, String lineDelimiter) throws Exception{ - StringBuilder sqlString = new StringBuilder(); - int counter = 0; - for (Map.Entry entry : jMap.entrySet()) { - Object ot = entry.getValue(); - String value = ot + ""; - if (ot instanceof String) { - value = "'" + value.replace("'", "''") + "'"; - } - sqlString.append("'" + entry.getKey() + "':" + value); - if (counter != jMap.size() - 1) - sqlString.append(lineDelimiter); - counter = counter + 1; - } - return sqlString.toString(); - } - - @SuppressWarnings("unused") - public static String buildVersion(String major, String minor, String patch) { - if (minor != null) { - major += "." + minor; - if (patch != null) { - major += "." + patch; - } - } - return major; - } - - /** - * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion - * X-latestVerstion will be equal to the latest full version. - * X-minorVersion - will be equal to the latest minor version. - * X-pathVersion - will be equal to the latest patch version. - * Future plans will change this. - * @param response - * @param major - * @param minor - * @param patch - * @return - */ - public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) { - ResponseBuilder response = Response.noContent(); - String versionIn = buildVersion(major,minor,patch); - String version = MusicUtil.getVersion(); - String[] verArray = version.split("\\.",3); - if ( minor != null ) { - response.header(XMINORVERSION,minor); - } else { - response.header(XMINORVERSION,verArray[1]); - } - if ( patch != null ) { - response.header(XPATCHVERSION,patch); - } else { - response.header(XPATCHVERSION,verArray[2]); - } - response.header(XLATESTVERSION,version); - logger.info(EELFLoggerDelegate.auditLogger,"Version In:" + versionIn); - return response; - } - - public static boolean isValidConsistency(String consistency) { - for (String string : cosistencyLevel) { - if (string.equalsIgnoreCase(consistency)) - return true; - } - return false; - - } - - public static ConsistencyLevel getConsistencyLevel(String consistency) { - return consistencyName.get(consistency.toUpperCase()); - } - - /** - * Given the time of write for an update in a critical section, this method provides a transformed timestamp - * that ensures that a previous lock holder who is still alive can never corrupt a later critical section. - * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections. - * @param the UUID lock reference associated with the write. - * @param the long timeOfWrite which is the actual time at which the write took place - * @throws MusicServiceException - * @throws MusicQueryException - */ - public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException { - // TODO: use acquire time instead of music eternity epoch - long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis); - - return ts; - } - - public static MusicCoreService getMusicCoreService() { - if(getLockUsing().equals(MusicUtil.CASSANDRA)) - return MusicCassaCore.getInstance(); - else - return MusicCassaCore.getInstance(); - } - - /** - * @param lockName - * @return - */ - public static Map validateLock(String lockName) { - Map resultMap = new HashMap<>(); - String[] locks = lockName.split("\\."); - if(locks.length < 3) { - resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey"); - return resultMap; - } - String keyspace= locks[0]; - if(keyspace.startsWith("$")) - keyspace = keyspace.substring(1); - resultMap.put("keyspace",keyspace); - return resultMap; - } - - - public static void setIsCadi(boolean isCadi) { - MusicUtil.isCadi = isCadi; - } - - public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName, - PreparedQueryObject updateQuery, String keyspace, String table, - Object cqlFormattedPrimaryKeyValue) - throws Exception { - try { - ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery); - // write it back to a quorum - Row row = results.one(); - ColumnDefinitions colInfo = row.getColumnDefinitions(); - int totalColumns = colInfo.size(); - int counter = 1; - StringBuilder fieldValueString = new StringBuilder(""); - for (Definition definition : colInfo) { - String colName = definition.getName(); - if (colName.equals(primaryKeyName)) - continue; - DataType colType = definition.getType(); - Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType); - Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); - fieldValueString.append(colName + " = ?"); - updateQuery.addValue(valueString); - if (counter != (totalColumns - 1)) - fieldValueString.append(","); - counter = counter + 1; - } - updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET " - + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";"); - updateQuery.addValue(cqlFormattedPrimaryKeyValue); - - MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical"); - } catch (MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery , - ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR, e); - } - } - - public static boolean getIsCadi() { - return MusicUtil.isCadi; - } - - - /** - * @return a random uuid - */ - public static String generateUUID() { - String uuid = UUID.randomUUID().toString(); - logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid); - return uuid; - } - - private static String checkPrefix(String prefix){ - if (prefix == null || "".equals(prefix) || prefix.endsWith("-")) { - return prefix; - } else { - return prefix + "-"; - } - } - - /** - * @return the transIdPrefix - */ - public static String getTransIdPrefix() { - return transIdPrefix; - } - - /** - * @param transIdPrefix the transIdPrefix to set - */ - public static void setTransIdPrefix(String transIdPrefix) { - MusicUtil.transIdPrefix = checkPrefix(transIdPrefix); - } - - /** - * @return the conversationIdPrefix - */ - public static String getConversationIdPrefix() { - return conversationIdPrefix; - } - - /** - * @param conversationIdPrefix the conversationIdPrefix to set - */ - public static void setConversationIdPrefix(String conversationIdPrefix) { - MusicUtil.conversationIdPrefix = checkPrefix(conversationIdPrefix); - } - - /** - * @return the clientIdPrefix - */ - public static String getClientIdPrefix() { - return clientIdPrefix; - } - - /** - * @param clientIdPrefix the clientIdPrefix to set - */ - public static void setClientIdPrefix(String clientIdPrefix) { - MusicUtil.clientIdPrefix = checkPrefix(clientIdPrefix); - } - - /** - * @return the messageIdPrefix - */ - public static String getMessageIdPrefix() { - return messageIdPrefix; - } - - /** - * @param messageIdPrefix the messageIdPrefix to set - */ - public static void setMessageIdPrefix(String messageIdPrefix) { - MusicUtil.messageIdPrefix = checkPrefix(messageIdPrefix); - } - - /** - * @return the transIdRequired - */ - public static Boolean getTransIdRequired() { - return transIdRequired; - } - - - /** - * @param transIdRequired the transIdRequired to set - */ - public static void setTransIdRequired(Boolean transIdRequired) { - MusicUtil.transIdRequired = transIdRequired; - } - - - /** - * @return the conversationIdRequired - */ - public static Boolean getConversationIdRequired() { - return conversationIdRequired; - } - - - /** - * @param conversationIdRequired the conversationIdRequired to set - */ - public static void setConversationIdRequired(Boolean conversationIdRequired) { - MusicUtil.conversationIdRequired = conversationIdRequired; - } - - - /** - * @return the clientIdRequired - */ - public static Boolean getClientIdRequired() { - return clientIdRequired; - } - - - /** - * @param clientIdRequired the clientIdRequired to set - */ - public static void setClientIdRequired(Boolean clientIdRequired) { - MusicUtil.clientIdRequired = clientIdRequired; - } - - - /** - * @return the messageIdRequired - */ - public static Boolean getMessageIdRequired() { - return messageIdRequired; - } - - /** - * @param messageIdRequired the messageIdRequired to set - */ - public static void setMessageIdRequired(Boolean messageIdRequired) { - MusicUtil.messageIdRequired = messageIdRequired; - } - - - public static String getCipherEncKey() { - return MusicUtil.cipherEncKey; - } - - - public static void setCipherEncKey(String cipherEncKey) { - MusicUtil.cipherEncKey = cipherEncKey; - if ( null == cipherEncKey || cipherEncKey.equals("") || - cipherEncKey.equals("nothing to see here")) { - logger.error(EELFLoggerDelegate.errorLogger, "Missing Cipher Encryption Key."); - } - } - - public static String getMusicAafNs() { - return MusicUtil.musicAafNs; - } - - - public static void setMusicAafNs(String musicAafNs) { - MusicUtil.musicAafNs = musicAafNs; - } - - - -} - diff --git a/src/main/java/org/onap/music/main/PropertiesLoader.java b/src/main/java/org/onap/music/main/PropertiesLoader.java deleted file mode 100644 index 8aac2672..00000000 --- a/src/main/java/org/onap/music/main/PropertiesLoader.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.main; - -import java.util.Properties; - -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.PropertySource; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.stereotype.Component; - -@PropertySource(value = {"file:/opt/app/music/etc/music.properties", "classpath:/project.properties","file:/opt/app/music/etc/key.properties"}) -@Component -public class PropertiesLoader implements InitializingBean { - - @Value("${cassandra.host}") - public String cassandraHost; -/* - @Value("${music.ip}") - public String musicIp; -*/ - @Value("${debug}") - public String debug; - - @Value("${version}") - public String version; - - @Value("${build}") - public String build; - - @Value("${music.properties}") - public String musicProperties; - - @Value("${lock.lease.period}") - public String lockLeasePeriod; - - @Value("${cassandra.user}") - public String cassandraUser; - - @Value("${cassandra.password}") - public String cassandraPassword; - - @Value("${cassandra.port}") - public String cassandraPort; - - @Value("${cadi}") - public String isCadi; - - @Value("${keyspace.active}") - public String isKeyspaceActive; - - @Value("${retry.count}") - public String rertryCount; - - @Value("${transId.header.prefix}") - private String transIdPrefix; - - @Value("${conversation.header.prefix}") - private String conversationIdPrefix; - - @Value("${clientId.header.prefix}") - private String clientIdPrefix; - - @Value("${messageId.header.prefix}") - private String messageIdPrefix; - - @Value("${transId.header.required}") - private Boolean transIdRequired; - - @Value("${conversation.header.required}") - private Boolean conversationIdRequired; - - @Value("${clientId.header.required}") - private Boolean clientIdRequired; - - @Value("${messageId.header.required}") - private Boolean messageIdRequired; - - @Value("${music.aaf.ns}") - private String musicAafNs; - - @Value("${cipher.enc.key}") - private String cipherEncKey; - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesLoader.class); - - @Bean - public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { - //return new PropertySourcesPlaceholderConfigurer(); - PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); - pspc.setIgnoreResourceNotFound(true); - pspc.setIgnoreUnresolvablePlaceholders(true); - return pspc; - } - - /** - * . - */ - public void loadProperties() { - if(cipherEncKey != null) { - MusicUtil.setCipherEncKey(cipherEncKey); - } - if (musicAafNs != null) { - MusicUtil.setMusicAafNs(musicAafNs); - } - if (cassandraPort != null && !cassandraPort.equals("${cassandra.port}")) { - MusicUtil.setCassandraPort(Integer.parseInt(cassandraPort)); - } - if (cassandraUser != null && !cassandraUser.equals("${cassandra.user}")) { - MusicUtil.setCassName(cassandraUser); - } - if (cassandraPassword != null && !cassandraPassword.equals("${cassandra.password}")) { - MusicUtil.setCassPwd(cassandraPassword); - } - if (debug != null && !debug.equals("${debug}")) { - MusicUtil.setDebug(Boolean.parseBoolean(debug)); - } - if (lockLeasePeriod != null && !lockLeasePeriod.equals("${lock.lease.period}")) { - MusicUtil.setDefaultLockLeasePeriod(Long.parseLong(lockLeasePeriod)); - } - if (musicProperties != null && !musicProperties.equals("${music.properties}")) { - MusicUtil.setMusicPropertiesFilePath(musicProperties); - } - if (cassandraHost != null && !cassandraHost.equals("${cassandra.host}")) { - MusicUtil.setMyCassaHost(cassandraHost); - } - if (version != null && !version.equals("${version}")) { - MusicUtil.setVersion(version); - } - if (build != null && !version.equals("${build}")) { - MusicUtil.setBuild(build); - } - if (isCadi != null && !isCadi.equals("${cadi}")) { - MusicUtil.setIsCadi(Boolean.parseBoolean(isCadi)); - } - if (rertryCount != null && !rertryCount.equals("${retry.count}")) { - MusicUtil.setRetryCount(Integer.parseInt(rertryCount)); - } - if (isKeyspaceActive != null && !isKeyspaceActive.equals("${keyspace.active}")) { - MusicUtil.setKeyspaceActive(Boolean.parseBoolean(isKeyspaceActive)); - } - if(transIdPrefix!=null) { - MusicUtil.setTransIdPrefix(transIdPrefix); - } - - if(conversationIdPrefix!=null) { - MusicUtil.setConversationIdPrefix(conversationIdPrefix); - } - - if(clientIdPrefix!=null) { - MusicUtil.setClientIdPrefix(clientIdPrefix); - } - - if(messageIdPrefix!=null) { - MusicUtil.setMessageIdPrefix(messageIdPrefix); - } - - if(transIdRequired!=null) { - MusicUtil.setTransIdRequired(transIdRequired); - } - - if(conversationIdRequired!=null) { - MusicUtil.setConversationIdRequired(conversationIdRequired); - } - - if(clientIdRequired!=null) { - MusicUtil.setClientIdRequired(clientIdRequired); - } - - if(messageIdRequired!=null) { - MusicUtil.setMessageIdRequired(messageIdRequired); - } - } - - public static void loadProperties(Properties properties) { - if (properties.getProperty("cassandra.host")!=null) { - MusicUtil.setMyCassaHost(properties.getProperty("cassandra.host")); - } - - if (properties.getProperty("cassandra.port")!=null) { - MusicUtil.setCassandraPort(Integer.parseInt(properties.getProperty("cassandra.port"))); - } - - if (properties.getProperty("cassandra.user")!=null) { - MusicUtil.setCassName(properties.getProperty("cassandra.user")); - } - - if (properties.getProperty("cassandra.password")!=null) { - MusicUtil.setCassPwd(properties.getProperty("cassandra.password")); - } - - if (properties.getProperty("music.properties")!=null) { - MusicUtil.setMusicPropertiesFilePath(properties.getProperty("music.properties")); - } - - if (properties.getProperty("debug")!=null) { - MusicUtil.setDebug(Boolean.parseBoolean(properties.getProperty("debug"))); - } - - if (properties.getProperty("version")!=null) { - MusicUtil.setVersion(properties.getProperty("version")); - } - - if (properties.getProperty("build")!=null) { - MusicUtil.setBuild(properties.getProperty("build")); - } - - if (properties.getProperty("lock.lease.period")!=null) { - MusicUtil.setDefaultLockLeasePeriod(Long.parseLong(properties.getProperty("lock.lease.period"))); - } - - if (properties.getProperty("cadi")!=null) { - MusicUtil.setIsCadi(Boolean.parseBoolean(properties.getProperty("cadi"))); - } - - if (properties.getProperty("keyspace.active")!=null) { - MusicUtil.setKeyspaceActive(Boolean.parseBoolean(properties.getProperty("keyspace.active"))); - } - - if (properties.getProperty("retry.count")!=null) { - MusicUtil.setRetryCount(Integer.parseInt(properties.getProperty("retry.count"))); - } - - if (properties.getProperty("transId.header.prefix")!=null) { - MusicUtil.setTransIdPrefix(properties.getProperty("transId.header.prefix")); - } - - if (properties.getProperty("conversation.header.prefix")!=null) { - MusicUtil.setConversationIdPrefix(properties.getProperty("conversation.header.prefix")); - } - - if (properties.getProperty("clientId.header.prefix")!=null) { - MusicUtil.setClientIdPrefix(properties.getProperty("clientId.header.prefix")); - } - - if (properties.getProperty("messageId.header.prefix")!=null) { - MusicUtil.setMessageIdPrefix(properties.getProperty("messageId.header.prefix")); - } - - if (properties.getProperty("transId.header.required")!=null) { - MusicUtil.setTransIdRequired(Boolean.parseBoolean(properties.getProperty("transId.header.required"))); - } - - if (properties.getProperty("conversation.header.required")!=null) { - MusicUtil.setConversationIdRequired(Boolean.parseBoolean(properties.getProperty("conversation.header.required"))); - } - - if (properties.getProperty("clientId.header.required")!=null) { - MusicUtil.setClientIdRequired(Boolean.parseBoolean(properties.getProperty("clientId.header.required"))); - } - - if (properties.getProperty("messageId.header.required")!=null) { - MusicUtil.setMessageIdRequired(Boolean.parseBoolean(properties.getProperty("messageId.header.required"))); - } - - if (properties.getProperty("music.aaf.ns")!=null) { - MusicUtil.setMusicAafNs(properties.getProperty("music.aaf.ns")); - } - - if (properties.getProperty("cipher.enc.key")!=null) { - MusicUtil.setCipherEncKey(properties.getProperty("cipher.enc.key")); - } - - } - - @Override - public void afterPropertiesSet() throws Exception { - // TODO Auto-generated method stub - - } - -} diff --git a/src/main/java/org/onap/music/main/ResultType.java b/src/main/java/org/onap/music/main/ResultType.java deleted file mode 100644 index f5ef2070..00000000 --- a/src/main/java/org/onap/music/main/ResultType.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.main; - -public enum ResultType { - SUCCESS("Success"), FAILURE("Failure"), - SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"), - BODYMISSING("Incomplete Request body. Please correct your input request and retry."); - - private String result; - - ResultType(String result) { - this.result = result; - } - - public String getResult() { - return result; - } - -} - - diff --git a/src/main/java/org/onap/music/main/ReturnType.java b/src/main/java/org/onap/music/main/ReturnType.java deleted file mode 100644 index f02dabbf..00000000 --- a/src/main/java/org/onap/music/main/ReturnType.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.main; - -import java.util.HashMap; -import java.util.Map; - -public class ReturnType { - private ResultType result; - private String message; - - private String timingInfo; - - public ReturnType(ResultType result, String message) { - super(); - this.result = result; - this.message = message; - } - - public String getTimingInfo() { - return timingInfo; - } - - public void setTimingInfo(String timingInfo) { - this.timingInfo = timingInfo; - } - - public ResultType getResult() { - return result; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String toJson() { - return "{ \"result\":\"" + result.getResult() + "\", \"message\":\"" + message + "\"}"; - } - - public String toString() { - return result + " | " + message; - } - - public Map toMap() { - Map newMap = new HashMap<>(); - newMap.put("result", result.getResult()); - newMap.put("message", message); - return newMap; - } - -} diff --git a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java b/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java deleted file mode 100644 index 5ae49f5d..00000000 --- a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.response.jsonobjects; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; -import org.onap.music.main.ResultType; - - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "JsonResponse", description = "General Response JSON") -public class JsonResponse { - - /* Status is required */ - private ResultType status; - - /* Standard informational fields */ - private String error; - private String message; - - /* versioning */ - private String musicVersion; - private String musicBuild; - - /* Data Fields */ - private Map> dataResult; - - /* Locking fields */ - private String lock; - private LockStatus lockStatus; - private List lockHolders; - private String lockLease; - private boolean isLockHolders=false; - - /** - * Create a JSONLock Response - * Use setters to provide more information as in - * JsonLockResponse(ResultType.SUCCESS).setMessage("We did it").setLock(mylockname) - * @param status - */ - public JsonResponse(ResultType status) { - this.status = status; - } - - public boolean isLockHolders() { - return isLockHolders; - } - - public JsonResponse setisLockHolders(boolean isLockHolders) { - this.isLockHolders = isLockHolders; - return this; - } - - /** - * - * @return - */ - @ApiModelProperty(value = "Overall status of the response.", - allowableValues = "Success,Failure") - public ResultType getStatus() { - return status; - } - - /** - * - * @param status - */ - public JsonResponse setStatus(ResultType status) { - this.status = status; - return this; - } - - /** - * - * @return the error - */ - @ApiModelProperty(value = "Error value") - public String getError() { - return error; - } - - /** - * - * @param error - */ - public JsonResponse setError(String error) { - this.error = error; - return this; - } - - /** - * - * @return the message - */ - @ApiModelProperty(value = "Message value") - public String getMessage() { - return message; - } - - /** - * - * @param message - */ - public JsonResponse setMessage(String message) { - this.message = message; - return this; - } - - - /** - * . - * @return the music version - */ - public String getMusicVersion() { - return this.musicVersion; - } - - /** - * . - * @param version of music - * @return - */ - public JsonResponse setMusicVersion(String version) { - this.musicVersion = version; - return this; - } - - /** - * . - * @return the music version - */ - public String getMusicBuild() { - return this.musicBuild; - } - - /** - * . - * @param build of music - * @return - */ - public JsonResponse setMusicBuild(String build) { - this.musicBuild = build; - return this; - } - - - public Map> getDataResult() { - return this.dataResult; - } - - public JsonResponse setDataResult(Map> map) { - this.dataResult = map; - return this; - } - - /** - * - * @return - */ - public String getLock() { - return lock; - } - - /** - * - * @param lock - */ - public JsonResponse setLock(String lock) { - this.lock = lock; - return this; - } - - /** - * - * @return the lockStatus - */ - @ApiModelProperty(value = "Status of the lock") - public LockStatus getLockStatus() { - return lockStatus; - } - - /** - * - * @param lockStatus - */ - public JsonResponse setLockStatus(LockStatus lockStatus) { - this.lockStatus = lockStatus; - return this; - } - - /** - * - * - * @return the lockHolder - */ - @ApiModelProperty(value = "Holder of the Lock") - public List getLockHolder() { - return lockHolders; - } - - /** - * - * @param lockHolder - */ - public JsonResponse setLockHolder(String lockHolder) { - this.lockHolders = new ArrayList(); - this.lockHolders.add(lockHolder); - return this; - } - - public JsonResponse setLockHolder(List lockHolders) { - this.lockHolders = lockHolders; - return this; - } - - - /** - * @return the lockLease - */ - public String getLockLease() { - return lockLease; - } - - /** - * @param lockLease the lockLease to set - */ - public JsonResponse setLockLease(String lockLease) { - this.lockLease = lockLease; - return this; - } - - /** - * Convert to Map - * - * @return - */ - public Map toMap() { - Map fullMap = new HashMap<>(); - fullMap.put("status", status); - if (error != null && !"".equals(error)) { - fullMap.put("error", error); - } - if (message != null) { - fullMap.put("message", message); - } - - if (musicVersion != null) { - fullMap.put("version", musicVersion); - } - - if (musicBuild != null) { - fullMap.put("build", musicBuild); - } - - if (dataResult != null) { - fullMap.put("result", dataResult); - } - - if (lock != null) { - Map lockMap = new HashMap<>(); - if (lock != null) { - lockMap.put("lock", lock); - } - if (lockStatus != null) { - lockMap.put("lock-status", lockStatus); - } - if (lockHolders != null && !lockHolders.isEmpty()) { - if (lockHolders.size()==1 && !isLockHolders) { - //for backwards compatability - lockMap.put("lock-holder", lockHolders.get(0)); - } else { - lockMap.put("lock-holder", lockHolders); - } - } - if (lockLease != null) { - lockMap.put("lock-lease", lockLease); - } - fullMap.put("lock", lockMap); - } - - return fullMap; - } - - /** - * Convert to String - */ - @Override - public String toString() { - return "JsonLockResponse [status=" + status + ", error=" + error + ", message=" + message - + ", lock=" + lock + ", lockStatus=" + lockStatus + ", lockHolder=" - + lockHolders + "]"; - } - -} diff --git a/src/main/java/org/onap/music/rest/Application.java b/src/main/java/org/onap/music/rest/Application.java deleted file mode 100644 index 5375155b..00000000 --- a/src/main/java/org/onap/music/rest/Application.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.rest; - -public class Application { - - private String application_name; - private String username; - private String password; - private String keyspace_name; - private boolean is_aaf; - private String uuid; - private boolean is_api; - - public String getApplication_name() { - return application_name; - } - public void setApplication_name(String application_name) { - this.application_name = application_name; - } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public String getKeyspace_name() { - return keyspace_name; - } - public void setKeyspace_name(String keyspace_name) { - this.keyspace_name = keyspace_name; - } - public boolean isIs_aaf() { - return is_aaf; - } - public void setIs_aaf(boolean is_aaf) { - this.is_aaf = is_aaf; - } - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public boolean getIs_api() { - return is_api; - } - public void setIs_api(boolean is_api) { - this.is_api = is_api; - } - - -} diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java deleted file mode 100755 index 756856d0..00000000 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ /dev/null @@ -1,1052 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Modifications Copyright (C) 2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.rest; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -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 javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.UriInfo; - -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonIndex; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonSelect; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.response.jsonobjects.JsonResponse; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.TableMetadata; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Example; -import io.swagger.annotations.ExampleProperty; - -/* Version 2 Class */ -//@Path("/v{version: [0-9]+}/keyspaces") -@Path("/v2/keyspaces") -@Api(value = "Data Api") -public class RestMusicDataAPI { - /* - * Header values for Versioning X-minorVersion *** - Used to request or communicate a MINOR - * version back from the client to the server, and from the server back to the client - This - * will be the MINOR version requested by the client, or the MINOR version of the last MAJOR - * version (if not specified by the client on the request) - Contains a single position value - * (e.g. if the full version is 1.24.5, X-minorVersion = "24") - Is optional for the client on - * request; however, this header should be provided if the client needs to take advantage of - * MINOR incremented version functionality - Is mandatory for the server on response - * - *** X-patchVersion *** - Used only to communicate a PATCH version in a response for - * troubleshooting purposes only, and will not be provided by the client on request - This will - * be the latest PATCH version of the MINOR requested by the client, or the latest PATCH version - * of the MAJOR (if not specified by the client on the request) - Contains a single position - * value (e.g. if the full version is 1.24.5, X-patchVersion = "5") - Is mandatory for the - * server on response (CURRENTLY NOT USED) - * - *** X-latestVersion *** - Used only to communicate an API's latest version - Is mandatory for the - * server on response, and shall include the entire version of the API (e.g. if the full version - * is 1.24.5, X-latestVersion = "1.24.5") - Used in the response to inform clients that they are - * not using the latest version of the API (CURRENTLY NOT USED) - * - */ - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); - private static final String XMINORVERSION = "X-minorVersion"; - private static final String XPATCHVERSION = "X-patchVersion"; - private static final String NS = "ns"; - private static final String VERSION = "v2"; - private static final String PARAMETER_ERROR = "Missing Row Identifier. Please provide the parameter of key=value for the row being selected."; - - - private class RowIdentifier { - public String primarKeyValue; - public StringBuilder rowIdString; - @SuppressWarnings("unused") - public PreparedQueryObject queryObject; // the string with all the row - // identifiers separated by AND - - public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, - PreparedQueryObject queryObject) { - this.primarKeyValue = primaryKeyValue; - this.rowIdString = rowIdString; - this.queryObject = queryObject; - } - } - - - /** - * Create Keyspace REST - * - * @param kspObject - * @param keyspaceName - * @return - * @throws Exception - */ - @POST - @Path("/{name}") - @ApiOperation(value = "Create Keyspace", response = String.class, - notes = "This API will not work if MUSIC properties has keyspace.active=false ") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"message\" : \"Keysapce Created\"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response createKeySpace( - @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, - JsonKeySpace kspObject, - @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); - logger.info(EELFLoggerDelegate.applicationLogger,"In Create Keyspace " + keyspaceName); - if (MusicUtil.isKeyspaceActive() ) { - logger.info(EELFLoggerDelegate.applicationLogger,"Creating Keyspace " + keyspaceName); - - if(kspObject == null || kspObject.getReplicationInfo() == null) { - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - ResultType result = ResultType.FAILURE; - try { - kspObject.setKeyspaceName(keyspaceName); - result = MusicCore.createKeyspace(kspObject, MusicUtil.EVENTUAL); - logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result); - } catch ( MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.QUERYERROR - ,ErrorSeverity.WARN, ErrorTypes.QUERYERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } catch ( MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build(); - } else { - String vError = "Keyspace Creation has been turned off. Contact DBA to create the keyspace or set keyspace.active to true."; - logger.info(EELFLoggerDelegate.applicationLogger,vError); - logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - - } - - /** - * - * @param kspObject - * @param keyspaceName - * @return - * @throws Exception - */ - @DELETE - @Path("/{name}") - @ApiOperation(value = "Delete Keyspace", response = String.class, - notes = "This API will not work if MUSIC properties has keyspace.active=false ") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"message\" : \"Keysapce Deleted\"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response dropKeySpace( - @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); - logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName); - if (MusicUtil.isKeyspaceActive()) { - String consistency = MusicUtil.EVENTUAL;// for now this needs only - String droperror = "Error Deleteing Keyspace " + keyspaceName; - JsonKeySpace kspObject = new JsonKeySpace(); - kspObject.setKeyspaceName(keyspaceName); - try{ - ResultType result = MusicCore.dropKeyspace(kspObject, consistency); - if ( result.equals(ResultType.FAILURE) ) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError(droperror).toMap()).build(); - } - } catch ( MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.QUERYERROR - ,ErrorSeverity.WARN, ErrorTypes.QUERYERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(droperror + " " + ex.getMessage()).toMap()).build(); - } catch ( MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR - ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(droperror + " " + ex.getMessage()).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build(); - } else { - String vError = "Keyspace deletion has been turned off. Contact DBA to delete the keyspace or set keyspace.active to true."; - logger.info(EELFLoggerDelegate.applicationLogger,vError); - logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param tableObj - * @param version - * @param keyspace - * @param tablename - * @param headers - * @return - * @throws Exception - - */ - @POST - @Path("/{keyspace: .*}/tables/{tablename: .*}") - @ApiOperation(value = "Create Table", response = String.class, - notes = "Create a table with the required json in the body.") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"message\" : \"Tablename Created under keyspace \"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response createTable( - @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonTable tableObj, - @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if ( null == tableObj ) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - if(keyspace == null || keyspace.isEmpty() || tablename == null || tablename.isEmpty()){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("One or more path parameters are not set, please check and try again." - + "Parameter values: keyspace='" + keyspace + "' tablename='" + tablename + "'") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - String consistency = MusicUtil.EVENTUAL; - // for now this needs only eventual consistency - ResultType result = ResultType.FAILURE; - try { - tableObj.setKeyspaceName(keyspace); - tableObj.setTableName(tablename); - result = MusicCore.createTable(tableObj, consistency); - } catch (MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - if ( result.equals(ResultType.FAILURE) ) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename.trim() + " Created under keyspace " + keyspace.trim()).toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param keyspace - * @param tablename - * @param fieldName - * @param info - * @throws Exception - */ - @POST - @Path("/{keyspace: .*}/tables/{tablename: .*}/index/{field: .*}") - @ApiOperation(value = "Create Index", response = String.class, - notes = "An index provides a means to access data using attributes " - + "other than the partition key. The benefit is fast, efficient lookup " - + "of data matching a given condition.") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"message\" : \"Index Created on .
.\"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Unknown Error in create index.\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response createIndex( - @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename, - @ApiParam(value = "Field Name",required = true) @PathParam("field") String fieldName, - @Context UriInfo info) throws Exception { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if ((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty()) || (fieldName == null || fieldName.isEmpty())){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - MultivaluedMap rowParams = info.getQueryParameters(); - String indexName = ""; - if (rowParams.getFirst("index_name") != null) - indexName = rowParams.getFirst("index_name"); - - JsonIndex jsonIndexObject = new JsonIndex(indexName, keyspace, tablename, fieldName); - - ResultType result = ResultType.FAILURE; - try { - result = MusicCore.createIndex(jsonIndexObject, MusicUtil.EVENTUAL); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .CRITICAL, ErrorTypes.GENERALSERVICEERROR, ex); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - if ( result.equals(ResultType.SUCCESS) ) { - return response.status(Status.OK).entity(new JsonResponse(result).setMessage("Index Created on " + keyspace+"."+tablename+"."+fieldName).toMap()).build(); - } else { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param insObj - * @param keyspace - * @param tablename - * @return - * @throws Exception - */ - @POST - @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") - @ApiOperation(value = "Insert Into Table", response = String.class, - notes = "Insert into table with data in json body.") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"message\" : \"Insert Successful\"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure - Generic",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response insertIntoTable( - @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonInsert insObj, - @ApiParam(value = "Keyspace Name", - required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", - required = true) @PathParam("tablename") String tablename) { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if ( null == insObj ) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace","(" + keyspace + ")"); - ReturnType result = null; - String consistency = insObj.getConsistencyInfo().get("type"); - try { - insObj.setKeyspaceName(keyspace); - insObj.setTableName(tablename); - if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - String lockId = insObj.getConsistencyInfo().get("lockId"); - if(lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); - } - } - result = MusicCore.insertIntoTable(insObj); - }catch (MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - }catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - if (result==null) { - logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); - }else if(result.getResult() == ResultType.FAILURE) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result.getResult()).setError(result.getMessage()).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(result.getResult()).setMessage("Insert Successful").toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param insObj - * @param keyspace - * @param tablename - * @param info - * @return - * @throws MusicServiceException - * @throws MusicQueryException - * @throws Exception - */ - @PUT - @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") - @ApiOperation(value = "Update Table", response = String.class, - notes = "Update the table with the data in the JSON body.") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response updateTable( - @ApiParam(value = "Major Version", - required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", - required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version", - required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonUpdate updateObj, - @ApiParam(value = "Keyspace Name", - required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", - required = true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws MusicQueryException, MusicServiceException { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if ( null == updateObj ) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - long startTime = System.currentTimeMillis(); - String operationId = UUID.randomUUID().toString(); // just for infoging - // purposes. - String consistency = updateObj.getConsistencyInfo().get("type"); - ReturnType operationResult = null; - logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency - + " update-" + operationId + "-------------------------"); - - updateObj.setKeyspaceName(keyspace); - updateObj.setTableName(tablename); - - try { - if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - String lockId = updateObj.getConsistencyInfo().get("lockId"); - if(lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); - } - } - operationResult = MusicCore.updateTable(updateObj,info.getQueryParameters()); - }catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, - ErrorTypes.GENERALSERVICEERROR, e); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - }catch (MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - }catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - long actualUpdateCompletionTime = System.currentTimeMillis(); - - long endTime = System.currentTimeMillis(); - long jsonParseCompletionTime = System.currentTimeMillis(); - String timingString = "Time taken in ms for Music " + consistency + " update-" + operationId - + ":" + "|total operation time:" + (endTime - startTime) - + "|json parsing time:" + (jsonParseCompletionTime - startTime) - + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime) - + "|"; - - if (operationResult != null && operationResult.getTimingInfo() != null) { - String lockManagementTime = operationResult.getTimingInfo(); - timingString = timingString + lockManagementTime; - } - logger.info(EELFLoggerDelegate.applicationLogger, timingString); - - if (operationResult==null) { - logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); - } - if ( operationResult.getResult() == ResultType.SUCCESS ) { - return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build(); - } else { - logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(operationResult.getResult()).setError(operationResult.getMessage()).toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param delObj - * @param keyspace - * @param tablename - * @param info - * @return - * @throws MusicServiceException - * @throws MusicQueryException - * @throws Exception - */ - @DELETE - @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") - @ApiOperation(value = "Delete From table", response = String.class, - notes = "Delete from a table, the row or parts of a row. Based on JSON body.") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response deleteFromTable( - @ApiParam(value = "Major Version", - required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", - required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version", - required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonDelete delObj, - @ApiParam(value = "Keyspace Name", - required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", - required = true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws MusicQueryException, MusicServiceException { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - if(delObj == null) { - logger.error(EELFLoggerDelegate.errorLogger,ResultType.BODYMISSING.getResult(), AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - ReturnType operationResult = null; - String consistency = delObj.getConsistencyInfo().get("type"); - delObj.setKeyspaceName(keyspace); - delObj.setTableName(tablename); - try { - if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - String lockId = delObj.getConsistencyInfo().get("lockId"); - if(lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); - } - } - - operationResult = MusicCore.deleteFromTable(delObj,info.getQueryParameters()); - } catch (MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("Unable to perform Delete operation. Exception from music").toMap()).build(); - } - if (operationResult==null) { - logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); - } - if (operationResult.getResult().equals(ResultType.SUCCESS)) { - return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build(); - } else { - logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param tabObj - * @param keyspace - * @param tablename - * @throws Exception - */ - @DELETE - @Path("/{keyspace: .*}/tables/{tablename: .*}") - @ApiOperation(value = "Drop Table", response = String.class) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response dropTable( - @ApiParam(value = "Major Version", - required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", - required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version", - required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Keyspace Name", - required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", - required = true) @PathParam("tablename") String tablename) throws Exception { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - JsonTable jsonTable = new JsonTable(); - jsonTable.setKeyspaceName(keyspace); - jsonTable.setTableName(tablename); - try { - return response.status(Status.OK).entity(new JsonResponse(MusicCore.dropTable(jsonTable, MusicUtil.EVENTUAL)).toMap()).build(); - } catch (MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.WARN - , ErrorTypes.QUERYERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN - , ErrorTypes.GENERALSERVICEERROR,ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param selObj - * @param keyspace - * @param tablename - * @param info - * @return - */ - @PUT - @Path("/{keyspace: .*}/tables/{tablename: .*}/rows/criticalget") - @ApiOperation(value = "** Depreciated ** - Select Critical", response = Map.class, - notes = "This API is depreciated in favor of the regular select api.\n" - + "Avaliable to use with the select api by providing a minorVersion of 1 " - + "and patchVersion of 0.\n" - + "Critical Get requires parameter rowId=value and consistency in order to work.\n" - + "It will fail if either are missing.") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"result\":{\"row 0\":{\"address\":" - + "{\"city\":\"Someplace\",\"street\":\"1 Some way\"}," - + "\"emp_salary\":50,\"emp_name\":\"tom\",\"emp_id\":" - + "\"cfd66ccc-d857-4e90-b1e5-df98a3d40cd6\"}},\"status\":\"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response selectCritical( - @ApiParam(value = "Major Version", - required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",example = "0", - required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",example = "0", - required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonInsert selObj, - @ApiParam(value = "Keyspace Name", - required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", - required = true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws Exception { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspace + " )"); - if (info.getQueryParameters().isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,RestMusicDataAPI.PARAMETER_ERROR, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes - .GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(RestMusicDataAPI.PARAMETER_ERROR).toMap()).build(); - } - if (selObj == null || selObj.getConsistencyInfo().isEmpty()) { - String error = " Missing Body or Consistency type."; - logger.error(EELFLoggerDelegate.errorLogger,ResultType.BODYMISSING.getResult() + error, AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult() + error).toMap()).build(); - } - ResultSet results = null; - String consistency = selObj.getConsistencyInfo().get("type"); - String lockId = selObj.getConsistencyInfo().get("lockId"); - selObj.setKeyspaceName(keyspace); - selObj.setTableName(tablename); - try { - if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - if(lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); - } - } - results = MusicCore.selectCritical(selObj, info.getQueryParameters()); - }catch (MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - - }catch(Exception ex) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - - if(results!=null && results.getAvailableWithoutFetching() >0) { - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * This API will replace the original select and provide a single API fro select and critical. - * The idea is to depreciate the older api of criticalGet and use a single API. - * - * @param selObj - * @param keyspace - * @param tablename - * @param info - * @return - */ - @GET - @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") - @ApiOperation(value = "Select", response = Map.class, - notes = "This has 2 versions: if minorVersion and patchVersion is null or 0, this will be a Eventual Select only.\n" - + "If minorVersion is 1 and patchVersion is 0, this will act like the Critical Select \n" - + "Critical Get requires parameter rowId=value and consistency in order to work.\n" - + "If parameters are missing or consistency information is missing. An eventual select will be preformed.") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"result\":{\"row 0\":{\"address\":" - + "{\"city\":\"Someplace\",\"street\":\"1 Some way\"}," - + "\"emp_salary\":50,\"emp_name\":\"tom\",\"emp_id\":" - + "\"cfd66ccc-d857-4e90-b1e5-df98a3d40cd6\"}},\"status\":\"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response selectWithCritical( - @ApiParam(value = "Major Version",example = "v2", - required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",example = "1", - required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",example = "0", - required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false,hidden = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonInsert selObj, - @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws Exception { - if ((minorVersion != null && patchVersion != null) && - (Integer.parseInt(minorVersion) == 1 && Integer.parseInt(patchVersion) == 0) && - (!(null == selObj) && !selObj.getConsistencyInfo().isEmpty())) { - return selectCritical(version, minorVersion, patchVersion, aid, ns, authorization, selObj, keyspace, tablename, info); - } else { - return select(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename, info); - } - } - - /** - * - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - private Response select( - String version,String minorVersion,String patchVersion, - String aid,String ns,String authorization,String keyspace, - String tablename,UriInfo info) throws Exception { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspace + " ) "); - try { - JsonSelect jsonSelect = new JsonSelect(); - jsonSelect.setKeyspaceName(keyspace); - jsonSelect.setTableName(tablename); - ResultSet results = MusicCore.select(jsonSelect, info.getQueryParameters()); - if(results.getAvailableWithoutFetching() >0) { - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).setError("No data found").toMap()).build(); - } catch (MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex.getMessage() ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, - ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param keyspace - * @param tablename - * @param info - * @param limit - * @return - * @throws MusicServiceException - */ - public PreparedQueryObject selectSpecificQuery(String keyspace, - String tablename, UriInfo info, int limit) - throws MusicServiceException { - PreparedQueryObject queryObject = new PreparedQueryObject(); - StringBuilder rowIdString = getRowIdentifier(keyspace, - tablename,info.getQueryParameters(),queryObject).rowIdString; - queryObject.appendQueryString( - "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowIdString); - if (limit != -1) { - queryObject.appendQueryString(" LIMIT " + limit); - } - queryObject.appendQueryString(";"); - return queryObject; - } - - /** - * - * @param keyspace - * @param tablename - * @param rowParams - * @param queryObject - * @return - * @throws MusicServiceException - */ - private RowIdentifier getRowIdentifier(String keyspace, String tablename, - MultivaluedMap rowParams, PreparedQueryObject queryObject) - throws MusicServiceException { - StringBuilder rowSpec = new StringBuilder(); - int counter = 0; - TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); - if (tableInfo == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - throw new MusicServiceException( - "Table information not found. Please check input for table name= " - + keyspace + "." + tablename); - } - StringBuilder primaryKey = new StringBuilder(); - for (MultivaluedMap.Entry> entry : rowParams.entrySet()) { - String keyName = entry.getKey(); - List valueList = entry.getValue(); - String indValue = valueList.get(0); - DataType colType = null; - Object formattedValue = null; - try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - formattedValue = MusicUtil.convertToActualDataType(colType, indValue); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); - } - if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) { - primaryKey.append(indValue); - } - rowSpec.append(keyName + "= ?"); - queryObject.addValue(formattedValue); - if (counter != rowParams.size() - 1) { - rowSpec.append(" AND "); - } - counter = counter + 1; - } - return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); - } -} diff --git a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java deleted file mode 100644 index eef3aa3a..00000000 --- a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * - * Modifications Copyright (C) 2018 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.rest; - -import java.util.HashMap; -/** - * @author inam - * - */ -import java.util.Map; - -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 javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - - -import org.onap.music.eelf.healthcheck.MusicHealthCheck; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.main.MusicUtil; - -import com.datastax.driver.core.ConsistencyLevel; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - - - - -@Path("/v2/service") -@Api(value="Healthcheck Api") -public class RestMusicHealthCheckAPI { - - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); - private static final String ACTIVE_STATUS = "ACTIVE"; - private static final String INVALID_STATUS = "INVALID"; - private static final String INACTIVE_STATUS = "INACTIVE"; - private static final String INVALID_MESSAGE = "Consistency level is invalid..."; - private static final String INACTIVE_MESSAGE = "One or more nodes in the Cluster is/are down or not responding."; - private static final String ACTIVE_MESSAGE = "Cassandra Running and Listening to requests"; - private static final String STATUS_KEY = "status"; - private static final String MESSAGE_KEY = "message"; - - @GET - @Path("/pingCassandra/{consistency}") - @ApiOperation(value = "Get Health Status", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Response cassandraStatus( - @Context HttpServletResponse response, - @ApiParam(value = "Consistency level",required = true) - @PathParam("consistency") String consistency) { - logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra"); - - Map resultMap = new HashMap<>(); - if(ConsistencyLevel.valueOf(consistency) == null) { - resultMap.put(STATUS_KEY,INVALID_STATUS); - resultMap.put(MESSAGE_KEY, INVALID_MESSAGE); - resultMap.put(INVALID_STATUS, INVALID_STATUS); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - MusicHealthCheck cassHealthCheck = new MusicHealthCheck(); - String status = cassHealthCheck.getCassandraStatus(consistency); - if(status.equals(ACTIVE_STATUS)) { - resultMap.put(STATUS_KEY,ACTIVE_STATUS); - resultMap.put(MESSAGE_KEY, ACTIVE_MESSAGE); - resultMap.put(ACTIVE_STATUS, ACTIVE_MESSAGE); - return Response.status(Status.OK).entity(resultMap).build(); - } else { - resultMap.put(STATUS_KEY,INACTIVE_STATUS); - resultMap.put(MESSAGE_KEY, INACTIVE_MESSAGE); - resultMap.put(INACTIVE_STATUS, INACTIVE_MESSAGE); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - } - - @GET - @Path("/musicHealthCheck") - @ApiOperation(value = "Get Health Status", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Response musicHealthCheck() { - logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for Health Check status for MUSIC"); - Map resultMap = new HashMap<>(); - MusicHealthCheck healthCheck = new MusicHealthCheck(); - - String status = healthCheck.getCassandraStatus(ConsistencyLevel.ANY.toString()); - if(status.equals(ACTIVE_STATUS)) { - resultMap.put("Cassandra", "Active"); - } else { - resultMap.put("Cassandra", "Inactive"); - } - resultMap.put("MUSIC", "Active"); - return Response.status(Status.OK).entity(resultMap).build(); - } - -} diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java deleted file mode 100644 index 321e2561..00000000 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ /dev/null @@ -1,632 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.rest; - -import java.util.List; -import java.util.Map; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -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.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; - -import org.onap.music.datastore.jsonobjects.JsonLeasedLock; -import org.onap.music.datastore.jsonobjects.JsonLock; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.lockingservice.cassandra.LockType; -import org.onap.music.lockingservice.cassandra.MusicLockState; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.response.jsonobjects.JsonResponse; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Example; -import io.swagger.annotations.ExampleProperty; - - -@Path("/v2/locks/") -@Api(value="Locking Api") -public class RestMusicLocksAPI { - - private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicLocksAPI.class); - private static final String XMINORVERSION = "X-minorVersion"; - private static final String XPATCHVERSION = "X-patchVersion"; - private static final String VERSION = "v2"; - - /** - * Puts the requesting process in the q for this lock. The corresponding - * node will be created if it did not already exist - * - * @param lockName - * @return - * @throws Exception - */ - @POST - @Path("/create/{lockname}") - @ApiOperation(value = "Create and Acquire a Lock Id for a single row.", - notes = "Creates and Acquires a Lock Id for a specific Row in a table based on the key of that row.\n" - + " The corresponding lock will be created if it did not already exist." - + " Lock Name also the Lock is in the form of keyspaceName.tableName.rowId.\n" - + " The Response will be in the form of \"$kesypaceName.tableName.rowId$lockRef\" " - + " where the lockRef is a integer representing the Lock Name buffered by \"$\" " - + " followed by the lock number. This term for " - + " this response is a lockId and it will be used in other /locks API calls where a " - + " lockId is required. If just a lock is required then the form that would be " - + " the original lockname(without the buffered \"$\").", - response = Map.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Unable to aquire lock\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response createLockReference( - @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - JsonLock lockObject, - @ApiParam(value = "Lock Owner", required = false) @HeaderParam("owner") String owner, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); - - //default lock type is write, as this is always semantically safe - LockType locktype = LockType.WRITE; - if (lockObject!=null && lockObject.getLocktype()!=null) { - locktype = lockObject.getLocktype(); - } - String lockId; - try { - lockId= MusicCore.createLockReference(lockName, locktype, owner); - } catch (MusicLockingException e) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } - - if (lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.LOCKINGERROR ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Lock Id is null").toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setLock(lockId).toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * Checks if the node is in the top of the queue and hence acquires the lock - * - * @param lockId - * @return - * @throws Exception - */ - @GET - @Path("/acquire/{lockId}") - @ApiOperation(value = "Aquire Lock Id ", - notes = "Checks if the node is in the top of the queue and hence acquires the lock", - response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," - + "\"message\" : \" is the lock holder for the key\"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Unable to aquire lock\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response accquireLock( - @ApiParam(value="Lock Id",required=true) @PathParam("lockId") String lockId, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockId); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); - try { - String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); - ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId); - if ( lockStatus.getResult().equals(ResultType.SUCCESS)) { - response.status(Status.OK); - } else { - response.status(Status.BAD_REQUEST); - } - return response.entity(new JsonResponse(lockStatus.getResult()).setLock(lockId).setMessage(lockStatus.getMessage()).toMap()).build(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, - ErrorTypes.LOCKINGERROR, e); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - - @POST - @Path("/acquire-with-lease/{lockId}") - @ApiOperation( - hidden = false, - value = " ** DEPRECATED ** - Aquire Lock with Lease", - notes = "Acquire the lock with a lease, where lease period is in Milliseconds.\n" - + "This will ensure that a lock will expire in set milliseconds.\n" - + "This is no longer available after v3.2.0", - response = Map.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"," - + "\"lock-lease\" : \"6000\"}," - + "\"message\" : \" is the lock holder for the key\"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Unable to aquire lock\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - @Deprecated - public Response accquireLockWithLease( - JsonLeasedLock lockObj, - @ApiParam(value="Lock Id",required=true) @PathParam("lockId") String lockId, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace",required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockId); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); - String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); - ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()); - if ( lockLeaseStatus.getResult().equals(ResultType.SUCCESS)) { - response.status(Status.OK); - } else { - response.status(Status.BAD_REQUEST); - } - return response.entity(new JsonResponse(lockLeaseStatus.getResult()).setLock(lockName) - .setMessage(lockLeaseStatus.getMessage()) - .setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - - - } - - - @GET - @Path("/enquire/{lockname}") - @ApiOperation(value = "Get the top of the lock queue", - notes = "Gets the current single lockholder at top of lock queue", - response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"lock\" : {\"lock\" : \"keyspace.table.rowId\"," - + "\"lock-holder\" : \"$tomtest.employees.tom$\"}}," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Error Message\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response enquireLock( - @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); - String who = MusicCore.whoseTurnIsIt(lockName); - ResultType status = ResultType.SUCCESS; - String error = ""; - if ( who == null ) { - status = ResultType.FAILURE; - error = "There was a problem getting the lock holder"; - logger.error(EELFLoggerDelegate.errorLogger,"There was a problem getting the lock holder", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - @GET - @Path("/holders/{lockname}") - @ApiOperation(value = "Get Lock Holders", - notes = "Gets the current Lock Holders.\n" - + "Will return an array of READ Lock References.", - response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"lock\" : {\"lock\" : \"keyspace.table.rowId\"," - + "\"lock-holder\" : [\"$keyspace.table.rowId$\",\"$keyspace.table.rowId$\"]}}," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Error message\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response currentLockHolder(@ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam("ns") String ns) { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, - ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity( - new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()) - .build(); - } - String keyspaceName = (String) resultMap.get("keyspace"); - List who = MusicCore.getCurrentLockHolders(lockName); - ResultType status = ResultType.SUCCESS; - String error = ""; - if (who == null || who.isEmpty()) { - status = ResultType.FAILURE; - error = (who !=null && who.isEmpty()) ? "No lock holders for the key":"There was a problem getting the lock holder"; - logger.error(EELFLoggerDelegate.errorLogger, "There was a problem getting the lock holder", - AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()) - .build(); - } - return response.status(Status.OK) - .entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).setisLockHolders(true).toMap()) - .build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - - @GET - @Path("/{lockname}") - @ApiOperation(value = "Lock State", - notes = "Returns current Lock State and Holder.", - response = Map.class,hidden = true) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," - + "\"message\" : \" is the lock holder for the key\"," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Unable to aquire lock\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response currentLockState( - @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam("ns") String ns) { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); - String who = MusicCore.whoseTurnIsIt(lockName); - ResultType status = ResultType.SUCCESS; - String error = ""; - if ( who == null ) { - status = ResultType.FAILURE; - error = "There was a problem getting the lock holder"; - logger.error(EELFLoggerDelegate.errorLogger,"There was a problem getting the lock holder", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - - } - - /** - * - * deletes the process from the lock queue - * - * @param lockId - * @throws Exception - */ - @DELETE - @Path("/release/{lockreference}") - @ApiOperation(value = "Release Lock", - notes = "Releases the lock from the lock queue.", - response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success - UNLOCKED = Lock Removed.",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"lock\" : {\"lock\" : \"$keyspace.table.rowId$\"}," - + "\"lock-status\" : \"UNLOCKED\"}," - + "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Unable to aquire lock\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response unLock(@PathParam("lockreference") String lockId, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockId); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); - boolean voluntaryRelease = true; - MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease); - if(mls.getErrorMessage() != null) { - resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage()); - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - Map returnMap = null; - if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) { - returnMap = new JsonResponse(ResultType.SUCCESS).setLock(lockId) - .setLockStatus(mls.getLockStatus()).toMap(); - response.status(Status.OK); - } - if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.LOCKINGERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - returnMap = new JsonResponse(ResultType.FAILURE).setLock(lockId) - .setLockStatus(mls.getLockStatus()).toMap(); - response.status(Status.BAD_REQUEST); - } - return response.entity(returnMap).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - /** - * - * @param lockName - * @throws Exception - */ - @Deprecated - @DELETE - @Path("/delete/{lockname}") - @ApiOperation( - hidden = true, - value = "-DEPRECATED- Delete Lock", response = Map.class, - notes = "-DEPRECATED- Delete the lock.") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Error Message if any\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response deleteLock(@PathParam("lockname") String lockName, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false, hidden = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Application namespace", - required = false, hidden = true) @HeaderParam("ns") String ns) throws Exception{ - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); - try{ - MusicCore.destroyLockRef(lockName); - }catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).toMap()).build(); - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } - - - /** - * Puts the requesting process in the q for this lock. The corresponding - * node will be created if it did not already exist - * - * @param lockName - * @return - * @throws Exception - */ - @POST - @Path("/promote/{lockname}") - @ApiOperation(value = "Attempt to promote the lock for a single row.", - response = Map.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value={ - @ApiResponse(code=200, message = "Success",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "\"status\" : \"SUCCESS\"}") - })), - @ApiResponse(code=400, message = "Failure",examples = @Example( value = { - @ExampleProperty(mediaType="application/json",value = - "{\"error\" : \"Unable to promote lock\"," - + "\"status\" : \"FAILURE\"}") - })) - }) - public Response promoteLock( - @ApiParam(value="Lock Id",required=true) @PathParam("lockId") String lockId, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) - throws Exception { - try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map resultMap = MusicCore.validateLock(lockId); - if (resultMap.containsKey("Error")) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); - } - - String keyspaceName = (String) resultMap.get("keyspace"); - EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); - - try { - ReturnType lockStatus = MusicCore.promoteLock(lockId); - if ( lockStatus.getResult().equals(ResultType.SUCCESS)) { - response.status(Status.OK); - } else { - response.status(Status.BAD_REQUEST); - } - return response.entity(new JsonResponse(lockStatus.getResult()).setLock(lockId).setMessage(lockStatus.getMessage()).toMap()).build(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, - ErrorTypes.LOCKINGERROR, e); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Unable to promote lock").toMap()).build(); - } - } finally { - EELFLoggerDelegate.mdcRemove("keyspace"); - } - } -} diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java deleted file mode 100755 index 4def0e45..00000000 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ /dev/null @@ -1,441 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (C) 2019 IBM. - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.rest; - -import java.util.Map; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -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 javax.ws.rs.core.UriInfo; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.eelf.logging.EELFLoggerDelegate; - -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.apache.commons.lang3.StringUtils; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import com.datastax.driver.core.ResultSet; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.response.jsonobjects.JsonResponse; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - -@Path("/v2/priorityq/") -@Api(value = "Q Api",hidden = true) -public class RestMusicQAPI { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class); - - - /** - * - * @param tableObj - * @param keyspace - * @param tablename - * @throws Exception - */ - - @POST - @Path("/keyspaces/{keyspace}/{qname}") // qname same as tablename - @ApiOperation(value = "Create Q", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response createQ( - @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, - @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonTable tableObj, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - - Map fields = tableObj.getFields(); - if (fields == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ/Required table fields are empty or not set").toMap()) - .build(); - } - - String primaryKey = tableObj.getPrimaryKey(); - String partitionKey = tableObj.getPartitionKey(); - String clusteringKey = tableObj.getClusteringKey(); - String filteringKey = tableObj.getFilteringKey(); - String clusteringOrder = tableObj.getClusteringOrder(); - - if(primaryKey == null) { - primaryKey = tableObj.getFields().get("PRIMARY KEY"); - } - - if ((primaryKey == null) && (partitionKey == null)) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Partition key cannot be empty").toMap()) - .build(); - } - - if ((primaryKey == null) && (clusteringKey == null)) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Clustering key cannot be empty").toMap()) - .build(); - } - - if (clusteringOrder == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Clustering Order cannot be empty").toMap()) - .build(); - } - - if ((primaryKey!=null) && (partitionKey == null)) { - primaryKey = primaryKey.trim(); - int count1 = StringUtils.countMatches(primaryKey,')'); - int count2 = StringUtils.countMatches(primaryKey,'('); - if (count1 != count2) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ Error: primary key '(' and ')' do not match, primary key=" + primaryKey) - .toMap()).build(); - } - - if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) ) { - if (primaryKey.contains(",") ) { - partitionKey= primaryKey.substring(0,primaryKey.indexOf(',')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - clusteringKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index - clusteringKey=clusteringKey.replaceAll("[)]+", ""); - } else { - partitionKey=primaryKey; - partitionKey=partitionKey.replaceAll("[\\)]+",""); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - clusteringKey=""; - } - } else { - partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - partitionKey = partitionKey.trim(); - clusteringKey= primaryKey.substring(primaryKey.indexOf(')')); - clusteringKey=clusteringKey.replaceAll("[\\(]+",""); - clusteringKey=clusteringKey.replaceAll("[\\)]+",""); - clusteringKey = clusteringKey.trim(); - if (clusteringKey.indexOf(',') == 0) clusteringKey=clusteringKey.substring(1); - clusteringKey = clusteringKey.trim(); - if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),) - } - } - - if (partitionKey.trim().isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Partition key cannot be empty").toMap()) - .build(); - } - - if (clusteringKey.trim().isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Clustering key cannot be empty").toMap()) - .build(); - } - - if((filteringKey != null) && (filteringKey.equalsIgnoreCase(partitionKey))) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Filtering key cannot be same as Partition Key").toMap()) - .build(); - } - - return new RestMusicDataAPI().createTable(version, minorVersion, patchVersion, aid, ns, authorization, tableObj, keyspace, tablename); - } - - /** - * - * @param insObj - * @param keyspace - * @param tablename - * @throws Exception - */ - @POST - @Path("/keyspaces/{keyspace}/{qname}/rows") - @ApiOperation(value = "", response = Void.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - // public Map insertIntoQ( - public Response insertIntoQ( - @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, - @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonInsert insObj, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) { - - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - if (insObj.getValues().isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("Required HTTP Request body is missing.").toMap()).build(); - } - return new RestMusicDataAPI().insertIntoTable(version, minorVersion, patchVersion, aid, ns, - authorization, insObj, keyspace, tablename); - } - - /** - * - * @param updateObj - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - @PUT - @Path("/keyspaces/{keyspace}/{qname}/rows") - @ApiOperation(value = "updateQ", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response updateQ( - @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, - @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonUpdate updateObj, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) throws MusicServiceException, MusicQueryException { - - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - if (updateObj.getValues().isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("Required HTTP Request body is missing. JsonUpdate updateObj.getValues() is empty. ") - .toMap()) - .build(); - } - return new RestMusicDataAPI().updateTable(version, minorVersion, patchVersion, aid, ns, - authorization,updateObj, keyspace, tablename, info); - } - - /** - * - * @param delObj - * @param keyspace - * @param tablename - * @param info - * - * @return - * @throws Exception - */ - - @DELETE - @Path("/keyspaces/{keyspace}/{qname}/rows") - @ApiOperation(value = "deleteQ", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response deleteFromQ( - @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, - @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonDelete delObj, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) throws MusicServiceException, MusicQueryException { - // added checking as per RestMusicDataAPI - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - if (delObj == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("deleteFromQ JsonDelete delObjis empty").toMap()).build(); - } - - return new RestMusicDataAPI().deleteFromTable(version, minorVersion, patchVersion, aid, ns, - authorization, delObj, keyspace, tablename, info); - } - - /** - * - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - @GET - @Path("/keyspaces/{keyspace}/{qname}/peek") - @ApiOperation(value = "", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - //public Map> peek( - public Response peek( - @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, - @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) { - int limit =1; //peek must return just the top row - // Map auth = new HashMap<>(); - // String userId =auth.get(MusicUtil.USERID); - // String password =auth.get(MusicUtil.PASSWORD); - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - - PreparedQueryObject queryObject = new PreparedQueryObject(); - if (info.getQueryParameters() == null ) { //|| info.getQueryParameters().isEmpty()) - queryObject.appendQueryString( - "SELECT * FROM " + keyspace + "." + tablename + " LIMIT " + limit + ";"); - } else { - try { - queryObject = new RestMusicDataAPI().selectSpecificQuery(keyspace, tablename, info, limit); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, - ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()) - .build(); - } - } - - try { - ResultSet results = MusicCore.get(queryObject); - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS) - .setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, - ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()) - .build(); - } - } - - /** - * - * - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - @GET - @Path("/keyspaces/{keyspace}/{qname}/filter") - @ApiOperation(value = "filter", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - // public Map> filter( - public Response filter( - @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, - @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) throws Exception { - - return new RestMusicDataAPI().selectWithCritical(version, minorVersion, patchVersion, aid, ns, authorization,null, keyspace, tablename, info);// , limit) - - } - - /** - * - * @param tabObj - * @param keyspace - * @param tablename - * @throws Exception - */ - @DELETE - @ApiOperation(value = "DropQ", response = String.class) - @Path("/keyspaces/{keyspace}/{qname}") - @Produces(MediaType.APPLICATION_JSON) - public Response dropQ( - @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", - required = false) @HeaderParam("X-minorVersion") String minorVersion, - @ApiParam(value = "Patch Version", - required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { - - return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename); - - } -} diff --git a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java b/src/main/java/org/onap/music/rest/RestMusicTestAPI.java deleted file mode 100644 index c1c04b09..00000000 --- a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.rest; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.main.MusicUtil; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - - -@Path("/v{version: [0-9]+}/test") -@Api(value="Test Api") -public class RestMusicTestAPI { - - @SuppressWarnings("unused") - private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicTestAPI.class); - - /** - * Returns a test JSON. This will confirm that REST is working. - * @return - */ - @GET - @Path("/") - @ApiOperation(value = "Get Test", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Map> simpleTests( - @Context HttpServletResponse response) { - response.addHeader("X-latestVersion",MusicUtil.getVersion()); - Map> testMap = new HashMap<>(); - for(int i=0; i < 3; i++){ - HashMap innerMap = new HashMap<>(); - innerMap.put("Music Version",MusicUtil.getVersion()); - innerMap.put("Music Build",MusicUtil.getBuild()); - innerMap.put(i+1+"", i+2+""); - testMap.put(i+"", innerMap); - } - return testMap; - } -} diff --git a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java deleted file mode 100644 index 8c86152e..00000000 --- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.rest; - -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -import org.onap.music.response.jsonobjects.JsonResponse; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - - -@Path("/v{version: [0-9]+}/version") -@Api(value="Version Api") -public class RestMusicVersionAPI { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class); - private static final String MUSIC_KEY = "MUSIC:"; - /** - * Get the version of MUSIC. - * @return - */ - @GET - @ApiOperation(value = "Get Version", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Map version(@Context HttpServletResponse response) { - logger.info("Replying to request for MUSIC version with MUSIC:" + MusicUtil.getVersion()); - response.addHeader("X-latestVersion",MusicUtil.getVersion()); - return new JsonResponse(ResultType.SUCCESS). - setMusicVersion(MUSIC_KEY + MusicUtil.getVersion()).toMap(); - } - - /** - * Get the version of MUSIC. - * @return - */ - @GET - @Path("/build") - @ApiOperation(value = "Get Version", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Map build(@Context HttpServletResponse response) { - logger.info("Replying to request for MUSIC build with MUSIC:" + MusicUtil.getBuild()); - response.addHeader("X-latestVersion",MusicUtil.getVersion()); - return new JsonResponse(ResultType.SUCCESS) - .setMusicBuild(MUSIC_KEY + MusicUtil.getBuild()) - .setMusicVersion(MUSIC_KEY + MusicUtil.getVersion()).toMap(); - } - - -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/service/MusicCoreService.java b/src/main/java/org/onap/music/service/MusicCoreService.java deleted file mode 100644 index b3226906..00000000 --- a/src/main/java/org/onap/music/service/MusicCoreService.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.service; - -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; - -import org.onap.music.datastore.Condition; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonIndex; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonSelect; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.lockingservice.cassandra.LockType; -import org.onap.music.lockingservice.cassandra.MusicLockState; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; - -import com.datastax.driver.core.ResultSet; - -public interface MusicCoreService { - - - // Core Music Database Methods - - - public ReturnType eventualPut(PreparedQueryObject queryObject); - - public ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey); - - public ReturnType criticalPut(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, String lockId, Condition conditionInfo); - - public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) - throws MusicServiceException,MusicQueryException; - - public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException; - - public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException; - - public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException; - - public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException; - - public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, Condition conditionInfo) - throws MusicLockingException, MusicQueryException, MusicServiceException; - - public ResultSet criticalGet(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, String lockId) throws MusicServiceException; - - // Core Music Locking Service Methods - - /** - * Create a lock ref in the music lock store. - * Default is write as this is the safest semantically - * - * @param fullyQualifiedKey the key to create a lock on - * @see {@link #creatLockReference(String, LockType)} - */ - public String createLockReference(String fullyQualifiedKey) throws MusicLockingException; // lock name - - /** - * Create a lock ref in the music lock store - * @param fullyQualifiedKey the key to create a lock on - * @param locktype the type of lock create, see {@link LockType} - */ - public String createLockReference(String fullyQualifiedKey, LockType locktype) throws MusicLockingException; - - /** - * Create a lock ref in the music lock store - * @param fullyQualifiedKey the key to create a lock on - * @param locktype the type of lock create, see {@link LockType} - * @param owner the owner of the lock, for deadlock prevention - */ - public String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException; - - public ReturnType acquireLockWithLease(String key, String lockReference, long leasePeriod) - throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id,time - - public ReturnType acquireLock(String key, String lockReference) - throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id - - public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, - String consistency) throws MusicServiceException; - - public ResultSet quorumGet(PreparedQueryObject query); - - /** - * Gets top of queue for fullyQualifiedKey - * @param fullyQualifiedKey - * @return - */ - public String whoseTurnIsIt(String fullyQualifiedKey);// lock name - - /** - * Gets the current lockholder(s) for lockName - * @param lockName - * @return - */ - public List getCurrentLockHolders(String fullyQualifiedKey); - - public void destroyLockRef(String lockId) throws MusicLockingException; - - public void deleteLock(String lockName) throws MusicLockingException; - - public ReturnType promoteLock(String lockIdToPromote) throws MusicLockingException; - - public List getLockQueue(String fullyQualifiedKey) - throws MusicServiceException, MusicQueryException, MusicLockingException; - - public long getLockQueueSize(String fullyQualifiedKey) - throws MusicServiceException, MusicQueryException, MusicLockingException; - - public Map validateLock(String lockName); - - public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException; - - public List releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException; - - - //Methods added for orm - - - public ResultType createTable(JsonTable jsonTableObject, String consistencyInfo) throws MusicServiceException,MusicQueryException; - - public ResultType dropTable(JsonTable jsonTableObject, String consistencyInfo) - throws MusicServiceException,MusicQueryException; - - public ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject,String consistencyInfo) throws MusicServiceException,MusicQueryException; - - public ResultType dropKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo) - throws MusicServiceException,MusicQueryException; - - public ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo) throws MusicServiceException,MusicQueryException; - - public ResultSet select(JsonSelect jsonSelect, MultivaluedMap rowParams) throws MusicServiceException, MusicQueryException; - - public ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException; - - public ReturnType insertIntoTable(JsonInsert jsonInsert) throws MusicLockingException, MusicQueryException, MusicServiceException; - - public ReturnType updateTable(JsonUpdate jsonUpdateObj,MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException; - - public ReturnType deleteFromTable(JsonDelete jsonDeleteObj,MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException; - -} diff --git a/src/main/java/org/onap/music/service/impl/MusicCassaCore.java b/src/main/java/org/onap/music/service/impl/MusicCassaCore.java deleted file mode 100644 index 0d2e3f0a..00000000 --- a/src/main/java/org/onap/music/service/impl/MusicCassaCore.java +++ /dev/null @@ -1,1149 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Modifications Copyright (c) 2018 IBM. - * =================================================================== - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.service.impl; - -import java.io.StringWriter; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.ws.rs.core.MultivaluedMap; - -import org.onap.music.datastore.Condition; -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonIndex; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonSelect; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicDeadlockException; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.lockingservice.cassandra.CassaLockStore; -import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject; -import org.onap.music.lockingservice.cassandra.LockType; -import org.onap.music.lockingservice.cassandra.MusicLockState; -import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.service.MusicCoreService; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.TableMetadata; - -public class MusicCassaCore implements MusicCoreService { - - private static CassaLockStore mLockHandle = null; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCassaCore.class); - private static MusicCassaCore musicCassaCoreInstance = null; - - private MusicCassaCore() { - // not going to happen - } - - public static CassaLockStore getmLockHandle() { - return mLockHandle; - } - - public static void setmLockHandle(CassaLockStore mLockHandle) { - MusicCassaCore.mLockHandle = mLockHandle; - } - - public static MusicCassaCore getInstance() { - - if(musicCassaCoreInstance == null) { - musicCassaCoreInstance = new MusicCassaCore(); - } - return musicCassaCoreInstance; - } - - - - - public static CassaLockStore getLockingServiceHandle() throws MusicLockingException { - logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle"); - long start = System.currentTimeMillis(); - - if (mLockHandle == null) { - try { - mLockHandle = new CassaLockStore(MusicDataStoreHandle.getDSHandle()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - throw new MusicLockingException("Failed to aquire Locl store handle " + e); - } - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms"); - return mLockHandle; - } - - public String createLockReference(String fullyQualifiedKey) throws MusicLockingException { - return createLockReference(fullyQualifiedKey, LockType.WRITE); - } - - public String createLockReference(String fullyQualifiedKey, LockType locktype) throws MusicLockingException { - return createLockReference(fullyQualifiedKey, locktype, null); - } - - public String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException { - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String lockName = splitString[2]; - - logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName); - long start = System.currentTimeMillis(); - String lockReference = null; - - try { - boolean deadlock = getLockingServiceHandle().checkForDeadlock(keyspace, table, lockName, locktype, owner, false); - if (deadlock) { - MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + owner + " tried to create lock on " + keyspace + "." + table + "." + lockName); - e.setValues(owner, keyspace, table, lockName); - throw e; - } - } catch (MusicDeadlockException e) { - //just threw this, no need to wrap it - throw e; - } catch (MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.applicationLogger, e); - throw new MusicLockingException("Unable to check for deadlock. " + e.getMessage(), e); - } - - try { - lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName, locktype, owner); - } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.applicationLogger, e); - throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.applicationLogger, e); - throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms"); - return lockReference; - } - - public ReturnType promoteLock(String lockId) throws MusicLockingException { - String[] splitString = lockId.split("\\."); - String keyspace = splitString[0].substring(1);//remove '$' - String table = splitString[1]; - String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$")); - String localFullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); - String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end - - logger.info(EELFLoggerDelegate.applicationLogger,"Attempting to promote lock " + lockId); - - try { - return getLockingServiceHandle().promoteLock(keyspace, table, primaryKeyValue, lockRef); - } catch (MusicServiceException e) { - throw new MusicLockingException("Unable to promote lock. ", e); - } catch (MusicQueryException e) { - throw new MusicLockingException("Unable to promote lock. ", e); - } - - } - - - public ReturnType acquireLockWithLease(String fullyQualifiedKey, String lockReference, long leasePeriod) - throws MusicLockingException, MusicQueryException, MusicServiceException { - evictExpiredLockHolder(fullyQualifiedKey,leasePeriod); - return acquireLock(fullyQualifiedKey, lockReference); - } - - private void evictExpiredLockHolder(String fullyQualifiedKey, long leasePeriod) - throws MusicLockingException, MusicQueryException, MusicServiceException { - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String primaryKeyValue = splitString[2]; - - LockObject currentLockHolderObject = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue); - - if (!currentLockHolderObject.getIsLockOwner()) { // no lock holder - return; - } - /* - * Release the lock of the previous holder if it has expired. if the update to the acquire time has - * not reached due to network delays, simply use the create time as the reference - */ - long referenceTime = Math.max(Long.parseLong(currentLockHolderObject.getAcquireTime()), - Long.parseLong(currentLockHolderObject.getCreateTime())); - if ((System.currentTimeMillis() - referenceTime) > leasePeriod) { - forciblyReleaseLock(fullyQualifiedKey, currentLockHolderObject.getLockRef() + ""); - logger.info(EELFLoggerDelegate.applicationLogger, currentLockHolderObject.getLockRef() + " forcibly released"); - } - } - - public ReturnType acquireLock(String fullyQualifiedKey, String lockId) - throws MusicLockingException, MusicQueryException, MusicServiceException { - String[] splitString = lockId.split("\\."); - String keyspace = splitString[0].substring(1);//remove '$' - String table = splitString[1]; - String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$")); - String localFullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); - String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end - - LockObject lockInfo = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, lockRef); - - if (!lockInfo.getIsLockOwner()) { - return new ReturnType(ResultType.FAILURE, lockId + " is not a lock holder");//not top of the lock store q - } - - if (getLockingServiceHandle().checkForDeadlock(keyspace, table, primaryKeyValue, lockInfo.getLocktype(), lockInfo.getOwner(), true)) { - MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + lockInfo.getOwner() + " tried to create lock on " + keyspace + "." + table + "." + primaryKeyValue); - e.setValues(lockInfo.getOwner(), keyspace, table, primaryKeyValue); - throw e; - } - - //check to see if the value of the key has to be synced in case there was a forceful release - String syncTable = keyspace+".unsyncedKeys_"+table; - String query = "select * from "+syncTable+" where key='"+localFullyQualifiedKey+"';"; - PreparedQueryObject readQueryObject = new PreparedQueryObject(); - readQueryObject.appendQueryString(query); - ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(readQueryObject); - if (!results.all().isEmpty()) { - logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!"); - try { - syncQuorum(keyspace, table, primaryKeyValue); - } catch (Exception e) { - StringWriter sw = new StringWriter(); - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ", - ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e); - String exceptionAsString = sw.toString(); - return new ReturnType(ResultType.FAILURE, "Exception thrown while syncing key:\n" + exceptionAsString); - } - String cleanQuery = "delete from " + syncTable + " where key='"+localFullyQualifiedKey+"';"; - PreparedQueryObject deleteQueryObject = new PreparedQueryObject(); - deleteQueryObject.appendQueryString(cleanQuery); - MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "critical"); - } - - getLockingServiceHandle().updateLockAcquireTime(keyspace, table, primaryKeyValue, lockRef); - - return new ReturnType(ResultType.SUCCESS, lockRef+" is the lock holder for the key"); - } - - - - /** - * - * @param tableQueryObject - * @param consistency - * @return Boolean Indicates success or failure - * @throws MusicServiceException - * - * - */ - public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, - String consistency) throws MusicServiceException { - boolean result = false; - - try { - // create shadow locking table - result = getLockingServiceHandle().createLockQueue(keyspace, table); - if (result == false) - return ResultType.FAILURE; - - result = false; - - // create table to track unsynced_keys - table = "unsyncedKeys_" + table; - - String tabQuery = - "CREATE TABLE IF NOT EXISTS " + keyspace + "." + table + " ( key text,PRIMARY KEY (key) );"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - - queryObject.appendQueryString(tabQuery); - result = false; - result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual"); - - // create actual table - result = MusicDataStoreHandle.getDSHandle().executePut(tableQueryObject, consistency); - } catch (MusicQueryException | MusicServiceException | MusicLockingException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, - ErrorTypes.MUSICSERVICEERROR); - throw new MusicServiceException(ex.getMessage()); - } - return result ? ResultType.SUCCESS : ResultType.FAILURE; - } - - private static void syncQuorum(String keyspace, String table, String primaryKeyValue) throws Exception { - logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---"); - PreparedQueryObject selectQuery = new PreparedQueryObject(); - PreparedQueryObject updateQuery = new PreparedQueryObject(); - - // get the primary key d - TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, table); - String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); // we only support single - // primary key - DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType(); - Object cqlFormattedPrimaryKeyValue = - MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue); - - // get the row of data from a quorum - selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + table + " WHERE " - + primaryKeyName + "= ?" + ";"); - selectQuery.addValue(cqlFormattedPrimaryKeyValue); - MusicUtil.writeBackToQuorum(selectQuery, primaryKeyName, updateQuery, keyspace, table, - cqlFormattedPrimaryKeyValue); - } - - /** - * - * @param query - * @return ResultSet - */ - public ResultSet quorumGet(PreparedQueryObject query) { - ResultSet results = null; - try { - results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(query); - } catch (MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR, - ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR, e); - - } - return results; - } - - public String whoseTurnIsIt(String fullyQualifiedKey) { - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String primaryKeyValue = splitString[2]; - try { - LockObject lockOwner = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue); - if (!lockOwner.getIsLockOwner()) { - return null; - } - return "$" + fullyQualifiedKey + "$" + lockOwner.getLockRef(); - } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.LOCKINGERROR + fullyQualifiedKey, - ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - return null; - } - - public List getCurrentLockHolders(String fullyQualifiedKey) { - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String primaryKeyValue = splitString[2]; - try { - return getLockingServiceHandle().getCurrentLockHolders(keyspace, table, primaryKeyValue); - } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+fullyQualifiedKey ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - return null; - } - - /** - * - * @param lockReference - * @return - */ - public static String getLockNameFromId(String lockReference) { - StringTokenizer st = new StringTokenizer(lockReference); - return st.nextToken("$"); - } - - @Override - public void destroyLockRef(String lockId) throws MusicLockingException { - long start = System.currentTimeMillis(); - String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); - String lockRef = lockId.substring(lockId.lastIndexOf('$')+1); - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String primaryKeyValue = splitString[2]; - try { - getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockRef,MusicUtil.getRetryCount()); - } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockRef, - ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e); - throw new MusicLockingException(e.getMessage()); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms"); - } - - public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference) throws MusicLockingException { - long start = System.currentTimeMillis(); - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String primaryKeyValue = splitString[2]; - try { - getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockReference,MusicUtil.getRetryCount()); - } catch (MusicLockingException | MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK + lockReference, - ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR,e); - throw new MusicLockingException(e.getMessage()); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms"); - return new MusicLockState(LockStatus.UNLOCKED, ""); - } - - @Override - public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException { - String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$")); - String lockRef = lockId.substring(lockId.lastIndexOf('$')+1); - if (voluntaryRelease) { - return voluntaryReleaseLock(fullyQualifiedKey, lockRef); - } else { - return forciblyReleaseLock(fullyQualifiedKey, lockRef); - } - } - - public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference) - throws MusicLockingException { - MusicLockState result = null; - try { - result = destroyLockRef(fullyQualifiedKey, lockReference); - } catch (Exception ex) { - logger.info(EELFLoggerDelegate.applicationLogger, - "Exception in voluntaryReleaseLock() for " + fullyQualifiedKey + "ref: " + lockReference); - throw new MusicLockingException(ex.getMessage()); - } - return result; - } - - public MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException { - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - - //leave a signal that this key could potentially be unsynchronized - String syncTable = keyspace+".unsyncedKeys_"+table; - PreparedQueryObject queryObject = new PreparedQueryObject(); - String values = "(?)"; - queryObject.addValue(fullyQualifiedKey); - String insQuery = "insert into "+syncTable+" (key) values "+values+";"; - queryObject.appendQueryString(insQuery); - try { - MusicDataStoreHandle.getDSHandle().executePut(queryObject, "critical"); - } catch (Exception e) { - logger.error("Cannot forcibly release lock: " + fullyQualifiedKey + " " + lockReference + ". " - + e.getMessage(), e); - } - - //now release the lock - return destroyLockRef(fullyQualifiedKey, lockReference); - } - - @Override - public List releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException { -// System.out.println("IN RELEASEALLLOCKSFOROWNER, "); - - List lockIds = getLockingServiceHandle().getAllLocksForOwner(ownerId, keyspace, table); - for (String lockId : lockIds) { -// System.out.println(" LOCKID = " + lockId); - //return "$" + keyspace + "." + table + "." + lockName + "$" + String.valueOf(lockRef); - releaseLock("$" + keyspace + "." + table + "." + lockId, true); - } - return lockIds; - } - - /** - * - * @param lockName - * @throws MusicLockingException - */ - @Deprecated - public void deleteLock(String lockName) throws MusicLockingException { - throw new MusicLockingException("Depreciated Method Delete Lock"); - } - - // Prepared Query Additions. - - /** - * - * @param queryObject - * @return ReturnType - * @throws MusicServiceException - */ - public ReturnType eventualPut(PreparedQueryObject queryObject) { - boolean result = false; - try { - result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); - } catch (MusicServiceException | MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex); - return new ReturnType(ResultType.FAILURE, ex.getMessage()); - } - if (result) { - return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed"); - } else { - return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform"); - } - } - - /** - * - * @param queryObject - * @return ReturnType - * @throws MusicServiceException - */ - public ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey) { - boolean result = false; - long guard = 0; - PreparedQueryObject getGaurd = new PreparedQueryObject(); - getGaurd.appendQueryString("SELECT guard FROM "+keyspace+".lockq_"+tablename+ " WHERE key = ? ;"); - getGaurd.addValue(primaryKey); - try { - ResultSet getGaurdResult = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(getGaurd); - Row row = getGaurdResult.one(); - if (row != null) { - guard = row.getLong("guard"); - long timeOfWrite = System.currentTimeMillis(); - long ts = MusicUtil.v2sTimeStampInMicroseconds(guard, timeOfWrite); - String query = queryObject.getQuery(); - if (!queryObject.getQuery().contains("USING TIMESTAMP")) { - if (queryObject.getOperation().equalsIgnoreCase("delete")) - query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE "); - else - query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET"); - } - queryObject.replaceQueryString(query); - } - - } catch (MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.applicationLogger,e.getMessage(), e); - } - try { - result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); - } catch (MusicServiceException | MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(),"[ERR512E] Failed to get Lock Handle ", - ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " ", ex); - return new ReturnType(ResultType.FAILURE, ex.getMessage()); - } - if (result) { - return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed"); - } else { - return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform"); - } - } - - /** - * - * @param keyspace - * @param table - * @param primaryKeyValue - * @param queryObject - * @param lockId - * @return - */ - public ReturnType criticalPut(String keyspace, String table, String primaryKeyValue, - PreparedQueryObject queryObject, String lockId, Condition conditionInfo) { - long start = System.currentTimeMillis(); - try { - String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$")); - if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) { - return new ReturnType(ResultType.FAILURE,"Lock value '" + keyLock + "' and key value '" - + primaryKeyValue + "' not match. Please check your values: " - + lockId + " ."); - } - LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, - lockId.substring(lockId.lastIndexOf("$") + 1)); - - if ( lockObject == null ) { - return new ReturnType(ResultType.FAILURE, lockId + " does not exist."); - } else if (!lockObject.getIsLockOwner()) { - return new ReturnType(ResultType.FAILURE, lockId + " is not the lock holder"); - } else if (lockObject.getLocktype() != LockType.WRITE) { - return new ReturnType(ResultType.FAILURE, - "Attempting to do write operation, but " + lockId + " is a read lock"); - } - - if (conditionInfo != null) { - try { - if (conditionInfo.testCondition() == false) - return new ReturnType(ResultType.FAILURE, "Lock acquired but the condition is not true"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e); - return new ReturnType(ResultType.FAILURE, - "Exception thrown while checking the condition, check its sanctity:\n" + e.getMessage()); - } - } - String query = queryObject.getQuery(); - long timeOfWrite = System.currentTimeMillis(); - long lockOrdinal = Long.parseLong(lockId.substring(lockId.lastIndexOf("$") + 1)); - long ts = MusicUtil.v2sTimeStampInMicroseconds(lockOrdinal, timeOfWrite); - // TODO: use Statement instead of modifying query - if (!queryObject.getQuery().contains("USING TIMESTAMP")) { - if (queryObject.getOperation().equalsIgnoreCase("delete")) - query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE "); - else if (queryObject.getOperation().equalsIgnoreCase("insert")) - query = query.replaceFirst(";", " USING TIMESTAMP " + ts + " ; "); - else - query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET"); - } - queryObject.replaceQueryString(query); - MusicDataStore dsHandle = MusicDataStoreHandle.getDSHandle(); - dsHandle.executePut(queryObject, MusicUtil.CRITICAL); - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms"); - } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e); - return new ReturnType(ResultType.FAILURE, - "Exception thrown while doing the critical put: " - + e.getMessage()); - } - return new ReturnType(ResultType.SUCCESS, "Update performed"); - } - - - /** - * - * @param queryObject - * @param consistency - * @return Boolean Indicates success or failure - * @throws MusicServiceException - * - * - */ - public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException,MusicQueryException { - // this is mainly for some functions like keyspace creation etc which does not - // really need the bells and whistles of Music locking. - boolean result = false; -// try { - result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, consistency); -// } catch (MusicQueryException | MusicServiceException ex) { - // logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, - // ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR, ex); -// throw new MusicServiceException(ex.getMessage(),ex); -// } - return result ? ResultType.SUCCESS : ResultType.FAILURE; - } - - /** - * This method performs DDL operation on cassandra. - * - * @param queryObject query object containing prepared query and values - * @return ResultSet - * @throws MusicServiceException - */ - public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { - ResultSet results = null; - try { - results = MusicDataStoreHandle.getDSHandle().executeOneConsistencyGet(queryObject); - } catch (MusicQueryException | MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e); - throw new MusicServiceException(e.getMessage()); - } - return results; - } - - /** - * This method performs DDL operations on cassandra, if the the resource is available. Lock ID - * is used to check if the resource is free. - * - * @param keyspace name of the keyspace - * @param table name of the table - * @param primaryKeyValue primary key value - * @param queryObject query object containing prepared query and values - * @param lockId lock ID to check if the resource is free to perform the operation. - * @return ResultSet - */ - public ResultSet criticalGet(String keyspace, String table, String primaryKeyValue, - PreparedQueryObject queryObject, String lockId) throws MusicServiceException { - ResultSet results = null; - String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$")); - try { - if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) { - throw new MusicLockingException("Lock value '" + keyLock + "' and key value '" - + primaryKeyValue + "' do not match. Please check your values: " - + lockId + " ."); - } - LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, - lockId.substring(lockId.lastIndexOf("$") + 1)); - if (null == lockObject) { - throw new MusicLockingException("No Lock Object. Please check if lock name or key is correct." - + lockId + " ."); - } - if ( !lockObject.getIsLockOwner()) { - return null;// not top of the lock store q - } - results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryObject); - } catch ( MusicLockingException e ) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR); - throw new MusicServiceException( - "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage()); - } catch (MusicQueryException | MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, e); - throw new MusicServiceException( - "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage()); - } - return results; - } - - /** - * This method performs DML operation on cassandra, when the lock of the dd is acquired. - * - * @param keyspaceName name of the keyspace - * @param tableName name of the table - * @param primaryKey primary key value - * @param queryObject query object containing prepared query and values - * @return ReturnType - * @throws MusicLockingException - * @throws MusicServiceException - * @throws MusicQueryException - */ - public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, Condition conditionInfo) - throws MusicLockingException, MusicQueryException, MusicServiceException { - long start = System.currentTimeMillis(); - String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey; - String lockId = createLockReference(fullyQualifiedKey, LockType.WRITE); - long lockCreationTime = System.currentTimeMillis(); - ReturnType lockAcqResult = null; - logger.info(EELFLoggerDelegate.applicationLogger, - "***Acquiring lock for atomicPut() query : " + queryObject.getQuery() + " : " + primaryKey); - logger.info(EELFLoggerDelegate.applicationLogger, - "***Acquiring lock for atomicPut() values: " + queryObject.getValues().toString()); - if (conditionInfo != null) { - logger.info(EELFLoggerDelegate.applicationLogger, - "***Acquiring lock for atomicPut() conditions: " + conditionInfo.toString()); - } - try { - lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod()); - } catch (MusicLockingException ex) { - logger.error(EELFLoggerDelegate.errorLogger, - "Exception while acquireLockWithLease() in atomic put for key: " + primaryKey); - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); - throw new MusicServiceException( - "Cannot perform atomic put for key: " + primaryKey + " : " + ex.getMessage()); - } - long lockAcqTime = System.currentTimeMillis(); - - /* - * if (!lockAcqResult.getResult().equals(ResultType.SUCCESS)) { logger.info(EELFLoggerDelegate. - * applicationLogger,"unable to acquire lock, id " + lockId); - * voluntaryReleaseLock(fullyQualifiedKey,lockId); return lockAcqResult; } - */ - - logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId); - String lockRef = lockId.substring(lockId.lastIndexOf("$")); - ReturnType criticalPutResult = null; - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockRef, conditionInfo); - long criticalPutTime = System.currentTimeMillis(); - long lockDeleteTime = System.currentTimeMillis(); - String timingInfo = "|lock creation time:" + (lockCreationTime - start) + "|lock accquire time:" - + (lockAcqTime - lockCreationTime) + "|critical put time:" + (criticalPutTime - lockAcqTime) - + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|"; - criticalPutResult.setTimingInfo(timingInfo); - } else { - logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId); - criticalPutResult = lockAcqResult; - } - try { - voluntaryReleaseLock(fullyQualifiedKey, lockId); - } catch (MusicLockingException ex) { - logger.info(EELFLoggerDelegate.applicationLogger, - "Exception occured while deleting lock after atomic put for key: " + primaryKey); - criticalPutResult.setMessage(criticalPutResult.getMessage() + "Lock release failed"); - } - return criticalPutResult; - } - - - - /** - * This method performs DDL operation on cassasndra, when the lock for the resource is acquired. - * - * @param keyspaceName name of the keyspace - * @param tableName name of the table - * @param primaryKey primary key value - * @param queryObject query object containing prepared query and values - * @return ResultSet - * @throws MusicServiceException - * @throws MusicLockingException - * @throws MusicQueryException - */ - public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException { - String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey; - String lockId = createLockReference(fullyQualifiedKey, LockType.READ); - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = null; - ResultSet result = null; - logger.info(EELFLoggerDelegate.applicationLogger, "Acquiring lock for atomicGet() : " + queryObject.getQuery()); - try { - lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod()); - } catch (MusicLockingException ex) { - logger.error(EELFLoggerDelegate.errorLogger, - "Exception while acquireLockWithLease() in atomic get for key: " + primaryKey); - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); - throw new MusicServiceException( - "Cannot perform atomic get for key: " + primaryKey + " : " + ex.getMessage()); - } - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId); - String lockRef = lockId.substring(lockId.lastIndexOf("$")); - result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockRef); - } else { - logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId); - } - try { - voluntaryReleaseLock(fullyQualifiedKey, lockId); - } catch (MusicLockingException ex) { - logger.info(EELFLoggerDelegate.applicationLogger, - "Exception occured while deleting lock after atomic put for key: " + primaryKey); - throw new MusicLockingException(ex.getMessage()); - } - - return result; - } - - - - /** - * @param lockName - * @return - */ - public Map validateLock(String lockName) { - return MusicUtil.validateLock(lockName); - } - - @Override - @Deprecated - public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { - return null; - } - - @Override - public List getLockQueue(String fullyQualifiedKey) - throws MusicServiceException, MusicQueryException, MusicLockingException { - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String primaryKeyValue = splitString[2]; - - return getLockingServiceHandle().getLockQueue(keyspace, table, primaryKeyValue); - } - @Override - public long getLockQueueSize(String fullyQualifiedKey) - throws MusicServiceException, MusicQueryException, MusicLockingException { - String[] splitString = fullyQualifiedKey.split("\\."); - String keyspace = splitString[0]; - String table = splitString[1]; - String primaryKeyValue = splitString[2]; - - return getLockingServiceHandle().getLockQueueSize(keyspace, table, primaryKeyValue); - } - - @Override - @Deprecated - public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException { - //deprecated - return null; - } - - //Methods added for ORM changes - - public ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject,String consistencyInfo) - throws MusicServiceException,MusicQueryException { - ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genCreateKeyspaceQuery(), consistencyInfo); - logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace Creation Process completed successfully"); - - return result; - } - - public ResultType dropKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo) - throws MusicServiceException,MusicQueryException { - ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genDropKeyspaceQuery(), - consistencyInfo); - logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace deletion Process completed successfully"); - return result; - } - - public ResultType createTable(JsonTable jsonTableObject, String consistencyInfo) - throws MusicServiceException, MusicQueryException { - ResultType result = null; - try { - result = createTable(jsonTableObject.getKeyspaceName(), - jsonTableObject.getTableName(), jsonTableObject.genCreateTableQuery(), consistencyInfo); - - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, - ErrorTypes.MUSICSERVICEERROR); - throw new MusicServiceException(ex.getMessage()); - } - logger.info(EELFLoggerDelegate.applicationLogger, " Table Creation Process completed successfully "); - return result; - } - - public ResultType dropTable(JsonTable jsonTableObject,String consistencyInfo) - throws MusicServiceException,MusicQueryException { - ResultType result = nonKeyRelatedPut(jsonTableObject.genDropTableQuery(), - consistencyInfo); - logger.info(EELFLoggerDelegate.applicationLogger, " Table deletion Process completed successfully "); - - return result; - } - - @Override - public ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo) - throws MusicServiceException, MusicQueryException{ - ResultType result = nonKeyRelatedPut(jsonIndexObject.genCreateIndexQuery(), - consistencyInfo); - - logger.info(EELFLoggerDelegate.applicationLogger, " Index creation Process completed successfully "); - return result; - } - - /** - * This method performs DDL operation on cassandra. - * - * @param queryObject query object containing prepared query and values - * @return ResultSet - * @throws MusicServiceException - */ - public ResultSet select(JsonSelect jsonSelect, MultivaluedMap rowParams) - throws MusicServiceException, MusicQueryException { - ResultSet results = null; - try { - results = get(jsonSelect.genSelectQuery(rowParams)); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); - throw new MusicServiceException(e.getMessage()); - } - return results; - } - - /** - * Select Critical - */ - public ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException { - - ResultSet results = null; - String consistency = ""; - if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) { - consistency = jsonInsertObj.getConsistencyInfo().get("type"); - } - - String lockId = jsonInsertObj.getConsistencyInfo().get("lockId"); - - PreparedQueryObject queryObject = jsonInsertObj.genSelectCriticalPreparedQueryObj(rowParams); - - if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - results = criticalGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), - jsonInsertObj.getPrimaryKeyVal(), queryObject,lockId); - } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - results = atomicGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), - jsonInsertObj.getPrimaryKeyVal(), queryObject); - } - - return results; - } - - /** - * this is insert row into Table - */ - public ReturnType insertIntoTable(JsonInsert jsonInsertObj) - throws MusicLockingException, MusicQueryException, MusicServiceException { - - String consistency = ""; - if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) { - consistency = jsonInsertObj.getConsistencyInfo().get("type"); - } - - ReturnType result = null; - - try { - PreparedQueryObject queryObj = null; - queryObj = jsonInsertObj.genInsertPreparedQueryObj(); - - if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { - result = eventualPut(jsonInsertObj.genInsertPreparedQueryObj()); - } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - String lockId = jsonInsertObj.getConsistencyInfo().get("lockId"); - if(lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); - return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL"); - } - result = criticalPut(jsonInsertObj.getKeyspaceName(), - jsonInsertObj.getTableName(), jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), lockId,null); - } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - result = atomicPut(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), - jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), null); - } - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return new ReturnType(ResultType.FAILURE, ex.getMessage()); - } - - return result; - } - - /** - * This is insert row into Table - */ - public ReturnType updateTable(JsonUpdate jsonUpdateObj, MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException { - - ReturnType result = null; - String consistency = ""; - if(null != jsonUpdateObj && null != jsonUpdateObj.getConsistencyInfo()) { - consistency = jsonUpdateObj.getConsistencyInfo().get("type"); - } - PreparedQueryObject queryObject = jsonUpdateObj.genUpdatePreparedQueryObj(rowParams); - - Condition conditionInfo; - if (jsonUpdateObj.getConditions() == null) { - conditionInfo = null; - } else { - // to avoid parsing repeatedly, just send the select query to obtain row - PreparedQueryObject selectQuery = new PreparedQueryObject(); - selectQuery.appendQueryString("SELECT * FROM " + jsonUpdateObj.getKeyspaceName() + "." + jsonUpdateObj.getTableName() + " WHERE " - + jsonUpdateObj.getRowIdString() + ";"); - selectQuery.addValue(jsonUpdateObj.getPrimarKeyValue()); - conditionInfo = new Condition(jsonUpdateObj.getConditions(), selectQuery); - } - - - if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { - result = eventualPut(queryObject); - } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - String lockId = jsonUpdateObj.getConsistencyInfo().get("lockId"); - if(lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); - - return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL"); - } - result = criticalPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(), - queryObject, lockId, conditionInfo); - } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) { - // this function is mainly for the benchmarks - try { - result = atomicPutWithDeleteLock(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), - jsonUpdateObj.getPrimarKeyValue(), queryObject, conditionInfo); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, - ErrorTypes.GENERALSERVICEERROR, e); - throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString()); - - } - } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - try { - result = atomicPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(), - queryObject, conditionInfo); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e); - throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString()); - } - } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { - try { - result = eventualPut_nb(queryObject, jsonUpdateObj.getKeyspaceName(), - jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue()); - }catch (Exception e) { - return new ReturnType(ResultType.FAILURE, e.getMessage()); - } - - } - - return result; - } - - /** - * This method is for Delete From Table - */ - public ReturnType deleteFromTable(JsonDelete jsonDeleteObj, MultivaluedMap rowParams) - throws MusicLockingException, MusicQueryException, MusicServiceException { - - ReturnType result = null; - String consistency = ""; - if(null != jsonDeleteObj && null != jsonDeleteObj.getConsistencyInfo()) { - consistency = jsonDeleteObj.getConsistencyInfo().get("type"); - } - PreparedQueryObject queryObject = jsonDeleteObj.genDeletePreparedQueryObj(rowParams); - - // get the conditional, if any - Condition conditionInfo; - if (jsonDeleteObj.getConditions() == null) { - conditionInfo = null; - } else { - // to avoid parsing repeatedly, just send the select query to obtain row - PreparedQueryObject selectQuery = new PreparedQueryObject(); - selectQuery.appendQueryString("SELECT * FROM " + jsonDeleteObj.getKeyspaceName() + "." + jsonDeleteObj.getTableName() + " WHERE " - + jsonDeleteObj.getRowIdString() + ";"); - selectQuery.addValue(jsonDeleteObj.getPrimarKeyValue()); - conditionInfo = new Condition(jsonDeleteObj.getConditions(), selectQuery); - } - - if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) - result = eventualPut(queryObject); - else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - String lockId = jsonDeleteObj.getConsistencyInfo().get("lockId"); - if(lockId == null) { - logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); - - return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL"); - } - result = criticalPut(jsonDeleteObj.getKeyspaceName(), - jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(), - queryObject, lockId, conditionInfo); - } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - result = atomicPut(jsonDeleteObj.getKeyspaceName(), - jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(), - queryObject, conditionInfo); - } else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { - result = eventualPut_nb(queryObject, jsonDeleteObj.getKeyspaceName(), - jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue()); - } - - return result; - } - - -} diff --git a/src/main/resources/LICENSE.txt b/src/main/resources/LICENSE.txt deleted file mode 100644 index cc6cdea5..00000000 --- a/src/main/resources/LICENSE.txt +++ /dev/null @@ -1,24 +0,0 @@ - -The following license applies to all files in this and sub-directories. Licenses -are included in individual source files where appropriate, and if it differs -from this text, it supersedes this. Any file that does not have license text -defaults to being covered by this text; not all files support the addition of -licenses. -# -# ------------------------------------------------------------------------- -# Copyright (c) 2017 AT&T Intellectual Property -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ------------------------------------------------------------------------- -# \ No newline at end of file diff --git a/src/main/resources/Resources.properties b/src/main/resources/Resources.properties deleted file mode 100644 index 72269cb8..00000000 --- a/src/main/resources/Resources.properties +++ /dev/null @@ -1,50 +0,0 @@ -#============LICENSE_START========================================== -#org.onap.music -#=================================================================== -# Copyright (c) 2017 AT&T Intellectual Property -#=================================================================== -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -#============LICENSE_END============================================= -#==================================================================== -#Resource key=Error Code|Message text|Resolution text |Description text -LOADING_DEFAULT_LOG_CONFIGURATION=\ - EELF0001I|\ - Loading default logging configuration from system resource file "{0}"|\ - No external logging configurations were defined or found, So verify the default logging configuration from system resource file (../logback.xml). |\ - Loading default logging configuration from system resource file -LOADING_LOG_CONFIGURATION=EELF0002I|\ - Loading logging configuration from file "{0}"|\ - Verify the correct logging configuration file is loaded. |\ - Loading logging configuration for specific file -LOGGING_ALREADY_INITIALIZED=\ - EELF0003W|\ - Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration.|\ - Verify the container logging definitions to ensure they represent your desired logging configuration. |\ - Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration. -NO_LOG_CONFIGURATION=\ - EELF0004E|\ - No log configuration could be found or defaulted!|\ - No external and default logging configuration file. |\ - No log configuration could be found or defaulted! -SEARCHING_LOG_CONFIGURATION=\ - EELF0005I|\ - Searching path "{0}" for log configuration file "{1}"|\ - Verify the correct Path({user.home};etc;../etc) and filename (eelf.logging.file).|\ - Searching path for specific log configuration file. -UNSUPPORTED_LOGGING_FRAMEWORK=\ - EELF0006E|\ - An unsupported logging framework is bound to SLF4J. |\ - Verify your logging frameworks.|\ - An unsupported logging framework is bound to SLF4J. - diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100755 index 6fbe6326..00000000 --- a/src/main/resources/application.properties +++ /dev/null @@ -1,9 +0,0 @@ -server.port=8080 -server.servlet.context-path=/MUSIC/rest -security.require-ssl=true -server.ssl.key-store=/opt/app/aafcertman/keystore.jks -server.ssl.key-store-password=changeit -server.ssl.key-store-provider=SUN -server.ssl.key-store-type=JKS -httpPort=8081 -spring.jackson.mapper.ACCEPT_CASE_INSENSITIVE_ENUMS=true diff --git a/src/main/resources/key.properties b/src/main/resources/key.properties deleted file mode 100644 index 5ce266fa..00000000 --- a/src/main/resources/key.properties +++ /dev/null @@ -1 +0,0 @@ -cipher.enc.key= nothing to see here diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml deleted file mode 100644 index 69d59ca3..00000000 --- a/src/main/resources/logback.xml +++ /dev/null @@ -1,273 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - ${logDirectory}/${generalLogName}.log - - - ${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip - 1GB - 5 - 5GB - - - ${applicationLoggerPattern} - - - - - 256 - true - - - - - - ${logDirectory}/${securityLogName}.log - - ${logDirectory}/${securityLogName}.%i.log.zip - 1 - 9 - - - 5MB - - - %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n - - - - - 256 - 0 - - - - - - - - - - ${logDirectory}/${auditLogName}.log - - ${logDirectory}/${auditLogName}.%i.log.zip - 1 - 9 - - - 5MB - - - ${auditLoggerPattern} - - - - 256 - - - - - ${logDirectory}/${metricsLogName}.log - - ${logDirectory}/${metricsLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - - ${metricsLoggerPattern} - - - - - - 256 - - - - - ${logDirectory}/${errorLogName}.log - - ${logDirectory}/${errorLogName}.%i.log.zip - 1 - 9 - - - 5MB - - - ${errorLoggerPattern} - - - - - 256 - - - - - ${debugLogDirectory}/${debugLogName}.log - - ${debugLogDirectory}/${debugLogName}.%i.log.zip - 1 - 9 - - - 5MB - - - ${debugLoggerPattern} - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/project.properties b/src/main/resources/project.properties deleted file mode 100644 index 69b99adc..00000000 --- a/src/main/resources/project.properties +++ /dev/null @@ -1,5 +0,0 @@ -version=${project.version} -artifactId=${project.artifactId} -build=${project.version}-${timestamp} -music.properties=/opt/app/music/etc/music.properties - diff --git a/src/test/java/LICENSE.txt b/src/test/java/LICENSE.txt deleted file mode 100644 index cc6cdea5..00000000 --- a/src/test/java/LICENSE.txt +++ /dev/null @@ -1,24 +0,0 @@ - -The following license applies to all files in this and sub-directories. Licenses -are included in individual source files where appropriate, and if it differs -from this text, it supersedes this. Any file that does not have license text -defaults to being covered by this text; not all files support the addition of -licenses. -# -# ------------------------------------------------------------------------- -# Copyright (c) 2017 AT&T Intellectual Property -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ------------------------------------------------------------------------- -# \ No newline at end of file diff --git a/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java b/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java deleted file mode 100644 index 7ab7d148..00000000 --- a/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * e - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.datastore; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -public class PreparedQueryObjectTest { - - private PreparedQueryObject preparedQueryObject; - - @Before - public void setUp() - { - preparedQueryObject = new PreparedQueryObject(); - } - - @Test - public void testKeyspaceName() - { - preparedQueryObject.setKeyspaceName("keyspaceName"); - assertEquals("keyspaceName", preparedQueryObject.getKeyspaceName()); - } - - @Test - public void testConsistency() - { - preparedQueryObject.setConsistency("consistency"); - assertEquals("consistency", preparedQueryObject.getConsistency()); - } - - @Test - public void testTableName() - { - preparedQueryObject.setTableName("tableName"); - assertEquals("tableName", preparedQueryObject.getTableName()); - } - - @Test - public void testoperation() - { - preparedQueryObject.setOperation("operation"); - assertEquals("operation", preparedQueryObject.getOperation()); - } - - @Test - public void testprimaryKeyValue() - { - preparedQueryObject.setPrimaryKeyValue("primaryKeyValue"); - assertEquals("primaryKeyValue", preparedQueryObject.getPrimaryKeyValue()); - } - - @Test - public void testAddValue() { - preparedQueryObject.addValue("one"); - assertEquals("one", preparedQueryObject.getValues().get(0)); - } - - @Test - public void testAddValues() { - preparedQueryObject.addValues("one", "two", "three"); - assertEquals(3, preparedQueryObject.getValues().size()); - assertEquals("two", preparedQueryObject.getValues().get(1)); - } - - @Test - public void testConstructorQuery() { - preparedQueryObject = new PreparedQueryObject("some query string"); - assertEquals("some query string", preparedQueryObject.getQuery()); - } - - @Test - public void testConstructorQueryValues() { - preparedQueryObject = new PreparedQueryObject("another query string", "a", "b", "c"); - assertEquals("another query string", preparedQueryObject.getQuery()); - assertEquals(3, preparedQueryObject.getValues().size()); - assertEquals("b", preparedQueryObject.getValues().get(1)); - } -} diff --git a/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java b/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java deleted file mode 100644 index cba9c7c2..00000000 --- a/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.eelf.logging.format; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -public class AppMessagesTest { - - private AppMessages messages; - - @Before - public void setUp() { - messages= AppMessages.ALREADYEXIST; - } - - @Test - public void testDetails() - { - messages.setDetails("details"); - assertEquals("details", messages.getDetails()); - } - - @Test - public void testResolution() - { - messages.setResolution("Resolution"); - assertEquals("Resolution", messages.getResolution()); - } - - @Test - public void testErrorCode() - { - messages.setErrorCode("ErrorCode"); - assertEquals("ErrorCode", messages.getErrorCode()); - } - - @Test - public void testErrorDescription() - { - messages.setErrorDescription("ErrorDescription"); - assertEquals("ErrorDescription", messages.getErrorDescription()); - } -} diff --git a/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java b/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java deleted file mode 100644 index 58135551..00000000 --- a/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -import org.codehaus.jackson.map.exc.UnrecognizedPropertyException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.ws.rs.core.Response; -import java.io.EOFException; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -@RunWith(SpringJUnit4ClassRunner.class) -public class MusicExceptionMapperTest { - - @Test - public void testToResponse() { - MusicExceptionMapper musicExceptionMapper = new MusicExceptionMapper(); - UnrecognizedPropertyException unrecognizedPropertyException = mock(UnrecognizedPropertyException.class); - Response response = musicExceptionMapper.toResponse(unrecognizedPropertyException); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); - assertTrue(((Map)response.getEntity()).get("error").toString().startsWith("Unknown field :")); - - EOFException eofException = mock(EOFException.class); - response = musicExceptionMapper.toResponse(eofException); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); - assertTrue(((Map)response.getEntity()).get("error").toString().equals("Request body cannot be empty".trim())); - - IllegalArgumentException illegalArgumentException = mock(IllegalArgumentException.class); - Mockito.when(illegalArgumentException.getMessage()).thenReturn("ERROR MSG"); - response = musicExceptionMapper.toResponse(illegalArgumentException); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); - assertTrue(((Map)response.getEntity()).get("error").toString().equals("ERROR MSG".trim())); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java b/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java deleted file mode 100644 index 583a9fd4..00000000 --- a/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class MusicLockingExceptionTest { - - @Test - public void TestException1() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicLockingException(); - } - } catch (MusicLockingException mle) { - assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); - } - - } - - @Test - public void TestException2() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicLockingException("MusicLockingException Exception occured.."); - } - } catch (MusicLockingException mle) { - assertEquals(mle.getMessage(), "MusicLockingException Exception occured.."); - } - - } - - @Test - public void TestException3() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicLockingException(new Throwable()); - } - } catch (MusicLockingException mle) { - assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); - } - - } - - @Test - public void TestException4() { - String message = "Exception occured"; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicLockingException(message, new Throwable()); - } - } catch (MusicLockingException mle) { - assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); - } - - } - - @Test - public void TestException5() { - String message = "Exception occured"; - boolean enableSuppression = true; - boolean writableStackTrace = false; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicLockingException(message, new Throwable(), enableSuppression, writableStackTrace); - } - } catch (MusicLockingException mle) { - assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); - } - - } - -} diff --git a/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java b/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java deleted file mode 100644 index 22e2d728..00000000 --- a/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class MusicPolicyVoilationExceptionTest { - - @Test - public void TestException1() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicPolicyVoilationException(); - } - } catch (MusicPolicyVoilationException mve) { - assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); - } - - } - - @Test - public void TestException2() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicPolicyVoilationException("MusicPolicyVoilationException Exception occured.."); - } - } catch (MusicPolicyVoilationException mve) { - assertEquals(mve.getMessage(), "MusicPolicyVoilationException Exception occured.."); - } - - } - - @Test - public void TestException3() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicPolicyVoilationException(new Throwable()); - } - } catch (MusicPolicyVoilationException mve) { - assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); - } - - } - - @Test - public void TestException4() { - String message = "Exception occured"; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicPolicyVoilationException(message, new Throwable()); - } - } catch (MusicPolicyVoilationException mve) { - assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); - } - - } - - @Test - public void TestException5() { - String message = "Exception occured"; - boolean enableSuppression = true; - boolean writableStackTrace = false; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicPolicyVoilationException(message, new Throwable(), enableSuppression, - writableStackTrace); - } - } catch (MusicPolicyVoilationException mve) { - assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); - } - - } - -} diff --git a/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java b/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java deleted file mode 100644 index 9096506a..00000000 --- a/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class MusicQueryExceptionTest { - - @Test - public void TestException1() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicQueryException(); - } - } catch (MusicQueryException mqe) { - assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); - } - - } - - @Test - public void TestException2() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicQueryException("MusicQueryException Exception occured.."); - } - } catch (MusicQueryException mqe) { - assertEquals(mqe.getMessage(), "MusicQueryException Exception occured.."); - } - - } - - @Test - public void TestException3() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicQueryException("MusicQueryException Exception occured..", 001); - } - } catch (MusicQueryException mqe) { - assertEquals(mqe.getMessage(), "MusicQueryException Exception occured.."); - } - - } - - @Test - public void TestException4() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicQueryException(new Throwable()); - } - } catch (MusicQueryException mqe) { - assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); - } - - } - - @Test - public void TestException5() { - String message = "Exception occured"; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicQueryException(message, new Throwable()); - } - } catch (MusicQueryException mqe) { - assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); - } - - } - - @Test - public void TestException6() { - String message = "Exception occured"; - boolean enableSuppression = true; - boolean writableStackTrace = false; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicQueryException(message, new Throwable(), enableSuppression, writableStackTrace); - } - } catch (MusicQueryException mqe) { - assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); - } - - } - -} diff --git a/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java b/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java deleted file mode 100644 index bf056b61..00000000 --- a/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.exceptions; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class MusicServiceExceptionTest { - @Test - public void TestException1() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicServiceException(); - } - } catch (MusicServiceException mse) { - assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); - } - - } - - @Test - public void TestException2() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicServiceException("MusicServiceException Exception occured.."); - } - } catch (MusicServiceException mse) { - assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); - } - - } - - @Test - public void TestException3() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicServiceException("MusicServiceException Exception occured..", 001); - } - } catch (MusicServiceException mse) { - assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); - } - - } - - @Test - public void TestException4() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicServiceException("MusicServiceException Exception occured..", 001, "errorMsg"); - } - } catch (MusicServiceException mse) { - assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); - } - - } - - @Test - public void TestException5() { - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicServiceException(new Throwable()); - } - } catch (MusicServiceException mse) { - assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); - } - - } - - @Test - public void TestException6() { - String message = "Exception occured"; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicServiceException(message, new Throwable()); - } - } catch (MusicServiceException mse) { - assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); - } - - } - - @Test - public void TestException7() { - String message = "Exception occured"; - boolean enableSuppression = true; - boolean writableStackTrace = false; - String s1 = "Value1"; - String s2 = "value2"; - try { - if (!s1.equalsIgnoreCase(s2)) { - throw new MusicServiceException(message, new Throwable(), enableSuppression, writableStackTrace); - } - } catch (MusicServiceException mse) { - assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); - } - - } - - @Test - public void testErrorCode() { - MusicServiceException musicServiceException = new MusicServiceException(); - musicServiceException.setErrorCode(0001); - assertEquals(0001, musicServiceException.getErrorCode()); - } - - @Test - public void testSetErrorMsg() { - MusicServiceException musicServiceException = new MusicServiceException(); - musicServiceException.setErrorMessage("errorMsg"); - assertEquals("errorMsg", musicServiceException.getErrorMessage()); - } - -} diff --git a/src/test/java/org/onap/music/rest/ApplicationTest.java b/src/test/java/org/onap/music/rest/ApplicationTest.java deleted file mode 100644 index 66983312..00000000 --- a/src/test/java/org/onap/music/rest/ApplicationTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 AT&T Intellectual Property - * - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.rest; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ApplicationTest { - - Application apl=new Application(); - private String application_name="music"; - private String username="music"; - private String password="music"; - private String keyspace_name="music"; - private boolean is_aaf=false; - private String uuid="123"; - private boolean is_api=true; - - @Test - public void testsetApplication_name() { - apl.setApplication_name(application_name); - assertEquals("music",apl.getApplication_name()); - } - - @Test - public void testsetUsername() - { - apl.setUsername(username); - assertEquals("music",apl.getUsername()); - } - - @Test - public void testsetPassword() - { - apl.setPassword(password); - assertEquals("music",apl.getPassword()); - } - - @Test - public void testsetKeyspace_name() - { - apl.setKeyspace_name(keyspace_name); - assertEquals("music",apl.getKeyspace_name()); - } - - @Test - public void testsetIs_aaf() - { - apl.setIs_aaf(is_aaf); - assertEquals(false,apl.isIs_aaf()); - } - - - @Test - public void testsetUuid() - { - apl.setUuid(uuid); - assertEquals("123",apl.getUuid()); - } - - @Test - public void testsetIs_api() - { - apl.setIs_api(is_api); - assertEquals(true,apl.getIs_api()); - - } - - - -} diff --git a/src/test/java/org/onap/music/unittests/CassandraCQL.java b/src/test/java/org/onap/music/unittests/CassandraCQL.java deleted file mode 100644 index 7b116bc8..00000000 --- a/src/test/java/org/onap/music/unittests/CassandraCQL.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -/** - * @author srupane - * - */ - -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -//import org.apache.thrift.transport.TTransportException; -import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.lockingservice.cassandra.LockType; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.extras.codecs.enums.EnumNameCodec; - -public class CassandraCQL { - public static final String createAdminKeyspace = "CREATE KEYSPACE admin WITH REPLICATION = " - + "{'class' : 'SimpleStrategy' , 'replication_factor': 1} AND DURABLE_WRITES = true"; - - public static final String createAdminTable = "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text," - + " application_name text, is_api boolean," - + " password text, username text," - + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");"; - - public static final String createKeySpace = - "CREATE KEYSPACE IF NOT EXISTS testcassa WITH replication = " - +"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;"; - - public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testcassa"; - - public static final String createTableEmployees = - "CREATE TABLE IF NOT EXISTS testcassa.employees " - + "(vector_ts text,empid uuid,empname text,empsalary varint,address Map,PRIMARY KEY (empname)) " - + "WITH comment='Financial Info of employees' " - + "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} " - + "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};"; - - public static final String insertIntoTablePrepared1 = - "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary) VALUES (?,?,?,?); "; - - public static final String insertIntoTablePrepared2 = - "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary,address) VALUES (?,?,?,?,?);"; - - public static final String selectALL = "SELECT * FROM testcassa.employees;"; - - public static final String selectSpecific = - "SELECT * FROM testcassa.employees WHERE empname= ?;"; - - public static final String updatePreparedQuery = - "UPDATE testcassa.employees SET vector_ts=?,address= ? WHERE empname= ?;"; - - public static final String deleteFromTable = " "; - - public static final String deleteFromTablePrepared = " "; - - // Set Values for Prepared Query - - public static List setPreparedInsertValues1() { - - List preppreparedInsertValues1 = new ArrayList<>(); - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6"); - BigInteger empSalary = BigInteger.valueOf(23443); - String empName = "Mr Test one"; - preppreparedInsertValues1.add(vectorTs); - preppreparedInsertValues1.add(empId); - preppreparedInsertValues1.add(empName); - preppreparedInsertValues1.add(empSalary); - return preppreparedInsertValues1; - } - - public static List setPreparedInsertValues2() { - - List preparedInsertValues2 = new ArrayList<>(); - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6"); - BigInteger empSalary = BigInteger.valueOf(45655); - String empName = "Mr Test two"; - Map address = new HashMap<>(); - preparedInsertValues2.add(vectorTs); - preparedInsertValues2.add(empId); - preparedInsertValues2.add(empName); - preparedInsertValues2.add(empSalary); - address.put("Street", "1 some way"); - address.put("City", "Some town"); - preparedInsertValues2.add(address); - return preparedInsertValues2; - } - - public static List setPreparedUpdateValues() { - - List preparedUpdateValues = new ArrayList<>(); - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - Map address = new HashMap<>(); - preparedUpdateValues.add(vectorTs); - String empName = "Mr Test one"; - address.put("Street", "101 Some Way"); - address.put("City", "New York"); - preparedUpdateValues.add(address); - preparedUpdateValues.add(empName); - return preparedUpdateValues; - } - - // Generate Different Prepared Query Objects - /** - * Query Object for Get. - * - * @return - */ - public static PreparedQueryObject setPreparedGetQuery() { - - PreparedQueryObject queryObject = new PreparedQueryObject(); - String empName1 = "Mr Test one"; - queryObject.appendQueryString(selectSpecific); - queryObject.addValue(empName1); - return queryObject; - } - - /** - * Query Object 1 for Insert. - * - * @return {@link PreparedQueryObject} - */ - public static PreparedQueryObject setPreparedInsertQueryObject1() { - - PreparedQueryObject queryobject = new PreparedQueryObject(); - queryobject.appendQueryString(insertIntoTablePrepared1); - List values = setPreparedInsertValues1(); - if (!values.isEmpty() || values != null) { - for (Object o : values) { - queryobject.addValue(o); - } - } - return queryobject; - - } - - /** - * Query Object 2 for Insert. - * - * @return {@link PreparedQueryObject} - */ - public static PreparedQueryObject setPreparedInsertQueryObject2() { - - PreparedQueryObject queryobject = new PreparedQueryObject(); - queryobject.appendQueryString(insertIntoTablePrepared2); - List values = setPreparedInsertValues2(); - if (!values.isEmpty() || values != null) { - for (Object o : values) { - queryobject.addValue(o); - } - } - return queryobject; - - } - - /** - * Query Object for Update. - * - * @return {@link PreparedQueryObject} - */ - public static PreparedQueryObject setPreparedUpdateQueryObject() { - - PreparedQueryObject queryobject = new PreparedQueryObject(); - queryobject.appendQueryString(updatePreparedQuery); - List values = setPreparedUpdateValues(); - if (!values.isEmpty() || values != null) { - for (Object o : values) { - queryobject.addValue(o); - } - } - return queryobject; - - } - - private static ArrayList getAllPossibleLocalIps() { - ArrayList allPossibleIps = new ArrayList(); - try { - Enumeration en = NetworkInterface.getNetworkInterfaces(); - while (en.hasMoreElements()) { - NetworkInterface ni = (NetworkInterface) en.nextElement(); - Enumeration ee = ni.getInetAddresses(); - while (ee.hasMoreElements()) { - InetAddress ia = (InetAddress) ee.nextElement(); - allPossibleIps.add(ia.getHostAddress()); - } - } - } catch (SocketException e) { - System.out.println(e.getMessage()); - } - return allPossibleIps; - } - - public static MusicDataStore connectToEmbeddedCassandra() throws Exception { - System.setProperty("log4j.configuration", "log4j.properties"); - - String address = "localhost"; - - EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - Cluster cluster = new Cluster.Builder().withoutJMXReporting().withoutMetrics().addContactPoint(address).withPort(9142).build(); - cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(5000); - EnumNameCodec lockTypeCodec = new EnumNameCodec(LockType.class); - cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec); - - Session session = cluster.connect(); - - return new MusicDataStore(cluster, session); - } - -} diff --git a/src/test/java/org/onap/music/unittests/JsonResponseTest.java b/src/test/java/org/onap/music/unittests/JsonResponseTest.java deleted file mode 100644 index 6af8c0d9..00000000 --- a/src/test/java/org/onap/music/unittests/JsonResponseTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2018-2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Test; -import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; -import org.onap.music.main.ResultType; -import org.onap.music.response.jsonobjects.JsonResponse; - -public class JsonResponseTest { - - JsonResponse result = null; - - @Test - public void testJsonResponseBooleanStringString() { - result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("version"); - assertEquals("error",result.getError()); - } - - @Test - public void testStatus() { - result = new JsonResponse(ResultType.SUCCESS); - result.setStatus(ResultType.SUCCESS); - assertEquals(ResultType.SUCCESS, result.getStatus()); - result = new JsonResponse(ResultType.FAILURE).setError("error").setMusicVersion("version"); - assertEquals(ResultType.FAILURE, result.getStatus()); - } - - @Test - public void testError() { - result = new JsonResponse(ResultType.FAILURE); - result.setError("error"); - assertTrue(result.getError().equals("error")); - result.setError(""); - assertFalse(result.getError().equals("error")); - } - - @Test - public void testVersion() { - result = new JsonResponse(ResultType.SUCCESS); - result.setMusicVersion("version"); - assertTrue(result.getMusicVersion().equals("version")); - result.setMusicVersion(""); - assertFalse(result.getMusicVersion().equals("version")); - } - - @Test - public void testToMap() { - result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("1.0"); - Map myMap = result.toMap(); - assertTrue(myMap.containsKey("status")); - assertEquals(ResultType.SUCCESS, myMap.get("status")); - assertEquals("error", myMap.get("error")); - assertEquals("1.0", myMap.get("version")); - - result = new JsonResponse(ResultType.FAILURE); - myMap = result.toMap(); - assertTrue(myMap.containsKey("status")); - assertEquals(ResultType.FAILURE, myMap.get("status")); - } - - @Test - public void testMessage() { - result = new JsonResponse(ResultType.SUCCESS); - result.setMessage("message"); - assertEquals("message", result.getMessage()); - - } - - @Test - public void testDataResult() { - result = new JsonResponse(ResultType.SUCCESS); - Map> dataResult= new HashMap<>(); - result.setDataResult(dataResult); - assertEquals(dataResult, result.getDataResult()); - - } - - @Test - public void testLock() { - result = new JsonResponse(ResultType.SUCCESS); - result.setLock("lock"); - assertEquals("lock", result.getLock()); - - } - - @Test - public void testLockLease() { - result = new JsonResponse(ResultType.SUCCESS); - result.setLockLease("lockLease"); - assertEquals("lockLease", result.getLockLease()); - } - - @Test - public void testMusicBuild() { - result = new JsonResponse(ResultType.SUCCESS); - result.setMusicBuild("Build"); - assertEquals("Build", result.getMusicBuild()); - } - - @Test - public void testLockHolder() { - result = new JsonResponse(ResultType.SUCCESS); - List lockHolders = new ArrayList<>(); - result.setLockHolder(lockHolders); - assertEquals(lockHolders, result.getLockHolder()); - } - - @Test - public void testLockStatus() { - result = new JsonResponse(ResultType.SUCCESS); - LockStatus status = LockStatus.LOCKED; - result.setLockStatus(status); - assertEquals(status, result.getLockStatus()); - - } - - @Test - public void testToString() { - result = new JsonResponse(ResultType.SUCCESS); - assertTrue(result.toString() instanceof String); - - } - - @Test - public void testLockHolders() { - result = new JsonResponse(ResultType.SUCCESS).setLock("lockName").setLockHolder("lockholder1"); - Map lockMap = (Map) result.toMap().get("lock"); - // assure that this is string for backwards compatibility - assertEquals("lockholder1", lockMap.get("lock-holder")); - - List lockholders = new ArrayList<>(); - lockholders.add("lockholder1"); - lockholders.add("lockholder2"); - result.setLockHolder(lockholders); - lockMap = (Map) result.toMap().get("lock"); - assertEquals(lockMap.get("lock-holder"), lockholders); - } -} diff --git a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java deleted file mode 100644 index 68e6f3dc..00000000 --- a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.mockito.Mock; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.PreparedQueryObject; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.TableMetadata; - -@RunWith(SpringJUnit4ClassRunner.class) -//@ActiveProfiles(profiles = "OrderRepositoryTest") -@ContextConfiguration -public class MusicDataStoreTest { - - static MusicDataStore dataStore; - static PreparedQueryObject testObject; - - @BeforeClass - public static void init()throws Exception { - dataStore = CassandraCQL.connectToEmbeddedCassandra(); - //CachingUtil.resetStatementBank(); - - } - - @AfterClass - public static void close() throws MusicServiceException, MusicQueryException { - - testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.dropKeyspace); - dataStore.executePut(testObject, "eventual"); - //dataStore.close(); - //CachingUtil.resetStatementBank(); - } - - @Test - public void Test1_SetUp() throws MusicServiceException, MusicQueryException { - boolean result = false; - //CachingUtil.resetStatementBank(); - testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createKeySpace); - result = dataStore.executePut(testObject, "eventual");; - testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createTableEmployees); - result = dataStore.executePut(testObject, "eventual"); - assertEquals(true, result); - - } - - @Test - public void Test2_ExecutePut_eventual_insert() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedInsertQueryObject1(); - boolean result = dataStore.executePut(testObject, "eventual"); - assertEquals(true, result); - } - - @Test - public void Test3_ExecutePut_critical_insert() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedInsertQueryObject2(); - boolean result = dataStore.executePut(testObject, "Critical"); - assertEquals(true, result); - } - - @Test - public void Test4_ExecutePut_eventual_update() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedUpdateQueryObject(); - boolean result = false; - result = dataStore.executePut(testObject, "eventual"); - assertEquals(true, result); - } - - @Test - public void Test5_ExecuteEventualGet() throws MusicServiceException, MusicQueryException { - testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.selectALL); - boolean result = false; - int count = 0; - ResultSet output = null; - output = dataStore.executeOneConsistencyGet(testObject); - System.out.println(output); - ; - for (Row row : output) { - count++; - System.out.println(row.toString()); - } - if (count == 2) { - result = true; - } - assertEquals(false, result); - } - - @Test - public void Test6_ExecuteCriticalGet() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedGetQuery(); - boolean result = false; - int count = 0; - ResultSet output = null; - output = dataStore.executeQuorumConsistencyGet(testObject); - System.out.println(output); - ; - for (Row row : output) { - count++; - System.out.println(row.toString()); - } - if (count == 1) { - result = true; - } - assertEquals(false, result); - } - - @Test(expected = NullPointerException.class) - public void Test7_exception() { - PreparedQueryObject queryObject = null; - try { - dataStore.executePut(queryObject, "critical"); - } catch (MusicQueryException | MusicServiceException e) { - System.out.println(e.getMessage()); - } - } - - @Test - public void Test8_columnDataType() { - DataType data = dataStore.returnColumnDataType("testCassa", "employees", "empName"); - String datatype = data.toString(); - assertEquals("text",datatype); - } - - @Test - public void Test8_columnMetdaData() { - TableMetadata data = dataStore.returnColumnMetadata("testCassa", "employees"); - assertNotNull(data); - } -} diff --git a/src/test/java/org/onap/music/unittests/MusicUtilTest.java b/src/test/java/org/onap/music/unittests/MusicUtilTest.java deleted file mode 100644 index c4c8ba2e..00000000 --- a/src/test/java/org/onap/music/unittests/MusicUtilTest.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * Modifications Copyright (C) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests; - -import static org.junit.Assert.*; -import java.math.BigInteger; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.junit.Test; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.PropertiesLoader; -import org.onap.music.service.MusicCoreService; - -import com.datastax.driver.core.ConsistencyLevel; -import com.datastax.driver.core.DataType; - -public class MusicUtilTest { - - private static final String XLATESTVERSION = "X-latestVersion"; - private static final String XMINORVERSION = "X-minorVersion"; - private static final String XPATCHVERSION = "X-patchVersion"; - - @Test - public void testGetCassName() { - MusicUtil.setCassName("Cassandra"); - assertTrue(MusicUtil.getCassName().equals("Cassandra")); - } - - @Test - public void testGetCassPwd() { - MusicUtil.setCassPwd("Cassandra"); - assertTrue(MusicUtil.getCassPwd().equals("Cassandra")); - } - - @Test - public void testMusicAafNs() { - MusicUtil.setMusicAafNs("ns"); - assertTrue("ns".equals(MusicUtil.getMusicAafNs())); - } - - @Test - public void testMusicCoreService() { - MusicUtil.setLockUsing(MusicUtil.CASSANDRA); - MusicCoreService mc = null; - mc = MusicUtil.getMusicCoreService(); - assertTrue(mc != null); - MusicUtil.setLockUsing("nothing"); - mc = null; - mc = MusicUtil.getMusicCoreService(); - assertTrue(mc != null); - - } - - @Test - public void testCipherEncKey() { - MusicUtil.setCipherEncKey("cipherEncKey"); - assertTrue("cipherEncKey".equals(MusicUtil.getCipherEncKey())); - } - - @Test - public void testGetMusicPropertiesFilePath() { - MusicUtil.setMusicPropertiesFilePath("filepath"); - assertEquals(MusicUtil.getMusicPropertiesFilePath(),"filepath"); - } - - @Test - public void testGetDefaultLockLeasePeriod() { - MusicUtil.setDefaultLockLeasePeriod(5000); - assertEquals(MusicUtil.getDefaultLockLeasePeriod(),5000); - } - - @Test - public void testIsDebug() { - MusicUtil.setDebug(true); - assertTrue(MusicUtil.isDebug()); - } - - @Test - public void testGetVersion() { - MusicUtil.setVersion("1.0.0"); - assertEquals(MusicUtil.getVersion(),"1.0.0"); - } - - @Test - public void testBuildVersionA() { - assertEquals(MusicUtil.buildVersion("1","2","3"),"1.2.3"); - } - - @Test - public void testBuildVersionB() { - assertEquals(MusicUtil.buildVersion("1",null,"3"),"1"); - } - - @Test - public void testBuildVersionC() { - assertEquals(MusicUtil.buildVersion("1","2",null),"1.2"); - } - - - @Test - public void testBuileVersionResponse() { - assertTrue(MusicUtil.buildVersionResponse("1","2","3").getClass().getSimpleName().equals("Builder")); - assertTrue(MusicUtil.buildVersionResponse("1",null,"3").getClass().getSimpleName().equals("Builder")); - assertTrue(MusicUtil.buildVersionResponse("1","2",null).getClass().getSimpleName().equals("Builder")); - assertTrue(MusicUtil.buildVersionResponse(null,null,null).getClass().getSimpleName().equals("Builder")); - } - - @Test - public void testGetConsistency() { - assertTrue(ConsistencyLevel.ONE.equals(MusicUtil.getConsistencyLevel("one"))); - } - - @Test - public void testRetryCount() { - MusicUtil.setRetryCount(1); - assertEquals(MusicUtil.getRetryCount(),1); - } - - @Test - public void testIsCadi() { - MusicUtil.setIsCadi(true); - assertEquals(MusicUtil.getIsCadi(),true); - } - - - @Test - public void testGetMyCassaHost() { - MusicUtil.setMyCassaHost("10.0.0.2"); - assertEquals(MusicUtil.getMyCassaHost(),"10.0.0.2"); - } - - @Test - public void testIsValidQueryObject() { - PreparedQueryObject myQueryObject = new PreparedQueryObject(); - myQueryObject.appendQueryString("select * from apple where type = ?"); - myQueryObject.addValue("macintosh"); - assertTrue(MusicUtil.isValidQueryObject(true,myQueryObject)); - - myQueryObject.appendQueryString("select * from apple"); - assertTrue(MusicUtil.isValidQueryObject(false,myQueryObject)); - - myQueryObject.appendQueryString("select * from apple where type = ?"); - assertFalse(MusicUtil.isValidQueryObject(true,myQueryObject)); - - myQueryObject = new PreparedQueryObject(); - myQueryObject.appendQueryString(""); - System.out.println("#######" + myQueryObject.getQuery().isEmpty()); - assertFalse(MusicUtil.isValidQueryObject(false,myQueryObject)); - - - } - - - - - @Test(expected = IllegalStateException.class) - public void testMusicUtil() { - System.out.println("MusicUtil Constructor Test"); - MusicUtil mu = new MusicUtil(); - System.out.println(mu.toString()); - } - - @Test - public void testConvertToCQLDataType() throws Exception { - Map myMap = new HashMap(); - myMap.put("name","tom"); - assertEquals(MusicUtil.convertToCQLDataType(DataType.varchar(),"Happy People"),"'Happy People'"); - assertEquals(MusicUtil.convertToCQLDataType(DataType.uuid(),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")),"29dc2afa-c2c0-47ae-afae-e72a645308ab"); - assertEquals(MusicUtil.convertToCQLDataType(DataType.blob(),"Hi"),"Hi"); - assertEquals(MusicUtil.convertToCQLDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),"{'name':'tom'}"); - } - - @Test - public void testConvertToActualDataType() throws Exception { - assertEquals(MusicUtil.convertToActualDataType(DataType.varchar(),"Happy People"),"Happy People"); - assertEquals(MusicUtil.convertToActualDataType(DataType.uuid(),"29dc2afa-c2c0-47ae-afae-e72a645308ab"),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")); - assertEquals(MusicUtil.convertToActualDataType(DataType.varint(),"1234"),BigInteger.valueOf(Long.parseLong("1234"))); - assertEquals(MusicUtil.convertToActualDataType(DataType.bigint(),"123"),Long.parseLong("123")); - assertEquals(MusicUtil.convertToActualDataType(DataType.cint(),"123"),Integer.parseInt("123")); - assertEquals(MusicUtil.convertToActualDataType(DataType.cfloat(),"123.01"),Float.parseFloat("123.01")); - assertEquals(MusicUtil.convertToActualDataType(DataType.cdouble(),"123.02"),Double.parseDouble("123.02")); - assertEquals(MusicUtil.convertToActualDataType(DataType.cboolean(),"true"),Boolean.parseBoolean("true")); - List myList = new ArrayList(); - List newList = myList; - myList.add("TOM"); - assertEquals(MusicUtil.convertToActualDataType(DataType.list(DataType.varchar()),myList),newList); - Map myMap = new HashMap(); - myMap.put("name","tom"); - Map newMap = myMap; - assertEquals(MusicUtil.convertToActualDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),newMap); - } - - @Test - public void testConvertToActualDataTypeByte() throws Exception { - byte[] testByte = "TOM".getBytes(); - assertEquals(MusicUtil.convertToActualDataType(DataType.blob(),testByte),ByteBuffer.wrap(testByte)); - - } - - @Test - public void testJsonMaptoSqlString() throws Exception { - Map myMap = new HashMap<>(); - myMap.put("name","tom"); - myMap.put("value",5); - String result = MusicUtil.jsonMaptoSqlString(myMap,","); - assertTrue(result.contains("name")); - assertTrue(result.contains("value")); - } - - @Test - public void test_generateUUID() { - //this function shouldn't be in cachingUtil - System.out.println("Testing getUUID"); - String uuid1 = MusicUtil.generateUUID(); - String uuid2 = MusicUtil.generateUUID(); - assertFalse(uuid1==uuid2); - } - - - @Test - public void testIsValidConsistency(){ - assertTrue(MusicUtil.isValidConsistency("ALL")); - assertFalse(MusicUtil.isValidConsistency("TEST")); - } - - @Test - public void testLockUsing() { - MusicUtil.setLockUsing("testlock"); - assertEquals("testlock", MusicUtil.getLockUsing()); - } - - @Test - public void testCassaPort() { - MusicUtil.setCassandraPort(1234); - assertEquals(1234, MusicUtil.getCassandraPort()); - } - - @Test - public void testBuild() { - MusicUtil.setBuild("testbuild"); - assertEquals("testbuild", MusicUtil.getBuild()); - } - - @Test - public void testTransId() { - MusicUtil.setTransIdPrefix("prefix"); - assertEquals("prefix-", MusicUtil.getTransIdPrefix()); - } - - - @Test - public void testConversationIdPrefix() { - MusicUtil.setConversationIdPrefix("prefix-"); - assertEquals("prefix-", MusicUtil.getConversationIdPrefix()); - } - - @Test - public void testClientIdPrefix() { - MusicUtil.setClientIdPrefix("clientIdPrefix"); - assertEquals("clientIdPrefix-", MusicUtil.getClientIdPrefix()); - } - - @Test - public void testMessageIdPrefix() { - MusicUtil.setMessageIdPrefix("clientIdPrefix"); - assertEquals("clientIdPrefix-", MusicUtil.getMessageIdPrefix()); - } - - @Test - public void testTransIdPrefix() { - MusicUtil.setTransIdPrefix("transIdPrefix"); - assertEquals("transIdPrefix-", MusicUtil.getTransIdPrefix()); - } - - @Test - public void testConvIdReq() { - MusicUtil.setConversationIdRequired(true); - assertEquals(true, MusicUtil.getConversationIdRequired()); - } - - @Test - public void testClientIdRequired() { - MusicUtil.setClientIdRequired(true); - assertEquals(true, MusicUtil.getClientIdRequired()); - } - - @Test - public void testMessageIdRequired() { - MusicUtil.setMessageIdRequired(true); - assertEquals(true, MusicUtil.getMessageIdRequired()); - } - - @Test - public void testTransIdRequired() { - MusicUtil.setTransIdRequired(true); - assertEquals(true,MusicUtil.getTransIdRequired()); - } - - @Test - public void testLoadProperties() { - PropertiesLoader pl = new PropertiesLoader(); - pl.loadProperties(); - } - -} diff --git a/src/test/java/org/onap/music/unittests/ResultTypeTest.java b/src/test/java/org/onap/music/unittests/ResultTypeTest.java deleted file mode 100644 index 012629e0..00000000 --- a/src/test/java/org/onap/music/unittests/ResultTypeTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -import static org.junit.Assert.*; -import org.junit.Test; -import org.onap.music.main.ResultType; - -public class ResultTypeTest { - - @Test - public void testResultType() { - assertEquals("SUCCESS",ResultType.SUCCESS.name()); - assertEquals("FAILURE",ResultType.FAILURE.name()); - } - - @Test - public void testGetResult() { - assertEquals("Success",ResultType.SUCCESS.getResult()); - assertEquals("Failure",ResultType.FAILURE.getResult()); - } - -} diff --git a/src/test/java/org/onap/music/unittests/ReturnTypeTest.java b/src/test/java/org/onap/music/unittests/ReturnTypeTest.java deleted file mode 100644 index 490020ac..00000000 --- a/src/test/java/org/onap/music/unittests/ReturnTypeTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Map; - -import org.junit.Test; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; - -public class ReturnTypeTest { - - @Test - public void testReturnType() { - ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); - assertEquals(result.getMessage(),"message"); - assertEquals(result.getResult(),ResultType.SUCCESS); - } - - @Test - public void testTimingInfo() { - ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); - result.setTimingInfo("123"); - assertEquals(result.getTimingInfo(),"123"); - } - - @Test - public void testGetResult() { - ReturnType result = new ReturnType(ResultType.FAILURE,"message"); - assertEquals(result.getResult(),ResultType.FAILURE); - } - - @Test - public void testGetMessage() { - ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); - result.setMessage("NewMessage"); - assertEquals(result.getMessage(),"NewMessage"); - } - - @Test - public void testToJson() { - ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); - String myJson = result.toJson(); - assertTrue(myJson.contains("message")); - } - - @Test - public void testToString() { - ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); - String test = result.toString(); - assertTrue(test.contains("message")); - } - - @Test - public void testToMap() { - ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); - Map myMap = result.toMap(); - assertTrue(myMap.containsKey("message")); - } - -} diff --git a/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java b/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java deleted file mode 100644 index 385a4698..00000000 --- a/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java +++ /dev/null @@ -1,975 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -//cjc import static org.junit.Assert.assertTrue; -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.List; -//cjc import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.mindrot.jbcrypt.BCrypt; -//cjcimport org.mindrot.jbcrypt.BCrypt; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -//cjc import org.onap.music.datastore.jsonobjects.JsonKeySpace; -//import org.onap.music.datastore.jsonobjects.JsonOnboard; -import org.onap.music.datastore.jsonobjects.JsonSelect; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.lockingservice.cassandra.CassaLockStore; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -//import org.onap.music.main.ResultType; -//import org.onap.music.rest.RestMusicAdminAPI; -import org.onap.music.rest.RestMusicDataAPI; -import org.onap.music.rest.RestMusicQAPI; -import org.springframework.test.util.ReflectionTestUtils; -import org.onap.music.rest.RestMusicLocksAPI; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.sun.jersey.core.util.Base64; -//import com.datastax.driver.core.DataType; -//import com.datastax.driver.core.ResultSet; -//import com.datastax.driver.core.Row; -import com.sun.jersey.core.util.MultivaluedMapImpl; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(MockitoJUnitRunner.class) -public class TestRestMusicQAPI { - - - //RestMusicAdminAPI admin = new RestMusicAdminAPI(); - RestMusicLocksAPI lock = new RestMusicLocksAPI(); - RestMusicQAPI qData = new RestMusicQAPI(); - static PreparedQueryObject testObject; - - @Mock - static HttpServletResponse http; - - @Mock - UriInfo info; - - static String appName = "TestApp"; - static String userId = "TestUser"; - static String password = "TestPassword"; - /* - static String appName = "com.att.ecomp.portal.demeter.aid";//"TestApp"; - static String userId = "m00468@portal.ecomp.att.com";//"TestUser"; - static String password = "happy123";//"TestPassword"; - */ - static String authData = userId+":"+password; - static String wrongAuthData = userId+":"+"pass"; - static String authorization = new String(Base64.encode(authData.getBytes())); - static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); - - static boolean isAAF = false; - static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); - static String uuidS = "abc66ccc-d857-4e90-b1e5-df98a3d40ce6"; - static String keyspaceName = "testkscjc"; - static String tableName = "employees"; - static String xLatestVersion = "X-latestVersion"; - static String onboardUUID = null; - static String lockId = null; - static String lockName = "testkscjc.employees.sample3"; - static String majorV="3"; - static String minorV="0"; - static String patchV="1"; - static String aid=null; - static JsonKeySpace kspObject=null; - static RestMusicDataAPI data = new RestMusicDataAPI(); - static Response resp; - - @BeforeClass - public static void init() throws Exception { - try { - ReflectionTestUtils.setField(MusicDataStoreHandle.class, "mDstoreHandle", - CassandraCQL.connectToEmbeddedCassandra()); - MusicCore.setmLockHandle(new CassaLockStore(MusicDataStoreHandle.getDSHandle())); - - // System.out.println("before class keysp"); - //resp=data.createKeySpace(majorV,minorV,patchV,aid,appName,userId,password,kspObject,keyspaceName); - //System.out.println("after keyspace="+keyspaceName); - } catch (Exception e) { - System.out.println("before class exception "); - e.printStackTrace(); - } - // admin keyspace and table - testObject = new PreparedQueryObject(); - testObject.appendQueryString("CREATE KEYSPACE admin WITH REPLICATION = " - + "{'class' : 'SimpleStrategy' , " - + "'replication_factor': 1} AND DURABLE_WRITES = true"); - MusicCore.eventualPut(testObject); - testObject = new PreparedQueryObject(); - testObject.appendQueryString( - "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text," - + " application_name text, is_api boolean," - + " password text, username text," - + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");"); - MusicCore.eventualPut(testObject); - - testObject = new PreparedQueryObject(); - testObject.appendQueryString( - "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), - MusicUtil.DEFAULTKEYSPACENAME)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - MusicCore.eventualPut(testObject); - - testObject = new PreparedQueryObject(); - testObject.appendQueryString( - "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), - UUID.fromString("bbc66ccc-d857-4e90-b1e5-df98a3d40de6"))); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), - MusicUtil.DEFAULTKEYSPACENAME)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestApp1")); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestUser1")); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - MusicCore.eventualPut(testObject); - - testObject = new PreparedQueryObject(); - testObject.appendQueryString( - "select uuid from admin.keyspace_master where application_name = ? allow filtering"); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - ResultSet rs = MusicCore.get(testObject); - List rows = rs.all(); - if (rows.size() > 0) { - System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid")); - } - - JsonKeySpace jsonKeyspace = new JsonKeySpace(); - Map consistencyInfo = new HashMap<>(); - Map replicationInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - replicationInfo.put("class", "SimpleStrategy"); - replicationInfo.put("replication_factor", 1); - jsonKeyspace.setConsistencyInfo(consistencyInfo); - jsonKeyspace.setDurabilityOfWrites("true"); - jsonKeyspace.setKeyspaceName(keyspaceName); - jsonKeyspace.setReplicationInfo(replicationInfo); - Response response = data.createKeySpace(majorV, minorV, patchV, null, authorization, appName, - jsonKeyspace, keyspaceName); - System.out.println("#######status is " + response.getStatus()+" keyspace="+keyspaceName); - - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - System.out.println("After class"); - testObject = new PreparedQueryObject(); - testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); - MusicCore.eventualPut(testObject); - testObject = new PreparedQueryObject(); - testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin"); - MusicCore.eventualPut(testObject); - MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle"); - if (mds != null) - mds.close(); - } - - -/* @Test - public void Test1_createQ_good() throws Exception { - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setTableName(tableName); - jsonTable.setFields(fields); - jsonTable.setPartitionKey("emp_name"); - jsonTable.setClusteringKey("uuid"); - jsonTable.setClusteringOrder("uuid ASC"); - //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableName); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()); - System.out.println("Entity" + response.getEntity()); - assertEquals(200, response.getStatus()); - }*/ - - @Test - public void Test1_createQ_FieldsEmpty() throws Exception { - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - /* - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - */ - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableName); - jsonTable.setFields(fields); - //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableName); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("EmptyFields #######status is " + response.getStatus()); - System.out.println("Entity" + response.getEntity()); - assertNotEquals(200, response.getStatus()); - } -/* @Test - public void Test1_createQ_Clustergood() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPartitionKey("emp_name"); - jsonTable.setClusteringKey("emp_id"); - jsonTable.setClusteringOrder("emp_id DESC"); - jsonTable.setTableName(tableNameC); - jsonTable.setFields(fields); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(200, response.getStatus()); - }*/ - -/* @Test - public void Test1_createQ_ClusterOrderGood1() throws Exception { - String tableNameC="testcjcO"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name,emp_id)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_id DESC"); - jsonTable.setFields(fields); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(200, response.getStatus()); - } */ - -/* @Test - public void Test1_createQ_PartitionKeygood() throws Exception { - String tableNameP="testcjcP"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setTableName(tableNameP); - jsonTable.setClusteringOrder("emp_id DESC"); - jsonTable.setFields(fields); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameP); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameP); - System.out.println("Entity" + response.getEntity()); - assertEquals(200, response.getStatus()); - } */ - - @Test - public void Test1_createQ_PartitionKeybadclose() throws Exception { - String tableNameC="testcjcP1"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id))"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name,emp_id"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_id DESC"); - jsonTable.setFields(fields); - //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - //assertEquals(400, response.getStatus()); - assertTrue(200 != response.getStatus()); - } - -/* @Test - public void Test1_createQ_ClusterOrderGood2() throws Exception { - String tableNameC="testcjcO1g"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name,emp_salary,emp_id)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name,emp_id"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC"); - jsonTable.setFields(fields); - //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(200, response.getStatus()); - } */ - - /* @Test - public void Test1_createQ_ColPkeyoverridesPrimaryKeyGood() throws Exception { - String tableNameC="testcjcPr"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name),emp_salary,emp_id)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name,emp_id"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC"); - jsonTable.setFields(fields); - //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(200, response.getStatus()); - //assertTrue(200 != response.getStatus()); - } */ - - @Test - public void Test1_createQ_ClusterOrderBad() throws Exception { - String tableNameC="testcjcO1b"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name,emp_id)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name,emp_id"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_id DESCx"); - jsonTable.setFields(fields); - //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - - @Test - public void Test3_createQ_0() throws Exception { - //duplicate testing ... - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - String tableNameDup=tableName+"X"; - jsonTable.setTableName(tableNameDup); - jsonTable.setFields(fields); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - jsonTable, keyspaceName, tableNameDup); - System.out.println("#######status for 1st time " + response.getStatus()); - System.out.println("Entity" + response.getEntity()); - - Response response0 = qData.createQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - jsonTable, keyspaceName, tableNameDup); - // 400 is the duplicate status found in response - // Music 113 duplicate testing - //import static org.junit.Assert.assertNotEquals; - System.out.println("#######status for 2nd time " + response0.getStatus()); - System.out.println("Entity" + response0.getEntity()); - - assertFalse("Duplicate table not created for "+tableNameDup, 200==response0.getStatus()); - //assertEquals(400, response0.getStatus()); - //assertNotEquals(200,response0.getStatus()); - } - - - // Improper keyspace - @Ignore - @Test - public void Test3_createQ2() throws Exception { - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPartitionKey("emp_name"); - jsonTable.setTableName(tableName); - jsonTable.setClusteringKey("emp_salary"); - jsonTable.setClusteringOrder("emp_salary DESC"); - jsonTable.setFields(fields); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - jsonTable, "wrong", tableName); - System.out.println("#######status is " + response.getStatus()); - System.out.println("Entity" + response.getEntity()); - assertEquals(401, response.getStatus()); - } - - - -/* @Test - public void Test4_insertIntoQ() throws Exception { - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testName"); - values.put("emp_salary", 500); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, keyspaceName, tableName); - assertEquals(200, response.getStatus()); - }*/ - - - @Test - public void Test4_insertIntoQ_valuesEmpty() throws Exception { - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - /* - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testName"); - values.put("emp_salary", 500); - */ - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, keyspaceName, tableName); - assertNotEquals(200, response.getStatus()); - } - -/* @Test - public void Test4_insertIntoQ2() throws Exception { - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "test1"); - values.put("emp_salary", 1500); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.insertIntoQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - jsonInsert, keyspaceName, tableName); - assertEquals(200, response.getStatus()); - }*/ - - - -/* @Test - public void Test5_updateQ() throws Exception { - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - Map values = new HashMap<>(); - row.add("emp_name", "testName"); - row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_salary", "2500"); - consistencyInfo.put("type", "atomic"); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName(tableName); - jsonUpdate.setValues(values); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = qData.updateQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, keyspaceName, tableName, info); - assertEquals(200, response.getStatus()); - }*/ - - @Test - public void Test5_updateQEmptyValues() throws Exception { - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - Map values = new HashMap<>(); - row.add("emp_name", "testName"); - //values.put("emp_salary", 2500); - consistencyInfo.put("type", "atomic"); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName(tableName); - jsonUpdate.setValues(values); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - //Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = qData.updateQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, keyspaceName, tableName, info); - assertNotEquals(200, response.getStatus()); - } - -/* @Test - public void Test6_filterQ() throws Exception { //select - JsonSelect jsonSelect = new JsonSelect(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testName"); - row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - consistencyInfo.put("type", "atomic"); - jsonSelect.setConsistencyInfo(consistencyInfo); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = qData.filter(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, keyspaceName, tableName, info); - HashMap> map = (HashMap>) response.getEntity(); - HashMap result = map.get("result"); - assertEquals("2500", ((HashMap) result.get("row 0")).get("emp_salary").toString()); - }*/ - -/* @Test - public void Test6_peekQ() throws Exception { //select - JsonSelect jsonSelect = new JsonSelect(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testName"); - consistencyInfo.put("type", "atomic"); - jsonSelect.setConsistencyInfo(consistencyInfo); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = qData.peek(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, keyspaceName, tableName, info); - HashMap> map = (HashMap>) response.getEntity(); - HashMap result = map.get("result"); - if (result.isEmpty() ) assertTrue(true); - else assertFalse(false); - //assertEquals("2500", ((HashMap) result.get("row 0")).get("emp_salary").toString()); - }*/ -/* - @Test - public void Test6_peekQ_empty() throws Exception { //select - // row is not needed in thhis test - JsonSelect jsonSelect = new JsonSelect(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testName"); - consistencyInfo.put("type", "atomic"); - jsonSelect.setConsistencyInfo(consistencyInfo); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - UriInfo infoe= mockUriInfo("/peek?");//empty queryParam: cause exception - // infoe.setQueryParameters(""); - System.out.println("uriinfo="+infoe.getQueryParameters()); - Mockito.when(infoe.getQueryParameters()).thenReturn(row); - Response response = qData.peek(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, keyspaceName, tableName, infoe); - HashMap> map = (HashMap>) response.getEntity(); - HashMap result = map.get("result"); - if (result.isEmpty() ) assertTrue(true); - else assertFalse(false); - //assertEquals("2500", ((HashMap) result.get("row 0")).get("emp_salary").toString()); - }*/ - -/* @Test - public void Test6_deleteFromQ1() throws Exception { - JsonDelete jsonDelete = new JsonDelete(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "test1"); - consistencyInfo.put("type", "atomic"); - jsonDelete.setConsistencyInfo(consistencyInfo); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = qData.deleteFromQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - jsonDelete, keyspaceName, tableName, info); - assertEquals(200, response.getStatus()); - }*/ - - // Values - @Test - @Ignore - public void Test6_deleteFromQ() throws Exception { - JsonDelete jsonDelete = new JsonDelete(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - consistencyInfo.put("type", "atomic"); - jsonDelete.setConsistencyInfo(consistencyInfo); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = qData.deleteFromQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - jsonDelete, keyspaceName, tableName, info); - assertEquals(400, response.getStatus()); - } - - // delObj - @Test - public void Test6_deleteFromQ2() throws Exception { - JsonDelete jsonDelete = new JsonDelete(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "test1"); - consistencyInfo.put("type", "atomic"); - jsonDelete.setConsistencyInfo(consistencyInfo); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - //Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = qData.deleteFromQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - null, keyspaceName, tableName, info); - assertEquals(400, response.getStatus()); - } -/* - @Test - public void Test7_dropQ() throws Exception { - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "atomic"); - jsonTable.setConsistencyInfo(consistencyInfo); - Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.dropQ(majorV, minorV,patchV, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - keyspaceName, tableName); - assertEquals(200, response.getStatus()); - }*/ - - private UriInfo mockUriInfo(String urix) throws URISyntaxException { - String uri="http://localhost:8080/MUSIC/rest/v"+majorV+"/priorityq/keyspaces/"+keyspaceName+"/"+tableName+urix; - UriInfo uriInfo = Mockito.mock(UriInfo.class); - System.out.println("mock urix="+urix+" uri="+uri); - Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI(uri)); - return uriInfo; - } - - - //Empty Fields - @Test - public void Test8_createQ_fields_empty() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPartitionKey("emp_name"); - jsonTable.setClusteringKey("emp_id"); - jsonTable.setClusteringOrder("emp_id DESC"); - jsonTable.setTableName(tableNameC); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - //Partition key null - @Test - public void Test8_createQ_partitionKey_empty() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setClusteringKey("emp_id"); - jsonTable.setClusteringOrder("emp_id DESC"); - jsonTable.setTableName(tableNameC); - jsonTable.setFields(fields); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - //Clustering key null - @Test - public void Test8_createQ_ClusteringKey_empty() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPartitionKey("emp_name"); - jsonTable.setClusteringOrder("emp_id DESC"); - jsonTable.setTableName(tableNameC); - jsonTable.setFields(fields); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - //Clustering Order null - @Test - public void Test8_createQ_ClusteringOrder_empty() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPartitionKey("emp_name"); - jsonTable.setClusteringKey("emp_id"); - jsonTable.setTableName(tableNameC); - jsonTable.setFields(fields); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - //Invalid primary key - @Test - public void Test8_createQ_primaryKey_invalid() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setPrimaryKey("(emp_name"); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setClusteringKey("emp_id"); - jsonTable.setClusteringOrder("emp_id ASC"); - jsonTable.setTableName(tableNameC); - jsonTable.setFields(fields); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - //Primary key with no clustering key - @Test - public void Test8_createQ_primaryKey_with_empty_clusteringKey() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableNameC); - jsonTable.setFields(fields); - jsonTable.setClusteringOrder("emp_id ASC"); - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - - } - - //Primary key with no partition key - @Test - public void Test8_createQ_primaryKey_with_empty_partitionKey() throws Exception { - String tableNameC="testcjcC"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "text"); - fields.put("emp_salary", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey(" "); - jsonTable.setTableName(tableNameC); - jsonTable.setFields(fields); - jsonTable.setClusteringOrder("emp_id ASC"); - - //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = qData.createQ(majorV, minorV,patchV, - aid, appName, authorization, - jsonTable, keyspaceName, tableNameC); - System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC); - System.out.println("Entity" + response.getEntity()); - assertEquals(400, response.getStatus()); - } - -} diff --git a/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java b/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java deleted file mode 100644 index cc7c5146..00000000 --- a/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -import java.util.List; -import java.util.UUID; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; -import org.mindrot.jbcrypt.BCrypt; -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.lockingservice.cassandra.CassaLockStore; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.springframework.test.util.ReflectionTestUtils; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.sun.jersey.core.util.Base64; - -@RunWith(Suite.class) -@SuiteClasses({ TstRestMusicDataAPI.class, TstRestMusicLockAPI.class, - TstRestMusicConditionalAPI.class}) -public class TestsUsingCassandra { - - static String appName = "TestApp"; - static String userId = "TestUser"; - static String password = "TestPassword"; - static String authData = userId+":"+password; - static String wrongAuthData = userId+":"+"pass"; - static String authorization = new String(Base64.encode(authData.getBytes())); - static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); - static boolean isAAF = false; - static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); - static String keyspaceName = "testcassa"; - static String tableName = "employees"; - static String xLatestVersion = "X-latestVersion"; - static String onboardUUID = null; - static String aid = "abc66ccc-d857-4e90-b1e5-df98a3d40ce6"; - - @BeforeClass - public static void beforeClass() throws Exception { - ReflectionTestUtils.setField(MusicDataStoreHandle.class, "mDstoreHandle", - CassandraCQL.connectToEmbeddedCassandra()); - MusicCore.setmLockHandle(new CassaLockStore(MusicDataStoreHandle.getDSHandle())); - createAdminTable(); - } - - @AfterClass - public static void afterClass() { - PreparedQueryObject testObject = new PreparedQueryObject(); - testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin"); - MusicCore.eventualPut(testObject); - MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle"); - if (mds != null) - mds.close(); - } - - private static void createAdminTable() throws Exception { - PreparedQueryObject testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createAdminKeyspace); - MusicCore.eventualPut(testObject); - testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createAdminTable); - MusicCore.eventualPut(testObject); - - testObject = new PreparedQueryObject(); - testObject.appendQueryString( - "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), - keyspaceName)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - MusicCore.eventualPut(testObject); - - testObject = new PreparedQueryObject(); - testObject.appendQueryString( - "select uuid from admin.keyspace_master where application_name = ? allow filtering"); - testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - ResultSet rs = MusicCore.get(testObject); - List rows = rs.all(); - if (rows.size() > 0) { - System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid")); - onboardUUID = rows.get(0).getUUID("uuid").toString(); - } - } -} diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java deleted file mode 100644 index 7021178e..00000000 --- a/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * ============LICENSE_START========================================== org.onap.music - * =================================================================== Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== Licensed under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR 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.music.unittests; - -import static org.junit.Assert.assertEquals; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mindrot.jbcrypt.BCrypt; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.music.conductor.conditionals.JsonConditional; -import org.onap.music.conductor.conditionals.RestMusicConditionalAPI; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonSelect; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.rest.RestMusicDataAPI; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.sun.jersey.core.util.Base64; -import com.sun.jersey.core.util.MultivaluedMapImpl; - -@RunWith(MockitoJUnitRunner.class) -public class TstRestMusicConditionalAPI { - - RestMusicDataAPI data = new RestMusicDataAPI(); - RestMusicConditionalAPI cond = new RestMusicConditionalAPI(); - static PreparedQueryObject testObject; - - @Mock - HttpServletResponse http; - - @Mock - UriInfo info; - - static String appName = "TestApp"; - static String userId = "TestUser"; - static String password = "TestPassword"; - static String authData = userId + ":" + password; - static String wrongAuthData = userId + ":" + "pass"; - static String authorization = new String(Base64.encode(authData.getBytes())); - static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); - static boolean isAAF = false; - static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); - static String keyspaceName = "testcassa"; - static String tableName = "employees"; - static String xLatestVersion = "X-latestVersion"; - static String onboardUUID = null; - - @BeforeClass - public static void init() throws Exception { - System.out.println("Testing RestMusicConditional class"); - try { - createKeyspace(); - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage()); - } - } - - @After - public void afterEachTest() throws MusicServiceException { - clearAllTablesFromKeyspace(); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - testObject = new PreparedQueryObject(); - testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); - MusicCore.eventualPut(testObject); - } - - @Test - public void test_insertIntoTable() throws Exception { - System.out.println("Testing conditional insert into table"); - createTable(); - - JsonConditional jsonCond = new JsonConditional(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("id", "test_id"); - consistencyInfo.put("type", "eventual"); - HashMap cascadeData = new HashMap<>(); - HashMap cascadeValue = new HashMap<>(); - cascadeValue.put("created", "hello"); - cascadeValue.put("updated", "world"); - cascadeData.put("key", "p1"); - cascadeData.put("value", cascadeValue); - HashMap> condition = new HashMap<>(); - HashMap exists = new HashMap<>(); - exists.put("status", "parked"); - HashMap nonexists = new HashMap<>(); - nonexists.put("status", "underway"); - condition.put("exists", exists); - condition.put("nonexists", nonexists); - - jsonCond.setPrimaryKey("id"); - jsonCond.setPrimaryKeyValue("testname"); - jsonCond.setCasscadeColumnName("plans"); - jsonCond.setTableValues(values); - jsonCond.setCasscadeColumnData(cascadeData); - jsonCond.setConditions(condition); - - Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, keyspaceName, tableName, jsonCond); - - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - /* - * @Test public void test4_insertIntoTable2() throws Exception { System.out.println("Testing insert into table #2"); - * createTable(); JsonInsert jsonInsert = new JsonInsert(); Map consistencyInfo = new HashMap<>(); - * Map values = new HashMap<>(); values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - * values.put("emp_name", "test1"); values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual"); - * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName); - * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1", - * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonInsert, keyspaceName, tableName); - * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - * - * assertEquals(200, response.getStatus()); } - * - * // Auth Error - * - * @Test public void test4_insertIntoTable3() throws Exception { - * System.out.println("Testing insert into table with bad credentials"); createTable(); JsonInsert jsonInsert = new - * JsonInsert(); Map consistencyInfo = new HashMap<>(); Map values = new - * HashMap<>(); values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); values.put("emp_name", "test1"); - * values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual"); - * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName); - * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1", - * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, wrongAuthorization, jsonInsert, keyspaceName, - * tableName); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - * - * assertEquals(401, response.getStatus()); } - * - * // Table wrong - * - * @Test public void test4_insertIntoTable4() throws Exception { - * System.out.println("Testing insert into wrong table"); createTable(); JsonInsert jsonInsert = new JsonInsert(); - * Map consistencyInfo = new HashMap<>(); Map values = new HashMap<>(); - * values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); values.put("emp_name", "test1"); - * values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual"); - * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName); - * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1", - * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonInsert, keyspaceName, "wrong"); - * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - * - * assertEquals(400, response.getStatus()); } - */ - - @Test - public void test5_updateTable() throws Exception { - System.out.println("Testing conditional update table"); - createAndInsertIntoTable(); - - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - - JsonConditional jsonCond = new JsonConditional(); - Map values = new HashMap<>(); - values.put("id", "test_id"); - HashMap cascadeData = new HashMap<>(); - HashMap cascadeValue = new HashMap<>(); - cascadeValue.put("created", "hello"); - cascadeValue.put("updated", "world"); - cascadeData.put("key", "p1"); - cascadeData.put("value", cascadeValue); - - jsonCond.setPrimaryKey("id"); - jsonCond.setPrimaryKeyValue("test_id"); - jsonCond.setCasscadeColumnName("plans"); - jsonCond.setTableValues(values); - jsonCond.setCasscadeColumnData(cascadeData); - - Response response = cond.updateConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, keyspaceName, tableName, jsonCond); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - /* - * // need mock code to create error for MusicCore methods - * - * @Test public void test5_updateTableAuthE() throws Exception { System.out.println("Testing update table #2"); - * createTable(); //MockitoAnnotations.initMocks(this); JsonUpdate jsonUpdate = new JsonUpdate(); Map consistencyInfo = new HashMap<>(); MultivaluedMap row = new MultivaluedMapImpl(); - * Map values = new HashMap<>(); row.add("emp_name", "testname"); values.put("emp_salary", 2500); - * consistencyInfo.put("type", "atomic"); jsonUpdate.setConsistencyInfo(consistencyInfo); - * jsonUpdate.setKeyspaceName(keyspaceName); jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values); //add - * ttl & timestamp //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - * Mockito.when(info.getQueryParameters()).thenReturn(row); //Map m1= new HashMap<>() ; - * //Mockito.when(MusicCore.autheticateUser(appName,userId,password,keyspaceName, - * "abc66ccc-d857-4e90-b1e5-df98a3d40ce6","updateTable")).thenReturn(m1); Response response = data.updateTable("1", - * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonUpdate, keyspaceName, tableName, - * info); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - * - * assertEquals(200, response.getStatus()); } - * - * @Ignore - * - * @Test public void test5_updateTableAuthException1() throws Exception { - * System.out.println("Testing update table authentication error"); createTable(); JsonUpdate jsonUpdate = new - * JsonUpdate(); Map consistencyInfo = new HashMap<>(); MultivaluedMap row = new - * MultivaluedMapImpl(); Map values = new HashMap<>(); row.add("emp_name", "testname"); - * values.put("emp_salary", 2500); consistencyInfo.put("type", "atomic"); - * jsonUpdate.setConsistencyInfo(consistencyInfo); jsonUpdate.setKeyspaceName(keyspaceName); - * jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values); - * - * Mockito.when(info.getQueryParameters()).thenReturn(row); String authDatax = ":"; String authorizationx = new - * String(Base64.encode(authDatax.getBytes())); Response response = data.updateTable("1", "1", "1", - * "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorizationx, jsonUpdate, keyspaceName, tableName, info); - * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - * - * assertEquals(401, response.getStatus()); } - * - * @Ignore - * - * @Test public void test5_updateTableAuthEmpty() throws Exception { - * System.out.println("Testing update table without authentication"); createTable(); - * - * JsonUpdate jsonUpdate = new JsonUpdate(); Map consistencyInfo = new HashMap<>(); - * MultivaluedMap row = new MultivaluedMapImpl(); Map values = new HashMap<>(); - * row.add("emp_name", "testname"); values.put("emp_salary", 2500); consistencyInfo.put("type", "atomic"); - * jsonUpdate.setConsistencyInfo(consistencyInfo); jsonUpdate.setKeyspaceName(keyspaceName); - * jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values); - * - * Mockito.when(info.getQueryParameters()).thenReturn(row); String authDatax =":"+password; String authorizationx = - * new String(Base64.encode(authDatax.getBytes())); String appNamex="xx"; Response response = data.updateTable("1", - * "1", "1", "", appNamex, authorizationx, jsonUpdate, keyspaceName, tableName, info); System.out.println("Status: " - * + response.getStatus() + ". Entity " + response.getEntity()); - * - * assertEquals(401, response.getStatus()); } - * - */ - - private static void createKeyspace() throws Exception { - // shouldn't really be doing this here, but create keyspace is currently turned off - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString(CassandraCQL.createKeySpace); - MusicCore.eventualPut(query); - - boolean isAAF = false; - String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); - query = new PreparedQueryObject(); - query.appendQueryString("INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); - query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - MusicCore.eventualPut(query); - } - - private void clearAllTablesFromKeyspace() throws MusicServiceException { - ArrayList tableNames = new ArrayList<>(); - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString( - "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '" + keyspaceName + "';"); - ResultSet rs = MusicCore.get(query); - for (Row row : rs) { - tableNames.add(row.getString("table_name")); - } - for (String table : tableNames) { - query = new PreparedQueryObject(); - query.appendQueryString("DROP TABLE " + keyspaceName + "." + table); - MusicCore.eventualPut(query); - } - } - - /** - * Create a table {@link tableName} in {@link keyspaceName} - * - * @throws Exception - */ - private void createTable() throws Exception { - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("id", "text"); - fields.put("plans", "map"); - fields.put("PRIMARY KEY", "(id)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("id"); - jsonTable.setTableName(tableName); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableName); - } - - /** - * Create table {@link createTable} and insert into said table - * - * @throws Exception - */ - private void createAndInsertIntoTable() throws Exception { - createTable(); - - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - JsonConditional jsonCond = new JsonConditional(); - Map values = new HashMap<>(); - values.put("id", "test_id"); - HashMap cascadeData = new HashMap<>(); - HashMap cascadeValue = new HashMap<>(); - cascadeValue.put("created", "hello"); - cascadeValue.put("updated", "world"); - cascadeData.put("key", "p1"); - cascadeData.put("value", cascadeValue); - HashMap> condition = new HashMap<>(); - HashMap exists = new HashMap<>(); - exists.put("status", "parked"); - HashMap nonexists = new HashMap<>(); - nonexists.put("status", "underway"); - condition.put("exists", exists); - condition.put("nonexists", nonexists); - - jsonCond.setPrimaryKey("id"); - jsonCond.setPrimaryKeyValue("test_id"); - jsonCond.setCasscadeColumnName("plans"); - jsonCond.setTableValues(values); - jsonCond.setCasscadeColumnData(cascadeData); - jsonCond.setConditions(condition); - - Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, keyspaceName, tableName, jsonCond); - } -} diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java deleted file mode 100644 index 407d0323..00000000 --- a/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java +++ /dev/null @@ -1,1161 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -import static org.junit.Assert.assertEquals; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mindrot.jbcrypt.BCrypt; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.music.datastore.MusicDataStoreHandle; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonSelect; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import org.onap.music.rest.RestMusicDataAPI; -import org.onap.music.rest.RestMusicLocksAPI; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.sun.jersey.core.util.Base64; -import com.sun.jersey.core.util.MultivaluedMapImpl; - -@RunWith(MockitoJUnitRunner.class) -public class TstRestMusicDataAPI { - - RestMusicDataAPI data = new RestMusicDataAPI(); - RestMusicLocksAPI lock = new RestMusicLocksAPI(); - static PreparedQueryObject testObject; - - @Mock - HttpServletResponse http; - - @Mock - UriInfo info; - - static String appName = "TestApp"; - static String userId = "TestUser"; - static String password = "TestPassword"; - static String authData = userId + ":" + password; - static String wrongAuthData = userId + ":" + "pass"; - static String authorization = new String(Base64.encode(authData.getBytes())); - static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); - static boolean isAAF = false; - static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); - static String keyspaceName = "testcassa"; - static String tableName = "employees"; - static String xLatestVersion = "X-latestVersion"; - static String onboardUUID = null; - static String aid = TestsUsingCassandra.aid; - - @BeforeClass - public static void init() throws Exception { - System.out.println("Testing RestMusicData class"); - try { - createKeyspace(); - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage()); - } - } - - @After - public void afterEachTest() throws MusicServiceException { - clearAllTablesFromKeyspace(); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - testObject = new PreparedQueryObject(); - testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); - MusicCore.eventualPut(testObject); - } - - @Test - public void test1_createKeyspace() throws Exception { - System.out.println("Testing create keyspace"); - JsonKeySpace jsonKeyspace = new JsonKeySpace(); - Map consistencyInfo = new HashMap<>(); - Map replicationInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - replicationInfo.put("class", "SimpleStrategy"); - replicationInfo.put("replication_factor", 1); - jsonKeyspace.setConsistencyInfo(consistencyInfo); - jsonKeyspace.setDurabilityOfWrites("true"); - jsonKeyspace.setKeyspaceName(keyspaceName); - jsonKeyspace.setReplicationInfo(replicationInfo); - // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = - data.createKeySpace("1", "1", "1", null, authorization, appName, jsonKeyspace, keyspaceName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - Map respMap = (Map) response.getEntity(); - assertEquals(ResultType.FAILURE, respMap.get("status")); - } - - @Test - public void test1_createKeyspaceSuccess() throws Exception { - System.out.println("Testing successful creation and deletion of keyspace"); - MusicUtil.setKeyspaceActive(true); - - String keyspaceToCreate = "temp"+keyspaceName; - - - JsonKeySpace jsonKeyspace = new JsonKeySpace(); - Map consistencyInfo = new HashMap<>(); - Map replicationInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - replicationInfo.put("class", "SimpleStrategy"); - replicationInfo.put("replication_factor", 1); - jsonKeyspace.setConsistencyInfo(consistencyInfo); - jsonKeyspace.setDurabilityOfWrites("true"); - //don't overwrite a keyspace we already have - jsonKeyspace.setKeyspaceName(keyspaceToCreate); - jsonKeyspace.setReplicationInfo(replicationInfo); - // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = - data.createKeySpace("1", "1", "1", null, authorization, appName, jsonKeyspace, keyspaceToCreate); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - Map respMap = (Map) response.getEntity(); - assertEquals(ResultType.SUCCESS, respMap.get("status")); - - response = data.dropKeySpace("1", "1", "1", null, authorization, appName, keyspaceToCreate); - assertEquals(200, response.getStatus()); - respMap = (Map) response.getEntity(); - assertEquals(ResultType.SUCCESS, respMap.get("status")); - - //unset to not mess up any further tests - MusicUtil.setKeyspaceActive(false); - } - - @Test - public void test3_createTable() throws Exception { - System.out.println("Testing create table"); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableName); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - @Test - public void test3_createTableNoBody() throws Exception { - System.out.println("Testing create table w/o body"); - - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, null, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test3_createTableNoName() throws Exception { - System.out.println("Testing create table without name"); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(""); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, ""); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test3_createTableNoFields() throws Exception { - System.out.println("Testing create table without fields"); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(""); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, ""); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - - @Test - public void test3_createTableClusterOrderBad() throws Exception { - System.out.println("Testing create table bad clustering"); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name,emp_salary)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name,emp_salary"); - jsonTable.setClusteringOrder("ASC"); - jsonTable.setTableName(tableName); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test3_createTable_withPropertiesNotNull() throws Exception { - System.out.println("Testing create table with properties"); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - Map properties = new HashMap<>(); - properties.put("comment", "Testing prperties not null"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - String tableName_prop = tableName + "_Prop"; - jsonTable.setTableName(tableName_prop); - jsonTable.setFields(fields); - jsonTable.setProperties(properties); - - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableName_prop); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - @Test - public void test3_createTable_duplicateTable() throws Exception { - System.out.println("Testing creating duplicate tables"); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - String tableNameDup = tableName + "x"; - jsonTable.setTableName(tableNameDup); - jsonTable.setFields(fields); - // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response1 = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameDup); - - Response response2 = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameDup); - System.out.println("Status: " + response2.getStatus() + ". Entity " + response2.getEntity()); - - assertEquals(400, response2.getStatus()); - Map respMap = (Map) response2.getEntity(); - assertEquals(ResultType.FAILURE, respMap.get("status")); - assertEquals("AlreadyExistsException: Table " + keyspaceName + "." + tableNameDup + " already exists", respMap.get("error")); - } - - - // Improper parenthesis in key field - @Test - public void test3_createTable_badParanthesis() throws Exception { - System.out.println("Testing malformed create table request"); - String tableNameC = "testTable0"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name),emp_id)"); - fields.put("emp_id", "varint"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_id Desc"); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameC); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - - // good clustering key - @Test - public void test3_createTable_1_clusterKey_good() throws Exception { - System.out.println("Testing create w/ clusterKey"); - - String tableNameC = "testTableC1"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name),emp_salary)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - // jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_salary ASC"); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameC); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - // bad partition key=clustering key - @Test - public void test3_createTable_2_clusterKey_bad() throws Exception { - System.out.println("Testing create w/ bad clusterKey"); - String tableNameC = "testTableC2"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name),emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); // "PRIMARY KEY" overrides if primaryKey present - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_salary ASC"); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameC); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - // good composite partition key,clustering key - @Test - public void test3_createTable_3_pfartition_clusterKey_good() throws Exception { - System.out.println("Testing create w/ composite partition key, clusterKey"); - - String tableNameC = "testTableC3"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "varint"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name,emp_id),emp_salary)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_salary ASC"); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameC); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - // bad - wrong cols in order by of composite partition key,clustering key - @Test - public void test3_createTable_5_clusteringOrder_bad() throws Exception { - System.out.println("Testing create table bad request with clustering & composite keys"); - String tableNameC = "testTableC5"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_id", "varint"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((uuid,emp_name),emp_id,emp_salary)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_idx desc, emp_salary ASC"); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameC); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - - // good clustering key, need to pass queryparameter - @Test - public void test3_createTableIndex_1() throws Exception { - System.out.println("Testing index in create table"); - String tableNameC = "testTableCinx"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name),emp_salary)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_salary ASC"); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameC); - // if 200 print to log otherwise fail assertEquals(200, response.getStatus()); - // info.setQueryParameters("index_name=inx_uuid"); - Map queryParametersMap = new HashMap(); - - queryParametersMap.put("index_name", "inxuuid"); - Mockito.when(info.getQueryParameters()).thenReturn(new MultivaluedHashMap(queryParametersMap)); - response = data.createIndex("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - keyspaceName, tableNameC, "uuid", info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - // create index without table name - @Test - public void test3_createTableIndexNoName() throws Exception { - System.out.println("Testing index in create table w/o tablename"); - String tableNameC = "testTableCinx"; - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "((emp_name),emp_salary)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setTableName(tableNameC); - jsonTable.setClusteringOrder("emp_salary ASC"); - jsonTable.setFields(fields); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableNameC); - // if 200 print to log otherwise fail assertEquals(200, response.getStatus()); - // info.setQueryParameters("index_name=inx_uuid"); - Map queryParametersMap = new HashMap(); - - queryParametersMap.put("index_name", "inxuuid"); - response = data.createIndex("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, "", - "", "uuid", info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test4_insertIntoTable() throws Exception { - System.out.println("Testing insert into table"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname"); - values.put("emp_salary", 500); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - @Test - public void test4_insertIntoTableNoBody() throws Exception { - System.out.println("Testing insert into table w/o body"); - createTable(); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, null, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test4_insertIntoTableNoaValues() throws Exception { - System.out.println("Testing insert into table"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test4_insertIntoTableNoValues() throws Exception { - System.out.println("Testing insert into table"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test4_insertIntoTableCriticalNoLockID() throws Exception { - System.out.println("Testing critical insert into table without lockid"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname"); - values.put("emp_salary", 500); - consistencyInfo.put("type", "critical"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test4_insertIntoTableAtomic() throws Exception { - System.out.println("Testing atomic insert into table without lockid"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname"); - values.put("emp_salary", 500); - consistencyInfo.put("type", "atomic"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - @Test - public void test4_insertIntoTableNoName() throws Exception { - System.out.println("Testing insert into table w/o table name"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname"); - values.put("emp_salary", 500); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, "", ""); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test4_insertIntoTable2() throws Exception { - System.out.println("Testing insert into table #2"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "test1"); - values.put("emp_salary", 1500); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - // Table wrong - @Test - public void test4_insertIntoTable4() throws Exception { - System.out.println("Testing insert into wrong table"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "test1"); - values.put("emp_salary", 1500); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, "wrong"); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test4_insertBlobIntoTable() throws Exception { - System.out.println("Testing insert a blob into table"); - createTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname"); - values.put("emp_salary", 500); - values.put("binary", "somestuffhere"); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - @Test - public void test5_updateTable() throws Exception { - System.out.println("Testing update table"); - createTable(); - - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - Map values = new HashMap<>(); - row.add("emp_name", "testname"); - values.put("emp_salary", 2500); - consistencyInfo.put("type", "atomic"); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName(tableName); - jsonUpdate.setValues(values); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, keyspaceName, tableName, info); - - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - - public void test5_updateTableNoBody() throws Exception { - System.out.println("Testing update table no body"); - createTable(); - - Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, null, keyspaceName, tableName, info); - - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test5_updateTable_tableDNE() throws Exception { - System.out.println("Testing update table that does not exist"); - createTable(); - - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("emp_salary", 2500); - consistencyInfo.put("type", "atomic"); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName("wrong_"+tableName); - jsonUpdate.setValues(values); - Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, keyspaceName, "wrong_"+ tableName, info); - - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test5_updateTableNoName() throws Exception { - System.out.println("Testing update table without tablename"); - createTable(); - - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("emp_salary", 2500); - consistencyInfo.put("type", "atomic"); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName(tableName); - jsonUpdate.setValues(values); - Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, "", "", info); - - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - // need mock code to create error for MusicCore methods - @Test - public void test5_updateTableAuthE() throws Exception { - System.out.println("Testing update table #2"); - createTable(); - // MockitoAnnotations.initMocks(this); - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - Map values = new HashMap<>(); - row.add("emp_name", "testname"); - values.put("emp_salary", 2500); - consistencyInfo.put("type", "atomic"); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName(tableName); - jsonUpdate.setValues(values); - // add ttl & timestamp - // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Mockito.when(info.getQueryParameters()).thenReturn(row); - // Map m1= new HashMap<>() ; - // Mockito.when(MusicCore.autheticateUser(appName,userId,password,keyspaceName,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6","updateTable")).thenReturn(m1); - Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, keyspaceName, tableName, info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - @Test - public void test6_critical_selectAtomic() throws Exception { - System.out.println("Testing critical select atomic"); - createAndInsertIntoTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testname"); - consistencyInfo.put("type", "atomic"); - jsonInsert.setConsistencyInfo(consistencyInfo); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, keyspaceName, tableName,info); - HashMap> map = (HashMap>) response.getEntity(); - HashMap result = map.get("result"); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - Map row0 = (Map) result.get("row 0"); - assertEquals("testname", row0.get("emp_name")); - assertEquals(BigInteger.valueOf(500), row0.get("emp_salary")); - } - - - @Test - public void test6_critical_select() throws Exception { - System.out.println("Testing critical select w/o body"); - createAndInsertIntoTable(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testname"); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, null, keyspaceName, tableName,info); - HashMap> map = (HashMap>) response.getEntity(); - HashMap result = map.get("result"); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - // Added during merge? - @Test - public void test6_critical_selectCritical_nolockid() throws Exception { - System.out.println("Testing critical select critical w/o lockid"); - createAndInsertIntoTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testname"); - consistencyInfo.put("type", "critical"); - jsonInsert.setConsistencyInfo(consistencyInfo); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, keyspaceName, tableName,info); - HashMap> map = (HashMap>) response.getEntity(); - HashMap result = map.get("result"); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test6_critical_select_nulltable() throws Exception { - System.out.println("Testing critical select w/ null tablename"); - createAndInsertIntoTable(); - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "atomic"); - jsonInsert.setConsistencyInfo(consistencyInfo); - Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, authorization, jsonInsert, keyspaceName, null,info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test6_select() throws Exception { - System.out.println("Testing select"); - createAndInsertIntoTable(); - JsonSelect jsonSelect = new JsonSelect(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testname"); - consistencyInfo.put("type", "atomic"); - jsonSelect.setConsistencyInfo(consistencyInfo); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = data.selectWithCritical("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, - null,keyspaceName, tableName, info); - HashMap> map = (HashMap>) response.getEntity(); - HashMap result = map.get("result"); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - Map row0 = (Map) result.get("row 0"); - assertEquals("testname", row0.get("emp_name")); - assertEquals(BigInteger.valueOf(500), row0.get("emp_salary")); - } - - @Test - public void test6_select_nullTablename() throws Exception { - System.out.println("Testing select w/ null tablename"); - createAndInsertIntoTable(); - JsonSelect jsonSelect = new JsonSelect(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "atomic"); - jsonSelect.setConsistencyInfo(consistencyInfo); - Response response = data.selectWithCritical("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", - appName, wrongAuthorization,null, keyspaceName, null, info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test6_deleteFromTable() throws Exception { - System.out.println("Testing delete from table"); - createAndInsertIntoTable(); - JsonDelete jsonDelete = new JsonDelete(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "test1"); - consistencyInfo.put("type", "atomic"); - jsonDelete.setConsistencyInfo(consistencyInfo); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonDelete, keyspaceName, tableName, info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - @Test - public void test6_deleteFromTable_missingTablename() throws Exception { - System.out.println("Testing delete from table w/ null tablename"); - createAndInsertIntoTable(); - JsonDelete jsonDelete = new JsonDelete(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "atomic"); - jsonDelete.setConsistencyInfo(consistencyInfo); - Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - wrongAuthorization, jsonDelete, keyspaceName, null, info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - // Values - @Ignore - @Test - public void test6_deleteFromTable1() throws Exception { - System.out.println("Testing delete from table missing delete object"); - createAndInsertIntoTable(); - - JsonDelete jsonDelete = new JsonDelete(); - Map consistencyInfo = new HashMap<>(); - MultivaluedMap row = new MultivaluedMapImpl(); - consistencyInfo.put("type", "atomic"); - jsonDelete.setConsistencyInfo(consistencyInfo); - Mockito.when(info.getQueryParameters()).thenReturn(row); - Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonDelete, keyspaceName, tableName, info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - // delObj - @Test - public void test6_deleteFromTable2() throws Exception { - System.out.println("Testing delete from table missing delete object"); - createAndInsertIntoTable(); - JsonDelete jsonDelete = new JsonDelete(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "atomic"); - jsonDelete.setConsistencyInfo(consistencyInfo); - Response response = data.deleteFromTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, null, keyspaceName, tableName, info); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test7_dropTable() throws Exception { - System.out.println("Testing drop table"); - createTable(); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "atomic"); - jsonTable.setConsistencyInfo(consistencyInfo); - Response response = data.dropTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, keyspaceName, tableName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - } - - @Test - public void test7_dropTable_nullTablename() throws Exception { - System.out.println("Testing drop table w/ null tablename"); - createTable(); - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - consistencyInfo.put("type", "atomic"); - jsonTable.setConsistencyInfo(consistencyInfo); - Response response = data.dropTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, keyspaceName, null); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - - @Test - public void test8_deleteKeyspace() throws Exception { - System.out.println("Testing drop keyspace"); - - JsonKeySpace jsonKeyspace = new JsonKeySpace(); - Map consistencyInfo = new HashMap<>(); - Map replicationInfo = new HashMap<>(); - consistencyInfo.put("type", "eventual"); - replicationInfo.put("class", "SimpleStrategy"); - replicationInfo.put("replication_factor", 1); - jsonKeyspace.setConsistencyInfo(consistencyInfo); - jsonKeyspace.setDurabilityOfWrites("true"); - jsonKeyspace.setKeyspaceName("TestApp1"); - jsonKeyspace.setReplicationInfo(replicationInfo); - Response response = data.dropKeySpace("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", authorization, - appName, keyspaceName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - private static void createKeyspace() throws Exception { - // shouldn't really be doing this here, but create keyspace is currently turned off - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString(CassandraCQL.createKeySpace); - MusicCore.eventualPut(query); - - boolean isAAF = false; - String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); - query = new PreparedQueryObject(); - query.appendQueryString("INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); - query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - MusicCore.eventualPut(query); - } - - private void clearAllTablesFromKeyspace() throws MusicServiceException { - ArrayList tableNames = new ArrayList<>(); - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString( - "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '" + keyspaceName + "';"); - ResultSet rs = MusicCore.get(query); - for (Row row : rs) { - tableNames.add(row.getString("table_name")); - } - for (String table : tableNames) { - query = new PreparedQueryObject(); - query.appendQueryString("DROP TABLE " + keyspaceName + "." + table); - MusicCore.eventualPut(query); - } - } - - /** - * Create a table {@link tableName} in {@link keyspaceName} - * - * @throws Exception - */ - private void createTable() throws Exception { - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("binary", "blob"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableName); - jsonTable.setFields(fields); - // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableName); - } - - /** - * Create table {@link createTable} and insert into said table - * - * @throws Exception - */ - private void createAndInsertIntoTable() throws Exception { - createTable(); - - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname"); - values.put("emp_salary", 500); - values.put("binary", "binarydatahere"); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - } -} diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java deleted file mode 100644 index e9321d25..00000000 --- a/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java +++ /dev/null @@ -1,768 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mindrot.jbcrypt.BCrypt; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonLeasedLock; -import org.onap.music.datastore.jsonobjects.JsonLock; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.lockingservice.cassandra.CassaLockStore; -import org.onap.music.lockingservice.cassandra.LockType; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.rest.RestMusicDataAPI; -import org.onap.music.rest.RestMusicLocksAPI; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.sun.jersey.core.util.Base64; -import com.sun.jersey.core.util.MultivaluedMapImpl; - -@RunWith(MockitoJUnitRunner.class) -public class TstRestMusicLockAPI { - - - @Mock - UriInfo info; - - RestMusicLocksAPI lock = new RestMusicLocksAPI(); - RestMusicDataAPI data = new RestMusicDataAPI(); - static PreparedQueryObject testObject; - - static String appName = "TestApp"; - static String userId = "TestUser"; - static String password = "TestPassword"; - static String authData = userId + ":" + password; - static String wrongAuthData = userId + ":" + "pass"; - static String authorization = new String(Base64.encode(authData.getBytes())); - static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes())); - static boolean isAAF = false; - static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6"); - static String keyspaceName = "testcassa"; - static String tableName = "employees"; - static String onboardUUID = null; - static String lockName = "testcassa.employees.testname"; - - @BeforeClass - public static void init() throws Exception { - System.out.println("Testing RestMusicLock class"); - try { - createKeyspace(); - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage()); - } - } - - @After - public void afterEachTest() throws MusicServiceException { - clearAllTablesFromKeyspace(); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - testObject = new PreparedQueryObject(); - testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName); - MusicCore.eventualPut(testObject); - } - - @SuppressWarnings("unchecked") - @Test - public void test_createLockReference() throws Exception { - System.out.println("Testing create lockref"); - createAndInsertIntoTable(); - Response response = lock.createLockReference(lockName, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", null, null, appName); - Map respMap = (Map) response.getEntity(); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - assertTrue(respMap.containsKey("lock")); - assertTrue(((Map) respMap.get("lock")).containsKey("lock")); - } - - @Test - public void test_createBadLockReference() throws Exception { - System.out.println("Testing create bad lockref"); - createAndInsertIntoTable(); - Response response = lock.createLockReference("badlock", "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", null, null, appName); - Map respMap = (Map) response.getEntity(); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test_createReadLock() throws Exception { - System.out.println("Testing create read lockref"); - createAndInsertIntoTable(); - JsonLock jsonLock = createJsonLock(LockType.READ); - Response response = lock.createLockReference(lockName, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", jsonLock, null, appName); - Map respMap = (Map) response.getEntity(); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - assertTrue(respMap.containsKey("lock")); - assertTrue(((Map) respMap.get("lock")).containsKey("lock")); - } - - @Test - public void test_createWriteLock() throws Exception { - System.out.println("Testing create read lockref"); - createAndInsertIntoTable(); - JsonLock jsonLock = createJsonLock(LockType.WRITE); - Response response = lock.createLockReference(lockName, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", jsonLock, null, appName); - Map respMap = (Map) response.getEntity(); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - - assertEquals(200, response.getStatus()); - assertTrue(respMap.containsKey("lock")); - assertTrue(((Map) respMap.get("lock")).containsKey("lock")); - } - - @Test - public void test_accquireLock() throws Exception { - System.out.println("Testing acquire lock"); - createAndInsertIntoTable(); - String lockRef = createLockReference(); - - Response response = - lock.accquireLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - @Test - public void test_acquireReadLock() throws Exception { - System.out.println("Testing acquire read lock"); - createAndInsertIntoTable(); - String lockRef = createLockReference(LockType.READ); - String lockRef2 = createLockReference(LockType.READ); - - Response response = - lock.accquireLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - response = - lock.accquireLock(lockRef2, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - @Test - public void test_acquireReadLockaFail() throws Exception { - System.out.println("Testing acquire read lock"); - createAndInsertIntoTable(); - String lockRef = createLockReference(LockType.WRITE); - String lockRef2 = createLockReference(LockType.READ); - - Response response = - lock.accquireLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - response = - lock.accquireLock(lockRef2, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_writeWReadLock() throws Exception { - System.out.println("Testing writing with a read lock"); - createAndInsertIntoTable(); - String lockRef = createLockReference(LockType.READ); - - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("emp_salary", 2500); - consistencyInfo.put("type", "critical"); - consistencyInfo.put("lockId", lockRef); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName(tableName); - jsonUpdate.setValues(values); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testname"); - Mockito.when(info.getQueryParameters()).thenReturn(row); - - Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, keyspaceName, tableName, info); - - assertEquals(400, response.getStatus()); - } - - @Test - public void test_writeWWriteLock() throws Exception { - System.out.println("Testing writing with a read lock"); - createAndInsertIntoTable(); - String lockRef = createLockReference(LockType.WRITE); - - JsonUpdate jsonUpdate = new JsonUpdate(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("emp_salary", 2500); - consistencyInfo.put("type", "critical"); - consistencyInfo.put("lockId", lockRef); - jsonUpdate.setConsistencyInfo(consistencyInfo); - jsonUpdate.setKeyspaceName(keyspaceName); - jsonUpdate.setTableName(tableName); - jsonUpdate.setValues(values); - MultivaluedMap row = new MultivaluedMapImpl(); - row.add("emp_name", "testname"); - Mockito.when(info.getQueryParameters()).thenReturn(row); - - Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonUpdate, keyspaceName, tableName, info); - - assertEquals(200, response.getStatus()); - } - - @Test - public void test_accquireLockWLease() throws Exception { - System.out.println("Testing acquire lock with lease"); - createAndInsertIntoTable(); - String lockRef = createLockReference(); - - JsonLeasedLock jsonLock = new JsonLeasedLock(); - jsonLock.setLeasePeriod(10000); // 10 second lease period? - Response response = lock.accquireLockWithLease(jsonLock, lockRef, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - @Test - public void test_accquireBadLockWLease() throws Exception { - System.out.println("Testing acquire bad lock ref with lease"); - createAndInsertIntoTable(); - String lockRef = createLockReference(); - - JsonLeasedLock jsonLock = new JsonLeasedLock(); - jsonLock.setLeasePeriod(10000); // 10 second lease period? - Response response = lock.accquireLockWithLease(jsonLock, "badlock", "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_accquireBadLock() throws Exception { - System.out.println("Testing acquire lock that is not lock-holder"); - createAndInsertIntoTable(); - // This is required to create an initial loc reference. - String lockRef1 = createLockReference(); - // This will create the next lock reference, whcih will not be avalale yet. - String lockRef2 = createLockReference(); - - Response response = lock.accquireLock(lockRef2, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_accquireBadLockRef() throws Exception { - System.out.println("Testing acquire bad lock ref"); - createAndInsertIntoTable(); - // This is required to create an initial loc reference. - String lockRef1 = createLockReference(); - - Response response = lock.accquireLock("badlockref", "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_currentLockHolder() throws Exception { - System.out.println("Testing get current lock holder"); - createAndInsertIntoTable(); - - String lockRef = createLockReference(); - - Response response = - lock.enquireLock(lockName, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - Map respMap = (Map) response.getEntity(); - assertEquals(lockRef, ((Map) respMap.get("lock")).get("lock-holder")); - } - - @Test - public void test_nocurrentLockHolder() throws Exception { - System.out.println("Testing get current lock holder w/ bad lockref"); - createAndInsertIntoTable(); - - Response response = - lock.enquireLock(lockName, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_badcurrentLockHolder() throws Exception { - System.out.println("Testing get current lock holder w/ bad lockref"); - createAndInsertIntoTable(); - - String lockRef = createLockReference(); - - Response response = - lock.enquireLock("badlock", "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_holders() throws Exception { - System.out.println("Testing holders api"); - createAndInsertIntoTable(); - - String lockRef = createLockReference(); - - Response response = - lock.currentLockHolder(lockName, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - Map respMap = (Map) response.getEntity(); - assertEquals(lockRef, ((Map) respMap.get("lock")).get("lock-holder").get(0)); - } - - @Test - public void test_holdersbadRef() throws Exception { - System.out.println("Testing holders api w/ bad lockref"); - createAndInsertIntoTable(); - - String lockRef = createLockReference(); - - Response response = - lock.currentLockHolder("badname", "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_unLock() throws Exception { - System.out.println("Testing unlock"); - createAndInsertIntoTable(); - String lockRef = createLockReference(); - - Response response = - lock.unLock(lockRef, "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - @Test - public void test_unLockBadRef() throws Exception { - System.out.println("Testing unlock w/ bad lock ref"); - createAndInsertIntoTable(); - String lockRef = createLockReference(); - - Response response = - lock.unLock("badref", "1", "1", authorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @Test - public void test_getLockState() throws Exception { - System.out.println("Testing get lock state"); - createAndInsertIntoTable(); - - String lockRef = createLockReference(); - - Response response = lock.currentLockState(lockName, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - Map respMap = (Map) response.getEntity(); - assertEquals(lockRef, ((Map) respMap.get("lock")).get("lock-holder")); - } - - @Test - public void test_getLockStateBadRef() throws Exception { - System.out.println("Testing get lock state w/ bad ref"); - createAndInsertIntoTable(); - - String lockRef = createLockReference(); - - Response response = lock.currentLockState("badname", "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(400, response.getStatus()); - } - - @SuppressWarnings("unchecked") - @Test - public void test_deadlock() throws Exception { - System.out.println("Testing deadlock"); - createAndInsertIntoTable(); - insertAnotherIntoTable(); - - // Process 1 creates and acquires a lock on row 1 - JsonLock jsonLock = createJsonLock(LockType.WRITE); - Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process1", appName); - Map respMapCreate1 = (Map) responseCreate1.getEntity(); - String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); - - Response responseAcquire1 = - lock.accquireLock(lockRefCreate1, "1", "1", authorization, "abc66001-d857-4e90-b1e5-df98a3d40ce6", appName); - - // Process 2 creates and acquires a lock on row 2 - Response responseCreate2 = lock.createLockReference(lockName + "2", "1", "1", authorization, - "abcde002-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process2", appName); - Map respMapCreate2 = (Map) responseCreate2.getEntity(); - String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); - - Response responseAcquire2 = - lock.accquireLock(lockRefCreate2, "1", "1", authorization, "abc66002-d857-4e90-b1e5-df98a3d40ce6", appName); - - // Process 2 creates a lock on row 1 - Response responseCreate3 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde003-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process2", appName); - - // Process 1 creates a lock on row 2, causing deadlock - Response responseCreate4 = lock.createLockReference(lockName + "2", "1", "1", authorization, - "abcde004-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process1", appName); - Map respMapCreate4 = (Map) responseCreate4.getEntity(); - - System.out.println("Status: " + responseCreate4.getStatus() + ". Entity " + responseCreate4.getEntity()); - assertEquals(400, responseCreate4.getStatus()); - assertTrue(respMapCreate4.containsKey("error")); - assertTrue( ((String)respMapCreate4.get("error")).toLowerCase().indexOf("deadlock") > -1 ); - } - - - @SuppressWarnings("unchecked") - @Test - public void test_lockPromotion() throws Exception { - System.out.println("Testing lock promotion"); - createAndInsertIntoTable(); - insertAnotherIntoTable(); - - // creates a lock 1 - JsonLock jsonLock = createJsonLock(LockType.READ); - Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLock, "process1", appName); - Map respMapCreate1 = (Map) responseCreate1.getEntity(); - String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); - - Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); - System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); - - assertEquals(200, respMapPromote.getStatus()); - } - - @SuppressWarnings("unchecked") - @Test - public void test_lockPromotionReadWrite() throws Exception { - System.out.println("Testing lock promotion with read and writes"); - createAndInsertIntoTable(); - insertAnotherIntoTable(); - - // creates a lock 1 - JsonLock jsonLockRead = createJsonLock(LockType.READ); - Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); - Map respMapCreate1 = (Map) responseCreate1.getEntity(); - String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); - - JsonLock jsonLockWrite = createJsonLock(LockType.WRITE); - Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockWrite, "process1", appName); - Map respMapCreate2 = (Map) responseCreate2.getEntity(); - String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); - - Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); - System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); - - assertEquals(200, respMapPromote.getStatus()); - } - - @SuppressWarnings("unchecked") - @Test - public void test_lockPromotionWriteRead() throws Exception { - System.out.println("Testing lock promotion with reads not at top of queue"); - createAndInsertIntoTable(); - insertAnotherIntoTable(); - - // creates a lock 1 - JsonLock jsonLockWrite = createJsonLock(LockType.WRITE); - Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockWrite, "process1", appName); - Map respMapCreate2 = (Map) responseCreate2.getEntity(); - String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); - - // creates a lock 2 - JsonLock jsonLockRead = createJsonLock(LockType.READ); - Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); - Map respMapCreate1 = (Map) responseCreate1.getEntity(); - String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); - - Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); - System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); - - assertEquals(200, respMapPromote.getStatus()); - } - - @SuppressWarnings("unchecked") - @Test - public void test_lockPromotion2Reads() throws Exception { - System.out.println("Testing lock promotion w/ 2 ReadLocks"); - createAndInsertIntoTable(); - insertAnotherIntoTable(); - - // creates a lock 1 - JsonLock jsonLockRead = createJsonLock(LockType.READ); - Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); - Map respMapCreate1 = (Map) responseCreate1.getEntity(); - String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); - - Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); - Map respMapCreate2 = (Map) responseCreate1.getEntity(); - String lockRefCreate2 = ((Map) respMapCreate1.get("lock")).get("lock"); - - Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); - System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); - - assertEquals(400, respMapPromote.getStatus()); - } - - @SuppressWarnings("unchecked") - @Test - public void test_2lockPromotions() throws Exception { - System.out.println("Testing 2 lock promotions"); - createAndInsertIntoTable(); - insertAnotherIntoTable(); - - // creates a lock 1 - JsonLock jsonLockRead = createJsonLock(LockType.READ); - Response responseCreate1 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); - Map respMapCreate1 = (Map) responseCreate1.getEntity(); - String lockRefCreate1 = ((Map) respMapCreate1.get("lock")).get("lock"); - - Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization, - "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName); - Map respMapCreate2 = (Map) responseCreate2.getEntity(); - String lockRefCreate2 = ((Map) respMapCreate2.get("lock")).get("lock"); - - Response respMapPromote = lock.promoteLock(lockRefCreate1, "1", "1", authorization); - System.out.println("Status: " + respMapPromote.getStatus() + ". Entity " + respMapPromote.getEntity()); - - assertEquals(400, respMapPromote.getStatus()); - - Response respMap2Promote = lock.promoteLock(lockRefCreate2, "1", "1", authorization); - System.out.println("Status: " + respMap2Promote.getStatus() + ". Entity " + respMap2Promote.getEntity()); - - assertEquals(400, respMapPromote.getStatus()); - } - - - - // Ignoring since this is now a duplicate of delete lock ref. - @Test - @Ignore - public void test_deleteLock() throws Exception { - System.out.println("Testing get lock state"); - createAndInsertIntoTable(); - - String lockRef = createLockReference(); - - Response response = lock.deleteLock(lockName, "1", "1", - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", authorization, appName); - System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - assertEquals(200, response.getStatus()); - } - - /** - * Create table and lock reference - * - * @return the lock ref created - * @throws Exception - */ - @SuppressWarnings("unchecked") - private String createLockReference() throws Exception { - Response response = lock.createLockReference(lockName, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", null, null, appName); - Map respMap = (Map) response.getEntity(); - return ((Map) respMap.get("lock")).get("lock"); - } - - /** - * Create table and lock reference - * - * @return the lock ref created - * @throws Exception - */ - @SuppressWarnings("unchecked") - private String createLockReference(LockType lockType) throws Exception { - JsonLock jsonLock = createJsonLock(lockType); - Response response = lock.createLockReference(lockName, "1", "1", authorization, - "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", jsonLock, null, appName); - Map respMap = (Map) response.getEntity(); - return ((Map) respMap.get("lock")).get("lock"); - } - - private static void createKeyspace() throws Exception { - // shouldn't really be doing this here, but create keyspace is currently turned off - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString(CassandraCQL.createKeySpace); - MusicCore.eventualPut(query); - - boolean isAAF = false; - String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); - query = new PreparedQueryObject(); - query.appendQueryString("INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); - query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); - query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - //CachingUtil.updateMusicCache(keyspaceName, appName); - //CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd); - MusicCore.eventualPut(query); - } - - private void clearAllTablesFromKeyspace() throws MusicServiceException { - ArrayList tableNames = new ArrayList<>(); - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString( - "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '" + keyspaceName + "';"); - ResultSet rs = MusicCore.get(query); - for (Row row : rs) { - tableNames.add(row.getString("table_name")); - } - for (String table : tableNames) { - query = new PreparedQueryObject(); - query.appendQueryString("DROP TABLE " + keyspaceName + "." + table); - MusicCore.eventualPut(query); - } - } - - /** - * Create a table {@link tableName} in {@link keyspaceName} - * - * @throws Exception - */ - private void createTable() throws Exception { - JsonTable jsonTable = new JsonTable(); - Map consistencyInfo = new HashMap<>(); - Map fields = new HashMap<>(); - fields.put("uuid", "text"); - fields.put("emp_name", "text"); - fields.put("emp_salary", "varint"); - fields.put("PRIMARY KEY", "(emp_name)"); - consistencyInfo.put("type", "eventual"); - jsonTable.setConsistencyInfo(consistencyInfo); - jsonTable.setKeyspaceName(keyspaceName); - jsonTable.setPrimaryKey("emp_name"); - jsonTable.setTableName(tableName); - jsonTable.setFields(fields); - // Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion()); - Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonTable, keyspaceName, tableName); - } - - /** - * Create table {@link createTable} and insert into said table - * - * @throws Exception - */ - private void createAndInsertIntoTable() throws Exception { - createTable(); - - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname"); - values.put("emp_salary", 500); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - } - - private void insertAnotherIntoTable() throws Exception { - createTable(); - - JsonInsert jsonInsert = new JsonInsert(); - Map consistencyInfo = new HashMap<>(); - Map values = new HashMap<>(); - values.put("uuid", "cccccccc-d857-4e90-b1e5-df98a3d40cd6"); - values.put("emp_name", "testname2"); - values.put("emp_salary", 700); - consistencyInfo.put("type", "eventual"); - jsonInsert.setConsistencyInfo(consistencyInfo); - jsonInsert.setKeyspaceName(keyspaceName); - jsonInsert.setTableName(tableName); - jsonInsert.setValues(values); - Response response = data.insertIntoTable("1", "1", "1", "abcdef00-d857-4e90-b1e5-df98a3d40ce6", appName, - authorization, jsonInsert, keyspaceName, tableName); - } - - private JsonLock createJsonLock(LockType lockType) { - JsonLock jsonLock = new JsonLock(); - jsonLock.setLockType(lockType); - return jsonLock; - } - -} \ No newline at end of file diff --git a/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java b/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java deleted file mode 100644 index b578bd66..00000000 --- a/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests.authentication; - -import static org.junit.Assert.*; -import java.util.ArrayList; -import java.util.List; -import javax.servlet.ServletRequest; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.aaf.cadi.CadiWrap; -import org.onap.aaf.cadi.Permission; -import org.onap.aaf.cadi.aaf.AAFPermission; -import org.onap.music.authentication.AuthUtil; - -public class AuthUtilTest { - - @Test - public void testGetAAFPermissions() { - CadiWrap cw = Mockito.mock(CadiWrap.class); - List permList = new ArrayList(); - Permission perm1 = Mockito.mock(AAFPermission.class); - permList.add(perm1); - Mockito.when(cw.getPermissions(Mockito.any())).thenReturn(permList); - - List returnedPerm = AuthUtil.getAAFPermissions(cw); - - assertEquals(perm1, returnedPerm.get(0)); - } - - @Test - public void testDecodeFunctionCode() throws Exception { - String toDecode = "some%2dthing.something.%2a"; - String decoded = AuthUtil.decodeFunctionCode(toDecode); - - assertEquals("some-thing.something.*", decoded); - } - - @Test - public void testIsAccessAllowed() throws Exception { - System.out.println("Request perms"); - assertTrue(AuthUtil.isAccessAllowed(createRequest("*", "*"), "testns")); - } - - @Test - public void testIsAccessNotAllowed() throws Exception { - System.out.println("Request to write when have read perms"); - assertFalse(AuthUtil.isAccessAllowed(createRequest("POST", "GET"), "testns")); - } - - @Test - public void testIsAccessAllowedNullRequest() { - try { - assertFalse(AuthUtil.isAccessAllowed(null, "namespace")); - fail("Should throw exception"); - } catch (Exception e) { - } - } - - @Test - public void testIsAccessAllowedNullNamespace() { - try { - assertFalse(AuthUtil.isAccessAllowed(createRequest(), null)); - fail("Should throw exception"); - } catch (Exception e) { - } - } - - @Test - public void testIsAccessAllowedEmptyNamespace() { - try { - assertFalse(AuthUtil.isAccessAllowed(createRequest(), "")); - fail("Should throw exception"); - } catch (Exception e) { - } - } - - /** - * - * @param permRequested 'PUT', 'POST', 'GET', or 'DELETE' - * @param permGranted '*' or 'GET' - * @return - */ - private ServletRequest createRequest(String permRequested, String permGranted) { - CadiWrap cw = Mockito.mock(CadiWrap.class); - List permList = new ArrayList(); - AAFPermission perm1 = Mockito.mock(AAFPermission.class); - Mockito.when(perm1.getType()).thenReturn("testns"); - Mockito.when(perm1.getKey()).thenReturn("org.onap.music.api.user.access|testns|" + permGranted); - - permList.add(perm1); - Mockito.when(cw.getPermissions(Mockito.any())).thenReturn(permList); - Mockito.when(cw.getRequestURI()).thenReturn("/v2/locks/create/testns.MyTable.Field1"); - Mockito.when(cw.getContextPath()).thenReturn("/v2/locks/create"); - Mockito.when(cw.getMethod()).thenReturn(permRequested); - - return cw; - } - - private ServletRequest createRequest() { - return createRequest("POST","*"); - } -} diff --git a/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java b/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java deleted file mode 100644 index b432072a..00000000 --- a/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests.authentication; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; -import org.onap.music.authentication.AuthorizationError; - -public class AuthorizationErrorTest { - - private AuthorizationError authorizationError; - - @Before - public void setUp() { - authorizationError = new AuthorizationError(); - } - - @Test - public void testResponseCode() { - authorizationError.setResponseCode(400); - assertEquals(400, authorizationError.getResponseCode()); - } - - @Test - public void testResponseMessage() { - authorizationError.setResponseMessage("ResponseMessage"); - assertEquals("ResponseMessage", authorizationError.getResponseMessage()); - } -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java deleted file mode 100644 index 7f6af4c5..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests.jsonobjects; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import org.onap.music.datastore.jsonobjects.JSONObject; - -public class JSONObjectTest { - private JSONObject jsonObject; - - @Before - public void setUp() { - jsonObject = new JSONObject(); - } - - @Test - public void testGetSetData() { - jsonObject.setData("data"); - Assert.assertEquals("data", jsonObject.getData()); - } -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java deleted file mode 100644 index a069b81d..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests.jsonobjects; - -import static org.junit.Assert.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonDelete; - -public class JsonDeleteTest { - - JsonDelete jd = null; - - @Before - public void init() { - jd = new JsonDelete(); - } - - @Test - public void testGetConditions() { - Map mapSo = new HashMap<>(); - mapSo.put("key1","one"); - mapSo.put("key2","two"); - jd.setConditions(mapSo); - assertEquals("one",jd.getConditions().get("key1")); - } - - @Test - public void testGetConsistencyInfo() { - Map mapSs = new HashMap<>(); - mapSs.put("key3","three"); - mapSs.put("key4","four"); - jd.setConsistencyInfo(mapSs); - assertEquals("three",jd.getConsistencyInfo().get("key3")); - } - - @Test - public void testGetColumns() { - List ary = new ArrayList<>(); - ary.add("e1"); - ary.add("e2"); - ary.add("e3"); - jd.setColumns(ary); - assertEquals("e1",jd.getColumns().get(0)); - } - - @Test - public void testGetTtl() { - jd.setTtl("2000"); - assertEquals("2000",jd.getTtl()); - } - - @Test - public void testGetTimestamp() { - jd.setTimestamp("20:00"); - assertEquals("20:00",jd.getTimestamp()); - - } - -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java deleted file mode 100644 index 4992af7b..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests.jsonobjects; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonInsert; - -public class JsonInsertTest { - - JsonInsert ji = new JsonInsert(); - - @Test - public void testGetKeyspaceName() { - ji.setKeyspaceName("keyspace"); - assertEquals("keyspace",ji.getKeyspaceName()); - } - - @Test - public void testGetTableName() { - ji.setTableName("table"); - assertEquals("table",ji.getTableName()); - } - - @Test - public void testGetConsistencyInfo() { - Map cons = new HashMap<>(); - cons.put("test","true"); - ji.setConsistencyInfo(cons); - assertEquals("true",ji.getConsistencyInfo().get("test")); - } - - @Test - public void testGetTtl() { - ji.setTtl("ttl"); - assertEquals("ttl",ji.getTtl()); - } - - @Test - public void testGetTimestamp() { - ji.setTimestamp("10:30"); - assertEquals("10:30",ji.getTimestamp()); - } - - @Test - public void testGetValues() { - Map cons = new HashMap<>(); - cons.put("val1","one"); - cons.put("val2","two"); - ji.setValues(cons); - assertEquals("one",ji.getValues().get("val1")); - } - - @Test - public void testGetRowSpecification() { - Map cons = new HashMap<>(); - cons.put("val1","one"); - cons.put("val2","two"); - ji.setRowSpecification(cons); - assertEquals("two",ji.getRowSpecification().get("val2")); - } - - @Test - public void testSerialize() { - Map cons = new HashMap<>(); - cons.put("val1","one"); - cons.put("val2","two"); - ji.setTimestamp("10:30"); - ji.setRowSpecification(cons); - byte[] test1 = ji.serialize(); - byte[] ji1 = SerializationUtils.serialize(ji); - assertArrayEquals(ji1,test1); - } - - @Test - public void testObjectMap() - { - Map map = new HashMap<>(); - ji.setObjectMap(map); - assertEquals(map, ji.getObjectMap()); - } - -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java deleted file mode 100644 index 0f4abd7c..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests.jsonobjects; - -import static org.junit.Assert.*; -import java.util.HashMap; -import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; - -public class JsonKeySpaceTest { - - JsonKeySpace jk = null; - - - @Before - public void init() { - jk = new JsonKeySpace(); - } - - - - @Test - public void testGetConsistencyInfo() { - Map mapSs = new HashMap<>(); - mapSs.put("k1", "one"); - jk.setConsistencyInfo(mapSs); - assertEquals("one",jk.getConsistencyInfo().get("k1")); - } - - @Test - public void testGetReplicationInfo() { - Map mapSo = new HashMap<>(); - mapSo.put("k1", "one"); - jk.setReplicationInfo(mapSo); - assertEquals("one",jk.getReplicationInfo().get("k1")); - - } - - @Test - public void testGetDurabilityOfWrites() { - jk.setDurabilityOfWrites("1"); - assertEquals("1",jk.getDurabilityOfWrites()); - } - - @Test - public void testGetKeyspaceName() { - jk.setKeyspaceName("Keyspace"); - assertEquals("Keyspace",jk.getKeyspaceName()); - } - -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java deleted file mode 100644 index b7dfa075..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR 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.music.unittests.jsonobjects; - -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonLeasedLock; - -public class JsonLeasedLockTest { - - JsonLeasedLock jl = null; - - @Before - public void init() { - jl = new JsonLeasedLock(); - } - - - @Test - public void testGetLeasePeriod() { - long lease = 20000; - jl.setLeasePeriod(lease); - assertEquals(lease,jl.getLeasePeriod()); - } - -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java deleted file mode 100644 index 37d1787a..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2018-2019 IBM - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests.jsonobjects; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonSelect; - -public class JsonSelectTest { - - @Test - public void testGetConsistencyInfo() { - JsonSelect js = new JsonSelect(); - Map mapSs = new HashMap<>(); - mapSs.put("k1", "one"); - js.setConsistencyInfo(mapSs); - assertEquals("one", js.getConsistencyInfo().get("k1")); - } - - @Test - public void testSerialize() throws IOException { - JsonSelect js = new JsonSelect(); - Map mapSs = new HashMap<>(); - mapSs.put("Key", "Value"); - js.setConsistencyInfo(mapSs); - js.serialize(); - } - -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java deleted file mode 100644 index 4e3b4629..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests.jsonobjects; - -import static org.junit.Assert.*; -import java.util.HashMap; -import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonTable; - -public class JsonTableTest { - - JsonTable jt = null; - - @Before - public void init() { - jt = new JsonTable(); - } - - @Test - public void testGetConsistencyInfo() { - Map mapSs = new HashMap<>(); - mapSs.put("k1", "one"); - jt.setConsistencyInfo(mapSs); - assertEquals("one",jt.getConsistencyInfo().get("k1")); - } - - @Test - public void testGetProperties() { - Map properties = new HashMap<>(); - properties.put("k1", "one"); - jt.setProperties(properties); - } - - @Test - public void testGetFields() { - Map fields = new HashMap<>(); - fields.put("k1", "one"); - jt.setFields(fields); - assertEquals("one",jt.getFields().get("k1")); - } - - @Test - public void testGetKeyspaceName() { - String keyspace = "keyspace"; - jt.setKeyspaceName(keyspace); - assertEquals(keyspace,jt.getKeyspaceName()); - } - - @Test - public void testGetTableName() { - String table = "table"; - jt.setTableName(table); - assertEquals(table,jt.getTableName()); - } - - @Test - public void testGetClusteringOrder() { - String clusteringOrder = "clusteringOrder"; - jt.setClusteringOrder(clusteringOrder); - assertEquals(clusteringOrder,jt.getClusteringOrder()); - } - - @Test - public void testGetPrimaryKey() { - String primaryKey = "primaryKey"; - jt.setPrimaryKey(primaryKey); - assertEquals(primaryKey,jt.getPrimaryKey()); - } - - @Test - public void testFilteringKey() { - jt.setFilteringKey("FilteringKey"); - assertEquals("FilteringKey",jt.getFilteringKey()); - } - -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java deleted file mode 100644 index e00cb463..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2018 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - *******************************************************************************/ - -package org.onap.music.unittests.jsonobjects; - -import static org.junit.Assert.*; -import java.util.HashMap; -import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonUpdate; - -public class JsonUpdateTest { - - JsonUpdate ju = null; - - @Before - public void init() { - ju = new JsonUpdate(); - } - - - @Test - public void testGetConditions() { - Map mapSo = new HashMap<>(); - mapSo.put("key1","one"); - mapSo.put("key2","two"); - ju.setConditions(mapSo); - assertEquals("one",ju.getConditions().get("key1")); - } - - @Test - public void testGetRow_specification() { - Map mapSo = new HashMap<>(); - mapSo.put("key1","one"); - mapSo.put("key2","two"); - ju.setRow_specification(mapSo); - assertEquals("one",ju.getRow_specification().get("key1")); - } - - @Test - public void testGetKeyspaceName() { - String keyspace = "keyspace"; - ju.setKeyspaceName(keyspace); - assertEquals(keyspace,ju.getKeyspaceName()); - } - - @Test - public void testGetTableName() { - String table = "table"; - ju.setTableName(table); - assertEquals(table,ju.getTableName()); - } - - @Test - public void testGetConsistencyInfo() { - Map mapSs = new HashMap<>(); - mapSs.put("k1", "one"); - ju.setConsistencyInfo(mapSs); - assertEquals("one",ju.getConsistencyInfo().get("k1")); - } - - @Test - public void testGetTtl() { - ju.setTtl("2000"); - assertEquals("2000",ju.getTtl()); - } - - @Test - public void testGetTimestamp() { - ju.setTimestamp("20:00"); - assertEquals("20:00",ju.getTimestamp()); - - } - - @Test - public void testGetValues() { - Map cons = new HashMap<>(); - cons.put("val1","one"); - cons.put("val2","two"); - ju.setValues(cons); - assertEquals("one",ju.getValues().get("val1")); - } - - @Test - public void testSerialize() { - assertTrue(ju.serialize() instanceof byte[]); - } - -} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java deleted file mode 100644 index ceda3f3a..00000000 --- a/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2019 IBM. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.unittests.jsonobjects; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; -import org.onap.music.eelf.healthcheck.MusicHealthCheck; - -public class MusicHealthCheckTest { - - private MusicHealthCheck musicHealthCheck; - - @Before - public void setUp() - { - musicHealthCheck= new MusicHealthCheck(); - } - - @Test - public void testCassandraHost() - { - musicHealthCheck.setCassandrHost("9042"); - assertEquals("9042", musicHealthCheck.getCassandrHost()); - } - -} diff --git a/src/test/resources/LICENSE.txt b/src/test/resources/LICENSE.txt deleted file mode 100644 index cc6cdea5..00000000 --- a/src/test/resources/LICENSE.txt +++ /dev/null @@ -1,24 +0,0 @@ - -The following license applies to all files in this and sub-directories. Licenses -are included in individual source files where appropriate, and if it differs -from this text, it supersedes this. Any file that does not have license text -defaults to being covered by this text; not all files support the addition of -licenses. -# -# ------------------------------------------------------------------------- -# Copyright (c) 2017 AT&T Intellectual Property -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ------------------------------------------------------------------------- -# \ No newline at end of file diff --git a/src/test/resources/Resources.properties b/src/test/resources/Resources.properties deleted file mode 100644 index 72269cb8..00000000 --- a/src/test/resources/Resources.properties +++ /dev/null @@ -1,50 +0,0 @@ -#============LICENSE_START========================================== -#org.onap.music -#=================================================================== -# Copyright (c) 2017 AT&T Intellectual Property -#=================================================================== -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -#============LICENSE_END============================================= -#==================================================================== -#Resource key=Error Code|Message text|Resolution text |Description text -LOADING_DEFAULT_LOG_CONFIGURATION=\ - EELF0001I|\ - Loading default logging configuration from system resource file "{0}"|\ - No external logging configurations were defined or found, So verify the default logging configuration from system resource file (../logback.xml). |\ - Loading default logging configuration from system resource file -LOADING_LOG_CONFIGURATION=EELF0002I|\ - Loading logging configuration from file "{0}"|\ - Verify the correct logging configuration file is loaded. |\ - Loading logging configuration for specific file -LOGGING_ALREADY_INITIALIZED=\ - EELF0003W|\ - Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration.|\ - Verify the container logging definitions to ensure they represent your desired logging configuration. |\ - Logging has already been initialized, check the container logging definitions to ensure they represent your desired logging configuration. -NO_LOG_CONFIGURATION=\ - EELF0004E|\ - No log configuration could be found or defaulted!|\ - No external and default logging configuration file. |\ - No log configuration could be found or defaulted! -SEARCHING_LOG_CONFIGURATION=\ - EELF0005I|\ - Searching path "{0}" for log configuration file "{1}"|\ - Verify the correct Path({user.home};etc;../etc) and filename (eelf.logging.file).|\ - Searching path for specific log configuration file. -UNSUPPORTED_LOGGING_FRAMEWORK=\ - EELF0006E|\ - An unsupported logging framework is bound to SLF4J. |\ - Verify your logging frameworks.|\ - An unsupported logging framework is bound to SLF4J. - diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties deleted file mode 100644 index 02e9c1a9..00000000 --- a/src/test/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.port=8080 -server.servlet.context-path=/MUSIC/rest \ No newline at end of file diff --git a/src/test/resources/cache.ccf b/src/test/resources/cache.ccf deleted file mode 100644 index e152ee8b..00000000 --- a/src/test/resources/cache.ccf +++ /dev/null @@ -1,62 +0,0 @@ -# DEFAULT CACHE REGION -jcs.default=DC -jcs.default.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes -jcs.default.cacheattributes.MaxObjects=1000 -jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache -jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes -jcs.default.elementattributes.IsEternal=true -jcs.default.elementattributes.IsSpool=true - -# PRE-DEFINED CACHE REGIONS -jcs.region.musicCache= -jcs.region.musicCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes -jcs.region.musicCache.cacheattributes.MaxObjects=1000 -jcs.region.musicCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache -jcs.region.musicCache.cacheattributes.UseMemoryShrinker=false -jcs.region.musicCache.cacheattributes.MaxMemoryIdleTime=3600 -jcs.region.musicCache.cacheattributes.ShrinkerInterval=60 -jcs.region.musicCache.cacheattributes.MaxSpoolPerRun=500 -jcs.region.musicCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes -jcs.region.musicCache.elementattributes.IsEternal=false - - -# PRE-DEFINED CACHE REGIONS -jcs.region.aafCache= -jcs.region.aafCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes -jcs.region.aafCache.cacheattributes.MaxObjects=1000 -jcs.region.aafCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache -jcs.region.aafCache.cacheattributes.UseMemoryShrinker=false -jcs.region.aafCache.cacheattributes.MaxMemoryIdleTime=3600 -jcs.region.aafCache.cacheattributes.ShrinkerInterval=60 -jcs.region.aafCache.cacheattributes.MaxSpoolPerRun=500 -jcs.region.aafCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes -jcs.region.aafCache.elementattributes.IsEternal=false - -# PRE-DEFINED CACHE REGIONS -jcs.region.appNameCache= -jcs.region.appNameCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes -jcs.region.appNameCache.cacheattributes.MaxObjects=1000 -jcs.region.appNameCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache -jcs.region.appNameCache.cacheattributes.UseMemoryShrinker=false -jcs.region.appNameCache.cacheattributes.MaxMemoryIdleTime=3600 -jcs.region.appNameCache.cacheattributes.ShrinkerInterval=60 -jcs.region.appNameCache.cacheattributes.MaxSpoolPerRun=500 -jcs.region.appNameCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes -jcs.region.appNameCache.elementattributes.IsEternal=false - -jcs.default=DC -jcs.default.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes -jcs.default.cacheattributes.MaxObjects=1000 -jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache -jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes -jcs.default.elementattributes.IsEternal=true -jcs.default.elementattributes.IsSpool=true - -jcs.region.eternalCache=DC -jcs.region.eternalCache.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes -jcs.region.eternalCache.cacheattributes.MaxObjects=1000 -jcs.region.eternalCache.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache -jcs.region.eternalCache.elementattributes=org.apache.commons.jcs.engine.ElementAttributes -jcs.region.eternalCache.elementattributes.IsEternal=true -jcs.region.eternalCache.elementattributes.IsSpool=true - diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml deleted file mode 100644 index 6bc5fd5e..00000000 --- a/src/test/resources/logback.xml +++ /dev/null @@ -1,302 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - ${logDirectory}/${generalLogName}.log - - - ${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip - 1GB - 5 - 5GB - - - ${applicationLoggerPattern} - - - - - 256 - true - - - - - - ${logDirectory}/${securityLogName}.log - - ${logDirectory}/${securityLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n - - - - - 256 - 0 - - - - - - - - - - ${logDirectory}/${auditLogName}.log - - ${logDirectory}/${auditLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - ${auditLoggerPattern} - - - - 256 - - - - - ${logDirectory}/${metricsLogName}.log - - ${logDirectory}/${metricsLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - - ${metricsLoggerPattern} - - - - - - 256 - - - - - ${logDirectory}/${errorLogName}.log - - ${logDirectory}/${errorLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - ${errorLoggerPattern} - - - - - 256 - - - - - ${debugLogDirectory}/${debugLogName}.log - - ${debugLogDirectory}/${debugLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - ${debugLoggerPattern} - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker deleted file mode 100644 index 1f0955d4..00000000 --- a/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker +++ /dev/null @@ -1 +0,0 @@ -mock-maker-inline diff --git a/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider b/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider deleted file mode 100644 index bc2f0992..00000000 --- a/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider +++ /dev/null @@ -1 +0,0 @@ -org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider diff --git a/src/test/resources/project.properties b/src/test/resources/project.properties deleted file mode 100644 index 199afa33..00000000 --- a/src/test/resources/project.properties +++ /dev/null @@ -1,4 +0,0 @@ -version=${project.version} -artifactId=${project.artifactId} -music.properties=/opt/app/music/etc/music.properties - -- cgit 1.2.3-korg